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.

  1. Step 1: Enable the Analytics API
  2. Step 2: Install the Google Client Library
  3. Step 3: Setup the sample
  4. Step 4: Run the sample

Step 1: Enable the Analytics API

To get started using Google Analytics API, you need to first create or select a project in the Google Developers Console and enable the API. Using this link guides you through the process and activates the Google Analytics API automatically.

Alternatively, you can activate the Google Analytics API yourself in the Developers Console by doing the following:

  1. Open the Credentials page.

In either case, you end up on the Credentials page and can create your project's credentials from here.

Create a client ID

From the Credentials page, click Create new Client ID under the OAuth heading to create your OAuth 2.0 credentials.

  1. For the APPLICATION TYPE select Service account.
  2. Click Create Client ID.
  3. For the KEY TYPE select P12 key.
  4. A dialog box appears. To proceed, click Okay, got it.

Your new Public/Private key pair is generated and downloaded to your machine; Save this file as client_secrets.p12; you will need it later in the tutorial.

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) {

  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()
        .setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))

    // Construct the Analytics service object.
    return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)

  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()

      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")

  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.