Read Google Analytics views

Updated: Sep 3, 2023

This example shows how to retrieve and process Google Analytics view data. It simplifies accessing insights about website traffic, user behavior, and audience demographics from different Google Analytics views.

You can also reference these examples to get other analytical data from Google Analytics: Read Google Analytics Social InteractionsRead Google Analytics goal conversions.

 

Java Code Listing

package com.northconcepts.datapipeline.examples.google.analytics;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.analyticsreporting.v4.AnalyticsReportingScopes;
import com.northconcepts.datapipeline.core.DataReader;
import com.northconcepts.datapipeline.core.DataWriter;
import com.northconcepts.datapipeline.core.StreamWriter;
import com.northconcepts.datapipeline.google.analytics.GoogleAnalyticsReportReader;
import com.northconcepts.datapipeline.job.Job;

/**
 *
 * CLIENT_SECRET is your Service account credentials created in the Google Developer Console
 * and stored in the resources folder.
 */
public class ReadGoogleAnalyticsViews {

    private static final String CLIENT_SECRET = "/My Project-5ed7b6c44f35.json";
    private static final String APPLICATION_NAME = "Hello Analytics Reporting";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String VIEW_ID = "80548296";
    /** Authorizes the installed application to access user's protected data. */
    private static GoogleCredential authorize(NetHttpTransport httpTransport) throws Throwable {
        return GoogleCredential.fromStream(
                ReadGoogleAnalyticsViews.class.getResourceAsStream(CLIENT_SECRET), httpTransport, JSON_FACTORY)
                .createScoped(AnalyticsReportingScopes.all());
    }

    public static void main(String[] args) throws Throwable {

        NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        DataReader reader = new GoogleAnalyticsReportReader(authorize(httpTransport), VIEW_ID)
                .addDateRange("14DaysAgo", "today")
                .addDimension("ga:pageTitle")
                .addDimension("ga:landingPagePath")
                .addDimension("ga:exitPagePath")
                .addMetric("ga:pageValue")
                .addMetric("ga:entrances")
                .addMetric("ga:entranceRate")
                .addMetric("ga:pageViews")
                .addMetric("ga:pageviewsPerSession")
                .addMetric("ga:uniquePageviews")
                .addMetric("ga:timeOnPage")
                .addMetric("ga:avgTimeOnPage")
                .addMetric("ga:exits")
                .addMetric("ga:exitRate")
                .setApplicationName(APPLICATION_NAME);
        DataWriter writer = StreamWriter.newSystemOutWriter();

        Job.run(reader, writer);

    }
}

 

Code Walkthrough

  1. authorize() method authorizes the installed application to access the user's protected data. The resource class (ReadGoogleAnalyticsViews) and OAuth 2.0 scopes are also defined in this method body along with credentials.
  2. NetHttpTransport instance is created to thread-safe HTTP low-level transport.
  3. GoogleAnalyticsReportReader uses an API to get analytics of social interactions from Google. The constructor of the instance accepts GoogleCredentials and VIEW_ID. Additional parameters such as date range, dimensions, metrics, and application name are specified using corresponding methods.
  4. StreamWriter.newSystemOutWriter() method is used to create DataWriter instance.
  5. Job.run() method is used to transfer the data from reader to writer to print out the records on the console. See how to compile and run data pipeline jobs. 
Mobile Analytics