このチュートリアルでは、Google アナリティクス アカウントへのアクセス、 アナリティクス API へのクエリ、API レスポンスの処理、結果の出力のために 必要な手順を詳しく説明していきます。チュートリアルでは、Core Reporting API v3.0、Management API v3.0、 OAuth 2.0 を使用しています。
ステップ 1: アナリティクス API を有効にする
Google アナリティクス API を使用するには、最初に セットアップ ツールを使用して Google API コンソールでプロジェクトを 作成し、API を有効にして認証情報を作成する必要があります。
クライアント ID を作成する
- [サービス アカウント] ページを開きます。 画面のメッセージに従って、プロジェクトを選択します。
- [サービス アカウントを作成] をクリックします。
- [サービス アカウントの作成] ウィンドウで、サービス アカウント名を 入力して [新しい秘密鍵の提供] をオンにします。サービス アカウントに Google Workspace ドメイン全体の権限を付与する場合、[Google Workspace ドメイン全体の委任を有効にする] も選択します。選択したら、[保存] をクリックします。
新しい公開鍵 / 秘密鍵のペアが生成され、マシンにダウンロードされます。この鍵には他のコピーはありません。安全に保管してください。
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
の値を、Developers 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: サンプルを実行する
アナリティクス 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