Python implementation for retrieving property IDs from GA4 Analytics Admin API

I’m trying to extract all Analytics accounts along with their corresponding property IDs using the GA4 Analytics Admin API in Python. Previously with Universal Analytics (GA3), I could easily fetch view IDs using the management API. Now I need to migrate to GA4 and I’m having authentication issues.

Here’s my current code attempt:

import requests
from google.oauth2 import service_account

api_endpoint = 'https://analyticsadmin.googleapis.com/v1alpha/accountSummaries'
service_key_path = '/path/to/my-project-credentials.json'
required_scopes = ['https://www.googleapis.com/auth/analytics.readonly']

creds = service_account.Credentials.from_service_account_file(
    service_key_path, 
    scopes=required_scopes
)

query_params = {'pageSize': 50}
auth_headers = {'Authorization': f'Bearer {creds.token}'}

api_response = requests.get(api_endpoint, params=query_params, headers=auth_headers)
result_data = api_response.json()
print(result_data)

I keep getting a 401 authentication error saying the credentials are invalid. I’m using a service account JSON file from Google Cloud Console but something seems wrong with my setup. How do I properly authenticate and what’s the correct way to generate the access token for this API?

Your service account credentials aren’t refreshed yet when you try to access creds.token. That’s what’s breaking your code.

Here’s the fix:

import requests
from google.oauth2 import service_account
from google.auth.transport.requests import Request

api_endpoint = 'https://analyticsadmin.googleapis.com/v1alpha/accountSummaries'
service_key_path = '/path/to/my-project-credentials.json'
required_scopes = ['https://www.googleapis.com/auth/analytics.readonly']

creds = service_account.Credentials.from_service_account_file(
    service_key_path, 
    scopes=required_scopes
)

# This is what you're missing - refresh the credentials
creds.refresh(Request())

query_params = {'pageSize': 50}
auth_headers = {'Authorization': f'Bearer {creds.token}'}

api_response = requests.get(api_endpoint, params=query_params, headers=auth_headers)
result_data = api_response.json()
print(result_data)

Double-check that your service account has Analytics Admin API access and the right IAM roles for your GA4 property.

Honestly though, GA4 API authentication gets tedious fast with all these credential refreshes. I’ve been automating GA4 workflows and found that using an automation platform handles all this OAuth mess automatically.

You can set up the same GA4 extraction in Latenode without dealing with token management or auth headers. It connects straight to GA4 and handles the API complexity for you. Much cleaner than wrestling with service account credentials.