如何用Python通过GA4 Admin API获取账户及property_id并解决认证问题
问题解决指南
1. 脚本认证错误的修复点
你直接调用credentials.token会拿到未刷新的无效token,这是核心问题。以下是两种修复方式:
修复方式一:手动刷新凭证
import requests import json from google.oauth2 import service_account url = 'https://analyticsadmin.googleapis.com/v1alpha/accountSummaries' KEY_FILE_LOCATION = r'C:/.../cogent-precinct.json' SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] credentials = service_account.Credentials.from_service_account_file(KEY_FILE_LOCATION, scopes=SCOPES) # 关键步骤:刷新凭证获取有效访问token credentials.refresh(requests.Request()) params = {'pageSize': 50} headers = {'Authorization': f'Bearer {credentials.token}'} response = requests.get(url, params=params, headers=headers) data = response.json() print(data)
修复方式二:使用Google API Python客户端(更推荐)
官方库会自动处理认证和分页逻辑,避免手动操作token的麻烦:
from google.oauth2 import service_account from googleapiclient.discovery import build KEY_FILE_LOCATION = r'C:/.../cogent-precinct.json' SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] credentials = service_account.Credentials.from_service_account_file(KEY_FILE_LOCATION, scopes=SCOPES) # 构建GA4 Admin API客户端实例 service = build('analyticsadmin', 'v1alpha', credentials=credentials) # 获取账户摘要数据(包含下属的property信息) results = service.accountSummaries().list(pageSize=50).execute() account_summaries = results.get('accountSummaries', []) # 遍历输出账户ID和对应的Property ID for summary in account_summaries: print(f"账户ID: {summary['account']}") for property_info in summary.get('properties', []): print(f" Property ID: {property_info['property']}")
2. 正确的密钥文件类型及生成步骤
你使用的JSON密钥文件是正确类型,生成步骤如下:
- 打开Google Cloud控制台,进入IAM与管理 > 服务账户页面
- 找到目标服务账户,点击右侧的操作 > 管理密钥
- 点击添加密钥 > 创建新密钥,选择JSON格式,点击「创建」,下载的文件就是所需的密钥文件
注意:必须给该服务账户授予GA4账户/媒体资源的权限(比如「Analytics查看者」或「Analytics管理员」),否则即使token有效,也会触发权限类错误。
3. pageToken的用法
当请求的pageSize无法返回所有结果时,API响应会包含nextPageToken字段。你需要将这个值作为下一次请求的pageToken参数传入,循环执行请求直到没有nextPageToken为止:
示例(基于官方客户端库):
from google.oauth2 import service_account from googleapiclient.discovery import build KEY_FILE_LOCATION = r'C:/.../cogent-precinct.json' SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] credentials = service_account.Credentials.from_service_account_file(KEY_FILE_LOCATION, scopes=SCOPES) service = build('analyticsadmin', 'v1alpha', credentials=credentials) all_account_summaries = [] page_token = None while True: # 传入page_token参数获取下一页数据 results = service.accountSummaries().list(pageSize=50, pageToken=page_token).execute() all_account_summaries.extend(results.get('accountSummaries', [])) page_token = results.get('nextPageToken') # 没有下一页时终止循环 if not page_token: break # 输出所有账户及下属Property信息 for summary in all_account_summaries: print(f"账户ID: {summary['account']}") for property_info in summary.get('properties', []): print(f" Property ID: {property_info['property']}")
内容的提问来源于stack exchange,提问作者LiAfe
相关产品推荐
相关产品推荐

