はじめてのアナリティクス API: サービス アカウント向け Java クイック スタート

このチュートリアルでは、Google アナリティクス アカウントへのアクセス、 アナリティクス API へのクエリ、API レスポンスの処理、結果の出力のために 必要な手順を詳しく説明していきます。このチュートリアルでは、Core Reporting API v3.0Management API v3.0OAuth2.0 を使用します。

ステップ 1: アナリティクス API を有効にする

Google アナリティクス API を使用するには、最初に セットアップ ツールを使用して Google API コンソールでプロジェクトを 作成し、API を有効にして認証情報を作成する必要があります。

クライアント ID を作成する

  1. [サービス アカウント] ページを開きます。画面のメッセージに従って、プロジェクトを選択します。
  2. [ サービス アカウントを作成] をクリックして、サービス アカウントの名前と説明を入力します。デフォルトのサービス アカウント ID を使用することも、別の一意の ID を選択することもできます。入力したら、[作成] をクリックします。
  3. 以降の [サービス アカウントの権限(オプション)] セクションは必須ではありません。[続行] をクリックします。
  4. [ユーザーにこのサービス アカウントへのアクセスを許可] 画面で、[キーの作成] セクションまで下にスクロールします。[ キーを作成] をクリックします。
  5. 表示されたサイドパネルで、キーの形式を選択します。JSON をおすすめします。
  6. [作成] をクリックします。新しい公開鍵と秘密鍵のペアが生成され、パソコンにダウンロードされます。この鍵は再発行できませんので、安全に保管する方法については、サービス アカウント キーの管理をご覧ください。
  7. [秘密鍵がパソコンに保存されました] ダイアログで [閉じる] をクリックし、[完了] をクリックしてサービス アカウントの表に戻ります。

Google アナリティクス アカウントへのサービス アカウントの追加

新しく作成されたサービス アカウントには、メールアドレス <projectId>-<uniqueId>@developer.gserviceaccount.com が設定されます。このメールアドレスを使用して、API でアクセスする Google アナリティクス アカウントにユーザーを追加します。このチュートリアルでは、表示と分析の権限が必要です。

ステップ 2: Google クライアント ライブラリをインストールする

Google Analytics API Java クライアントをインストールするには、解凍して Java クラスパスにコピーする必要があるすべての jar を含む zip ファイルをダウンロードする必要があります。

  1. Google アナリティクス Java クライアント ライブラリをダウンロードします。このライブラリは、必要な依存関係をすべて含む ZIP ファイルとしてバンドルされています。
  2. ZIP ファイルを展開します
  3. libs ディレクトリ内のすべての JAR をクラスパスに追加します。
  4. google-api-services-analytics-v3-[version].jar jar をクラスパスに追加します。

ステップ 3: サンプルを設定する

HelloAnalytics.java という名前のファイルを 1 つ作成する必要があります。このファイルには指定のサンプルコードを記述します。

  1. 次のソースコードを HelloAnalytics.java にコピーまたは ダウンロードします。
  2. 先ほどダウンロードした client_secrets.JSON をサンプルコードと同じディレクトリに移動します。
  3. KEY_FILE_LOCATION の値は、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");
    }
  }
}

ステップ 4: サンプルを実行する

Analytics API を有効にして Java 用 Google API クライアント ライブラリをインストールし、サンプル ソースコードを設定したら、サンプルを実行できるようになります。

IDE を使用している場合は、デフォルトの実行ターゲットが HelloAnalytics クラスに設定されていることを確認してください。それ以外の場合は、コマンドラインからアプリケーションをコンパイルして実行できます。

  1. 次のコマンドを使用してサンプルをコンパイルします。
    javac -classpath /path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics.java
  2. 次のコマンドを使用してサンプルを実行します。
    java -classpath ./:/path/to/google/lib/*:/path/to/google/lib/libs/* HelloAnalytics

以上の手順が完了すると、サンプルは、承認済みユーザーの最初の Google アナリティクス ビュー(プロファイル)の名前と、過去 7 日間のセッション数を出力します。

承認済みの Analytics サービス オブジェクトを使用して、 Management API リファレンス ドキュメントにあるコードサンプルをすべて実行できます。たとえば、 accountSummaries.list メソッドを使用するようにコードを変更してみましょう。