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


import com.northconcepts.datapipeline.core.DataReader;
import com.northconcepts.datapipeline.core.DataWriter;
import com.northconcepts.datapipeline.core.StreamWriter;
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)

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

        NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        DataReader reader = new GoogleAnalyticsReportReader(authorize(httpTransport), VIEW_ID)
                .addDateRange("14DaysAgo", "today")
        DataWriter writer = StreamWriter.newSystemOutWriter();, 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. 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