はじめてのアナリティクス API: インストール済みアプリケーション向け Python クイック スタート

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

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

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

クライアント ID の作成

[認証情報] ページから以下の手順を実行します。

  1. [認証情報を作成] をクリックし、[OAuth クライアント ID] を選択します。
  2. [アプリケーションの種類] で [その他] を選択します。
  3. 認証情報の名前を指定します。
  4. [作成] をクリックします。

作成した認証情報を選択し、[JSON をダウンロード] をクリックします。ダウンロードしたファイルを client_secrets.json という名前で保存します。このファイルは、チュートリアルの後半で必要になります。

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

パッケージ マネージャーを使用するか、Python クライアント ライブラリを手動でダウンロードしてインストールできます。

pip

Python パッケージのインストールには、推奨ツールの pip を使用します。

sudo pip install --upgrade google-api-python-client

setuptools

setuptools パッケージに含まれる easy_install ツールを使用します。

sudo easy_install --upgrade google-api-python-client

手動インストール

最新の Python 用クライアント ライブラリをダウンロードし、コードを解凍して、次のコマンドを実行します。

sudo python setup.py install

システムに Python クライアントをインストールするには、スーパーユーザー(sudo)権限でコマンドを実行することが必要になる場合があります。

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

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

  1. 次のソースコードをコピーするかダウンロードして、HelloAnalytics.py に記述します。
  2. 先ほどダウンロードしておいた client_secrets.json をサンプルコードと同じディレクトリに移動します。
"""A simple example of how to access the Google Analytics API."""

import argparse

from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools

def get_service(api_name, api_version, scope, client_secrets_path):
  """Get a service that communicates to a Google API.

  Args:
    api_name: string The name of the api to connect to.
    api_version: string The api version to connect to.
    scope: A list of strings representing the auth scopes to authorize for the
      connection.
    client_secrets_path: string A path to a valid client secrets file.

  Returns:
    A service that is connected to the specified API.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      client_secrets_path, scope=scope,
      message=tools.message_if_missing(client_secrets_path))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(api_name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  service = build(api_name, api_version, http=http)

  return service

def get_first_profile_id(service):
  # Use the Analytics service object to get the first profile id.

  # Get a list of all Google Analytics accounts for the authorized user.
  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    # Get the first Google Analytics account.
    account = accounts.get('items')[0].get('id')

    # Get a list of all the properties for the first account.
    properties = service.management().webproperties().list(
        accountId=account).execute()

    if properties.get('items'):
      # Get the first property id.
      property = properties.get('items')[0].get('id')

      # Get a list of all views (profiles) for the first property.
      profiles = service.management().profiles().list(
          accountId=account,
          webPropertyId=property).execute()

      if profiles.get('items'):
        # return the first view (profile) id.
        return profiles.get('items')[0].get('id')

  return None

def get_results(service, profile_id):
  # Use the Analytics Service Object to query the Core Reporting API
  # for the number of sessions in the past seven days.
  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='7daysAgo',
      end_date='today',
      metrics='ga:sessions').execute()

def print_results(results):
  # Print data nicely for the user.
  if results:
    print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
    print 'Total Sessions: %s' % results.get('rows')[0][0]

  else:
    print 'No results found'

def main():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.readonly']

  # Authenticate and construct service.
  service = get_service('analytics', 'v3', scope, 'client_secrets.json')
  profile = get_first_profile_id(service)
  print_results(get_results(service, profile))

if __name__ == '__main__':
  main()

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

アナリティクス API を有効にして、Python 用 Google API クライアント ライブラリをインストールし、サンプル ソースコードを設定したら、サンプルの実行準備は完了です。

次のコマンドを使用してサンプルを実行します。

python HelloAnalytics.py
  1. アプリケーションによって承認ページがブラウザに読み込まれます。
  2. Google アカウントにまだログインしていない場合は、ログインするよう求められます。複数の Google アカウントにログインしている場合は、承認に使用するアカウントを 1 つ選択するよう求められます。

以上の手順が完了すると、サンプルコードによって、認証済みユーザーの最初の Google アナリティクス ビュー(旧プロファイル)の名前と、直前 7 日間のセッション数が出力されます。

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

トラブルシューティング

AttributeError: 「Module_six_moves_urllib_parse」オブジェクトに「urlparse」属性がありません

Mac OSX でデフォルト インストールの "six" モジュール(このライブラリに依存)が、pip がインストールするモジュールよりも先に読み込まれた場合に、このエラーが発生します。この問題を修正するには、以下の手順で PYTHONPATH システム環境変数に pip のインストール先を追加します。

  1. 次のコマンドで pip のインストール先を確認します。

    pip show six | grep "Location:" | cut -d " " -f2
    

  2. 次の行を ~/.bashrc ファイルに追加し、<pip_install_path> を上記で確認した値で置き換えます。

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>
    
  3. 開いているターミナル ウィンドウで、次のコマンドを使って ~/.bashrc ファイルを再度読み込みます。

    source ~/.bashrc