このチュートリアルでは、Google アナリティクス アカウントへのアクセス、 アナリティクス API へのクエリ、API レスポンスの処理、結果の出力のために 必要な手順を詳しく説明していきます。このチュートリアルでは、Core Reporting API v3.0、Management API v3.0、OAuth2.0 を使用します。
ステップ 1: アナリティクス API を有効にする
Google アナリティクス API を使用するには、最初に セットアップ ツールを使用して Google API コンソールでプロジェクトを 作成し、API を有効にして認証情報を作成する必要があります。
クライアント ID を作成する
- [サービス アカウント] ページを開きます。画面のメッセージに従って、プロジェクトを選択します。
- [ サービス アカウントを作成] をクリックして、サービス アカウントの名前と説明を入力します。デフォルトのサービス アカウント ID を使用することも、別の一意の ID を選択することもできます。入力したら、[作成] をクリックします。
- 以降の [サービス アカウントの権限(オプション)] セクションは必須ではありません。[続行] をクリックします。
- [ユーザーにこのサービス アカウントへのアクセスを許可] 画面で、[キーの作成] セクションまで下にスクロールします。[ キーを作成] をクリックします。
- 表示されたサイドパネルで、キーの形式を選択します。JSON をおすすめします。
- [作成] をクリックします。新しい公開鍵と秘密鍵のペアが生成され、パソコンにダウンロードされます。この鍵は再発行できませんので、安全に保管する方法については、サービス アカウント キーの管理をご覧ください。
- [秘密鍵がパソコンに保存されました] ダイアログで [閉じる] をクリックし、[完了] をクリックしてサービス アカウントの表に戻ります。
Google アナリティクス アカウントへのサービス アカウントの追加
新しく作成されたサービス アカウントには、メールアドレス <projectId>-<uniqueId>@developer.gserviceaccount.com
が設定されます。このメールアドレスを使用して、API でアクセスする Google アナリティクス アカウントにユーザーを追加します。このチュートリアルでは、表示と分析の権限が必要です。
ステップ 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 つ作成する必要があります。このファイルには指定のサンプルコードを記述します。
- 次のソースコードを
HelloAnalytics.py
にコピーまたは ダウンロードします。 - 先ほどダウンロードした
client_secrets.json
をサンプルコードと同じディレクトリに移動します。 key_file_location
の値は、Developer Console に表示された適切な値に置き換えます。
"""A simple example of how to access the Google Analytics API.""" from apiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials def get_service(api_name, api_version, scopes, key_file_location): """Get a service that communicates to a Google API. Args: api_name: The name of the api to connect to. api_version: The api version to connect to. scopes: A list auth scopes to authorize for the application. key_file_location: The path to a valid service account JSON key file. Returns: A service that is connected to the specified API. """ credentials = ServiceAccountCredentials.from_json_keyfile_name( key_file_location, scopes=scopes) # Build the service object. service = build(api_name, api_version, credentials=credentials) 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 this 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 within 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):', results.get('profileInfo').get('profileName') print 'Total Sessions:', 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' key_file_location = '<REPLACE_WITH_JSON_FILE>' # Authenticate and construct service. service = get_service( api_name='analytics', api_version='v3', scopes=[scope], key_file_location=key_file_location) profile_id = get_first_profile_id(service) print_results(get_results(service, profile_id)) if __name__ == '__main__': main()
ステップ 4: サンプルを実行する
Analytics API を有効にして Python 用 Google API クライアント ライブラリをインストールし、サンプル ソースコードを設定したら、サンプルを実行できるようになります。
次のコマンドを使用してサンプルを実行します。
python HelloAnalytics.py
以上の手順が完了すると、サンプルは、承認済みユーザーの最初の Google アナリティクス ビュー(プロファイル)の名前と、過去 7 日間のセッション数を出力します。
承認済みの Analytics サービス オブジェクトを使用して、 Management API リファレンス ドキュメントにあるコードサンプルをすべて実行できます。たとえば、 accountSummaries.list メソッドを使用するようにコードを変更してみましょう。
トラブルシューティング
AttributeError: 「Module_six_moves_urllib_parse」オブジェクトに「urlparse」属性がありません
Mac OSX でデフォルト インストールの "six" モジュール(このライブラリに依存)が、pip がインストールするモジュールよりも先に読み込まれた場合に、このエラーが発生します。この問題を修正するには、以下の手順で PYTHONPATH
システム環境変数に pip のインストール先を追加します。
-
次のコマンドで pip のインストール先を確認します。
pip show six | grep "Location:" | cut -d " " -f2
-
~/.bashrc
ファイルに次の行を追加し、<pip_install_path>
を上記で確認した値に置き換えます。export PYTHONPATH=$PYTHONPATH:<pip_install_path>
-
開いているターミナル ウィンドウで、次のコマンドを使用して
~/.bashrc
ファイルを再読み込みします。source ~/.bashrc