-
. How to retrieve the property_id for a Google Analytics account using the GA4 Data API and Python
Hey there! I’m working on a project where I need to pull together a list of all ‘Analytics accounts’ and their associated property_id in Google Analytics. This went swimmingly when I was using the Google Analytics API V3 (Universal Analytics). However, things are a bit sticky with the Google Analytics 4 API.
I followed the instructions here: https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/list.
Using the script below, (expecting to get the property id), I ran into an error message:
`python
import requests
import json
from google.oauth2 import service_accounturl = ‘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)
params = {‘pageSize’: 50}
headers = {‘Authorization’: f’Bearer {credentials.token}’}response = requests.get(url, params=params, headers=headers)
data = response.json()
print(data)
…
{‘error’: {‘code’: 401, ‘message’: ‘Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.’, ‘status’: ‘UNAUTHENTICATED’}}
`
I use a .json file—generated during my ‘Service account’ creation process at https://console.cloud.google.com—to store the key that I then save into the KEY_FILE_LOCATION variable. I suspect that the issue lies within the aforementioned .json file.The documentation mentions that pageToken should be employed, but I’m at a loss as to how to generate it. Do you think I need to tweak the script, or perhaps use a different .json file? If so, I could use some guidance on how to generate it. Can you help me troubleshoot this issue?
Log in to reply.