本教程详细介绍了访问 Analytics Reporting API v4 所需的步骤。
1. 启用 API
要开始使用 Analytics Reporting API V4,需要先使用设置工具,该工具会引导您在 Google API 控制台中创建项目、启用 API 以及创建凭据。
创建凭据
- 打开服务帐号页。如果看到相关提示,请选择项目。
- 点击创建服务帐号。
- 在创建服务帐号窗口中,键入服务帐号的名称,然后选择提供新的私钥。然后点击保存。
此时,系统会生成您的新公钥/私钥对,并下载到您的计算机;它是该密钥唯一的副本,由您负责安全存储该密钥。
将服务帐号添加到 Google Analytics(分析)帐号
新创建的服务帐号将拥有一个类似以下所示的电子邮件地址:
quickstart@PROJECT-ID.iam.gserviceaccount.com
使用此电子邮件地址将用户添加到要通过 API 访问的 Google Analytics(分析)数据视图。就本教程而言,仅需获得读取和分析权限。
2. 安装客户端库
您既可以使用文件包管理器,也可以手动下载并安装 Python 客户端库:
pip
建议使用 pip 工具来安装 Python 文件包:
sudo pip install --upgrade google-api-python-client
Setuptools
使用 setuptools 文件包中的 easy_install 工具:
sudo easy_install --upgrade google-api-python-client
手动安装
下载最新的 Google API Python 客户端库,解压代码并运行:
sudo python setup.py install
3. 设置示例
您需要创建一个名为 HelloAnalytics.py
的文件,其中将包含指定的示例代码。
- 以下源代码复制或下载到
HelloAnalytics.py
中。 - 将先前下载的
client_secrets.json
移到示例代码所在的目录中。 - 将
SERVICE_ACCOUNT_EMAIL
和KEY_FILE_LOCATION
的值替换为 Developer Console 中的相应值。 - 替换
VIEW_ID
的值。您可以使用帐号浏览器找到数据视图 ID。
"""Hello Analytics Reporting API V4.""" from apiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>' VIEW_ID = '<REPLACE_WITH_VIEW_ID>' def initialize_analyticsreporting(): """Initializes an Analytics Reporting API V4 service object. Returns: An authorized Analytics Reporting API V4 service object. """ credentials = ServiceAccountCredentials.from_json_keyfile_name( KEY_FILE_LOCATION, SCOPES) # Build the service object. analytics = build('analyticsreporting', 'v4', credentials=credentials) return analytics def get_report(analytics): """Queries the Analytics Reporting API V4. Args: analytics: An authorized Analytics Reporting API V4 service object. Returns: The Analytics Reporting API V4 response. """ return analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:sessions'}], 'dimensions': [{'name': 'ga:country'}] }] } ).execute() def print_response(response): """Parses and prints the Analytics Reporting API V4 response. Args: response: An Analytics Reporting API V4 response. """ for report in response.get('reports', []): columnHeader = report.get('columnHeader', {}) dimensionHeaders = columnHeader.get('dimensions', []) metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', []) for row in report.get('data', {}).get('rows', []): dimensions = row.get('dimensions', []) dateRangeValues = row.get('metrics', []) for header, dimension in zip(dimensionHeaders, dimensions): print header + ': ' + dimension for i, values in enumerate(dateRangeValues): print 'Date range: ' + str(i) for metricHeader, value in zip(metricHeaders, values.get('values')): print metricHeader.get('name') + ': ' + value def main(): analytics = initialize_analyticsreporting() response = get_report(analytics) print_response(response) if __name__ == '__main__': main()
4. 运行示例
使用以下文件运行示例应用:
python HelloAnalytics.py
当您完成这些步骤后,示例代码就会输出给定数据视图过去 7 天内的会话数。
问题排查
AttributeError:'Module_six_moves_urllib_parse' 对象没有 'urlparse' 属性
在 Mac OSX 中,当“six”模块(该库的依赖项)的默认安装先于 pip 安装的模块加载时,就会出现上述错误。要解决该问题,请将 pip 的安装位置添加到 PYTHONPATH
系统环境变量中:
使用以下命令确定 pip 的安装位置:
pip show six | grep "Location:" | cut -d " " -f2
将以下行添加到您的
~/.bashrc
文件中,将<pip_install_path>
替换为上面确定的值:export PYTHONPATH=$PYTHONPATH:<pip_install_path>
使用以下命令,在任何已打开的终端窗口中重新加载您的
~/.bashrc
文件:source ~/.bashrc