Learn business growth with Google Analytics 4 Forums Google Analytics 4 . How to retrieve the property_id for a Google Analytics account using the GA4 Data API and Python

  • . How to retrieve the property_id for a Google Analytics account using the GA4 Data API and Python

    Posted by Isaiah on 2 June 2023 at 8:31 pm

    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_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’}}
    `
    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?

    Elijah replied 11 months, 2 weeks ago 3 Members · 2 Replies
  • 2 Replies
  • Lucas

    Member
    29 June 2023 at 10:53 am

    Hey, let’s start by setting your credentials:

    `python
    import os

    os.environ[‘GOOGLE_APPLICATION_CREDENTIALS’] = ‘path_to_your_client_secrets.json’
    `
    This step tells our Google SDKs to look for credentials in the specified location.

    Next, to list all the ‘Analytics accounts’ and their associated ‘property_id,’ check out this resource for getting property_ids using the Google Analytics 4 API – [here](https://developers.google.com/analytics/devguides/migration/api/management-ua-to-ga4).

    Here’s a helpful Python script that I pulled together:

    `python
    from google.analytics.admin import AnalyticsAdminServiceClient

    def list_account_summaries(transport: str = ‘rest’):
    “””
    Prints summaries of all accounts accessible by the caller.

    Args:
    transport(str): The transport to use. Could be “grpc” or “rest”.
    “””
    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()

    # In the GA4 API, ‘Account’ refers to the old ‘UA’, and ‘Property’ refers to the GA4 equivalent.
    list_account_summaries()
    `
    Give this a shot and let me know how it goes!

  • Elijah

    Member
    9 July 2023 at 5:24 am

    The error you’re seeing indicates an issue with the authentication credentials. The service account credentials that you’ve generated need to be correctly configured to access Google Analytics data. Make sure the service account is assigned the correct permissions in your Google Cloud Console and that it’s added as a user in your Google Analytics property with the appropriate access level.

    In terms of pageToken, you might not need it unless you’re working with a use case that involves pagination. This is typically used when the API response is too large and it’s split across multiple pages. The pageToken would be employed to access subsequent pages in such cases.

    Check the following:
    1. When you generated your service account key, did you include the right scopes? That is, did you ensure that the scope ‘https://www.googleapis.com/auth/analytics.readonly’ is included when the service account key was generated?
    2. Did you add the service account to your Google Analytics Account and assign it the correct access permissions? You need to add it as a user to the respective Google Analytics Account and provide at least read and analyze permissions for the account.
    3. Is your Google Analytics Account indeed a GA4 one? GA4 accounts have a different set of APIs than Universal Analytics accounts and are not interchangeable.

    One more thing to note is that credentials.token is potentially not initialized by default. Instead, use credentials.get_access_token().access_token. So change your header to headers = {'Authorization': 'Bearer {}'.format(credentials.get_access_token().access_token)}.

    If all these conditions are met and you’re still facing the issue, you might want to regenerate the service account key and try again.

Log in to reply.