Hello Analytics API: Java quickstart for service accounts

This tutorial walks through the steps required to access a Google Analytics account, query the Analytics APIs, handle the API responses, and output the results. The Core Reporting API v3.0, Management API v3.0, and OAuth2.0 are used in this tutorial.

Step 1: Enable the Analytics API

To get started using Google Analytics API, you need to first use the setup tool, which guides you through creating a project in the Google API Console, enabling the API, and creating credentials.

Create a client ID

  1. Open the Service accounts page. If prompted, select a project.
  2. Click Create service account.
  3. In the Create service account window, type a name for the service account, and select Furnish a new private key. If you want to grant Google Apps domain-wide authority to the service account, also select Enable Google Apps Domain-wide Delegation. Then click Create.

Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. You are responsible for storing it securely.

Add service account to Google Analytics account

The newly created service account will have an email address, <projectId>-<uniqueId>@developer.gserviceaccount.com; Use this email address to add a user to the Google analytics account you want to access via the API. For this tutorial only Read & Analyze permissions are needed.

Step 2: Install the Google Client Library

To install the Google Analytics API Java Client, you must download a zip file containing all of the jars you need to extract and copy into your Java classpath.

  1. Download the Google Analytics Java client library, which is bundled as a ZIP file with all the required dependencies.
  2. Extract the ZIP file
  3. Add all of the JARs within the libs directory to your classpath.
  4. Add the google-api-services-analytics-v3-[version].jar jar to your classpath.

Step 3: Setup the sample

You'll need to create a single file named HelloAnalytics.java, which will contain the given sample code.

  1. Copy or download the following source code to HelloAnalytics.java.
  2. Move the previously downloaded client_secrets.p12 within the same directory as the sample code.
  3. Replace the values of the SERVICE_ACCOUNT_EMAIL and KEY_FILE_LOCATION with the appropriate values from the Developer Console.
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;

import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.Accounts;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Webproperties;

import java.io.File;
import java.io.IOException;


/**
 * A simple example of how to access the Google Analytics API using a service
 * account.
 */
public class HelloAnalytics {


  private static final String APPLICATION_NAME = "Hello Analytics";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static final String KEY_FILE_LOCATION = "/path/to/your.p12";
  private static final String SERVICE_ACCOUNT_EMAIL = "<SERVICE_ACCOUNT_EMAIL>@developer.gserviceaccount.com";
  public static void main(String[] args) {
    try {
      Analytics analytics = initializeAnalytics();

      String profile = getFirstProfileId(analytics);
      System.out.println("First Profile Id: "+ profile);
      printResults(getResults(analytics, profile));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static Analytics initializeAnalytics() throws Exception {
    // Initializes an authorized analytics service object.

    // Construct a GoogleCredential object with the service account email
    // and p12 file downloaded from the developer console.
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
        .setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
        .setServiceAccountScopes(AnalyticsScopes.all())
        .build();

    // Construct the Analytics service object.
    return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }


  private static String getFirstProfileId(Analytics analytics) throws IOException {
    // Get the first view (profile) ID for the authorized user.
    String profileId = null;

    // Query for the list of all accounts associated with the service account.
    Accounts accounts = analytics.management().accounts().list().execute();

    if (accounts.getItems().isEmpty()) {
      System.err.println("No accounts found");
    } else {
      String firstAccountId = accounts.getItems().get(0).getId();

      // Query for the list of properties associated with the first account.
      Webproperties properties = analytics.management().webproperties()
          .list(firstAccountId).execute();

      if (properties.getItems().isEmpty()) {
        System.err.println("No Webproperties found");
      } else {
        String firstWebpropertyId = properties.getItems().get(0).getId();

        // Query for the list views (profiles) associated with the property.
        Profiles profiles = analytics.management().profiles()
            .list(firstAccountId, firstWebpropertyId).execute();

        if (profiles.getItems().isEmpty()) {
          System.err.println("No views (profiles) found");
        } else {
          // Return the first (view) profile associated with the property.
          profileId = profiles.getItems().get(0).getId();
        }
      }
    }
    return profileId;
  }

  private static GaData getResults(Analytics analytics, String profileId) throws IOException {
    // Query the Core Reporting API for the number of sessions
    // in the past seven days.
    return analytics.data().ga()
        .get("ga:" + profileId, "7daysAgo", "today", "ga:sessions")
        .execute();
  }

  private static void printResults(GaData results) {
    // Parse the response from the Core Reporting API for
    // the profile name and number of sessions.
    if (results != null && !results.getRows().isEmpty()) {
      System.out.println("View (Profile) Name: "
        + results.getProfileInfo().getProfileName());
      System.out.println("Total Sessions: " + results.getRows().get(0).get(0));
    } else {
      System.out.println("No results found");
    }
  }
}

Step 4: Run the sample

After you have enabled the Analytics API, installed the Google APIs client library for Java, and set up the sample source code the sample is ready to run.

If you're using an IDE, make sure you have a default run target set to the HelloAnalytics class. Otherwise you can compile and run the application from the command line:

  1. Compile the sample using:
    javac -classpath /path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics.java
  2. Run the sample using:
    java -classpath ./:/path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics

When you finish these steps, the sample outputs the name of the authorized user's first Google Analytics view (profile) and the number of sessions for the last seven days.

With the authorized Analytics service object you can now run any of code samples found in the Management API reference docs. For example you could try changing the code to use the accountSummaries.list method.