Sunday, 15 March 2015

Simple example of Google Analytics API usage

Publishing my old note, of how to use Google Analytics Core Reporting API (v2)

 
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;

import com.google.gdata.client.analytics.AnalyticsService;
import com.google.gdata.client.analytics.DataQuery;

import com.google.gdata.data.analytics.DataEntry;
import com.google.gdata.data.analytics.DataFeed;

public class MainDemo {

    private static final String APP_NAME = "DataOverTimeDemo";
    private static final String USERNAME = "ly@yourdomain.com";
    private static final String PASSWORD = "yourpass";
    private static final String TABLE_ID = "ga:12345381";
    public static final String DATA_URL = "https://www.googleapis.com/analytics/v2.4/data";

    public static void main(String args[]) {
        try {
            new MainDemo();
        } catch (FileNotFoundException e) {
            e.printStackTrace()
        }
    }

    public MainDemo() throws FileNotFoundException {

        DataQuery basicQuery = null;
        try {

            AnalyticsService analyticsService = new AnalyticsService(APP_NAME);
            analyticsService.setUserCredentials(USERNAME, PASSWORD);
            basicQuery = getBasicQuery(TABLE_ID);

            DataFeed basicData = null;
            basicData = analyticsService.getFeed(basicQuery, DataFeed.class);
            System.out.println("BASIC RESULTS" + basicData);
            System.out.println("----------- Data Feed Results ----------");
            // info about page visitors for specific time peiod
            for (DataEntry entry : basicData.getEntries()) {
                System.out.println("\nPage Title = "
                        + entry.stringValueOf("ga:pageTitle")
                        + "\nPage Path  = "
                        + entry.stringValueOf("ga:pagePath")
                        + "\nPage visits  = "
                        + entry.stringValueOf("ga:visitors"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DataQuery getBasicQuery(String tableId)
            throws MalformedURLException {
        DataQuery query = new DataQuery(new URL(DATA_URL));
        query.setIds(tableId);
        query.setStartDate("2009-04-01");
        query.setEndDate("2012-08-24");
        query.setDimensions("ga:pageTitle,ga:pagePath");
        query.setMetrics("ga:visitors");
        // query.setSort("-ga:pageviews");
        query.setMaxResults(100);
        query.setFilters("ga:pagePath=@customized/products/1447");
        return query;
    }
}


Useful links
Explorer
Core Reporting API (v2)

No comments:

Post a Comment