from google.oauth2 import service_account
from googleapiclient.discovery import build
# Replace the values in the following line with your own credentials
creds = service_account.Credentials.from_service_account_file(r"C:\Users\xxxx\xxx\xxx\xxx.json")
# Create a Google Analytics Data API client
analytics_service = build('analyticsdata', 'v1beta', credentials=creds)
# Define the Google Analytics Data API request for a GA4 property
request = {
'property': 'properties/xxxxx',
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'dimensions': [{'name': 'date'}],
'metrics': [{'name': 'activeUsers'}]
}
# Call the Google Analytics Data API using the request
try:
response = analytics_service.properties().runReport(body={'request': request}).execute()
# Print the response
print(response)
except Exception as e:
print(e)
我已为服务帐户授予对 Google Analytics 4 管理员和 IAM 的适当访问权限。我还在 GCP 上激活了 Google Analytics Data API,但我一直收到以下错误,
缺少必需的参数“property”
我期待从我输入的属性 ID 中提取数据
试试这个:
# Define the Google Analytics Data API request for a GA4 property
# Here is where it went right for me
request = {
'property': 'properties/xxxxx',
'requestBody': {
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'dimensions': [{'name': 'date'}],
'metrics': [{'name': 'activeUsers'}]
}
}