pythongoogle-oauthgoogle-analytics-apigoogle-analytics-4

How to get property_id in Google Analytics Data API (GA4) using Python?


I need to get a list with all 'Analytics accounts', I also need all property_id in Google Analytics that each 'Analytics accounts' contains.

When I used the Google Analytics API V3 (Universal Analytics) to get the view_id, I followed the guide described in the link below:

https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/installed-py -> the line of code:

accounts = service.management().accountSummaries().list().execute()

but when I use the API (GA4) I have to use the instructions given in the link below:

https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/list

For this case, I tried to use the below script to get property id, and get this message:

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)

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'}}

The json file I'm using in the KEY_FILE_LOCATION variable is the json generated during the 'Service account' creation process in https://console.cloud.google.com, when creating the key which I saved to the json file, and I think the problem is in the .json file.

The documentation says that I should use pageToken, but I don't understand how I can generate it.

What am I doing wrong, maybe something needs to be changed in the script, also what jason file do I need to use to get access and how do I generate it?


Solution

  • Set your credentials:

    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'location of your client_secrets.json'
    

    See for getting property_ids: https://developers.google.com/analytics/devguides/migration/api/management-ua-to-ga4

    This is the code:

    from google.analytics.admin import AnalyticsAdminServiceClient
    
    def list_account_summaries(transport: str = None) -> None:
        """
        Prints summaries of all accounts accessible by the caller.
    
        Args:
            transport(str): The transport to use. For example, "grpc"
                or "rest". If set to None, a transport is chosen automatically.
        """
        client = AnalyticsAdminServiceClient(transport=transport)
        results = client.list_account_summaries()
    
        print("Result:")
        for account_summary in results:
            print("-- Account --")
            print(f"Resource name: {account_summary.name}")
            print(f"Account name: {account_summary.account}")
            print(f"Display name: {account_summary.display_name}")
            print()
            for property_summary in account_summary.property_summaries:
                print("-- Property --")
                print(f"Property resource name: {property_summary.property}")
                print(f"Property display name: {property_summary.display_name}")
                print()
    
    # Account is UA; Property is GA4
    list_account_summaries()