更新时间:2025年3月5号
启用API
Google Cloud里新建项目
在Google Cloud里新建项目,点击项目列表,在Google Cloud左上角位置:
然后点击「新建项目」:
开启Google Analytics Data API
现将Google Cloud的工作项目切换为刚创建的“GA For Demo”:
点击右上角的导航菜单,然后点击「API和服务」——「已启用的API和服务」——「+启用API和服务」,搜索“Google Analytics Data API”,然后将它启用:
创建服务账号
点击右上角的导航菜单,然后点击「API和服务」——「凭据」:
做如下设置,服务账号命名为“GA4 API TEST”,然后点击「完成」
注意这个邮箱,后面会需要GA4授权。
下载JSON秘钥
然后点击「秘钥」——「添加键」——「创建新秘钥」,选择JSON:
点击「创建」,可以看到下载了一个秘钥:
获取GA4授权
给服务账号ga4-api-test@ga-for-demo.iam.gserviceaccount.com授权,在GA4里点击「管理」——「媒体资源访问权限管理」——「+」——「添加用户」,将其添加,权限类型是查看者的就可以:
Python里
安装基础库
pip install google-analytics-data
代码调试
示例代码:
# [START analyticsdata_json_credentials_quickstart]
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Metric,
RunReportRequest,
)
def sample_run_report(property_id="206759202", credentials_json_path="/home/haran_huang/cloudshell_open/python-docs-samples/ga-for-demo-ee78a4d8024e.json"):
client = BetaAnalyticsDataClient.from_service_account_json(credentials_json_path)
# [END analyticsdata_json_credentials_initialize]
# [START analyticsdata_json_credentials_run_report]
request = RunReportRequest(
property=f"properties/{property_id}",
dimensions=[Dimension(name="city")],
metrics=[Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="2025-01-31", end_date="today")],
)
response = client.run_report(request)
# [END analyticsdata_json_credentials_run_report]
print("Report result:")
for row in response.rows:
print(row.dimension_values[0].value, row.metric_values[0].value)
# [END analyticsdata_json_credentials_quickstart]
if __name__ == "__main__":
sample_run_report()
这个代码的作用是获取,2月起,每个城市的活跃用户数。













