使用Python调用Google Analytics userActivity.search获取用户数据报错求助
I’ve run into this exact issue before—here’s what’s going wrong and how to fix it:
Why the Error Occurs
The error pops up because you’re passing the request body directly as a positional argument to the search() method, but the Google Client Library for Python expects the request body to be specified using the body keyword parameter. Unlike some other API methods, userActivity().search() doesn’t accept the body as a positional argument.
Correct Way to Call search()
You need to explicitly pass your request object using the body= keyword, just like you did with batchGet() in the original quickstart. Here’s a complete working example:
from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials # Authenticate (same as your existing setup) SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] KEY_FILE_LOCATION = 'path/to/your/service-account-key.json' VIEW_ID = 'your-view-id-here' credentials = ServiceAccountCredentials.from_json_keyfile_name( KEY_FILE_LOCATION, SCOPES) analytics = build('analyticsreporting', 'v4', credentials=credentials) # Build your User Activity request body user_activity_request = { "viewId": VIEW_ID, "user": { "userId": "target-user-id" # Use userIp instead if you don't have a userId }, "dateRange": { "startDate": "2024-01-01", "endDate": "2024-01-31" }, "pageSize": 10 # Optional: adjust how many activities to retrieve } # Correct call to search() with body keyword parameter response = analytics.userActivity().search(body=user_activity_request).execute() # Print or process the response print(response)
Alternative Approach: Build the Request Explicitly
If you prefer a more verbose (but sometimes clearer) approach, you can build the request object first and set its body before executing:
request = analytics.userActivity().search() request.body = user_activity_request response = request.execute()
Key Takeaway
Always remember to use the body= keyword when passing request payloads to Google Analytics API methods that require it. The original batchGet() example works because it uses body=request—you just need to apply the same pattern to userActivity().search().
内容的提问来源于stack exchange,提问作者the_economist

