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, enter a name and description for the service account. You can use the default service account ID, or choose a different, unique one. When done click Create.
  3. The Service account permissions (optional) section that follows is not required. Click Continue.
  4. On the Grant users access to this service account screen, scroll down to the Create key section. Click Create key.
  5. In the side panel that appears, select the format for your key: JSON is recommended.
  6. Click Create. Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. For information on how to store it securely, see Managing service account keys.
  7. Click Close on the Private key saved to your computer dialog, then click Done to return to the table of your service accounts.

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.JSON within the same directory as the sample code.
  3. Replace the values of the 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.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
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 = "<REPLACE_WITH_JSON_FILE>";
  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();
    }
  }

  /**
   * Initializes an Analytics service object.
   *
   * @return An authorized Analytics service object.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  private static AnalyticsReporting initializeAnalytic() throws GeneralSecurityException, IOException {

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential
        .fromStream(new FileInputStream(KEY_FILE_LOCATION))
        .createScoped(AnalyticsScopes.all());

    // 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.