Search code examples
google-analyticsgoogle-analytics-api

Google Analytics API returned User does not have sufficient permissions for this profile


I have run a code followed the instruction below https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'path/to/keyfile'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'


def initialize_analyticsreporting():
  "Initializes an Analytics Reporting API V4 service object.

  Returns:
    An authorized Analytics Reporting API V4 service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  analytics = build('analyticsreporting', 'v4', credentials=credentials)

  return analytics


def get_report(analytics):
  """Queries the Analytics Reporting API V4.

  Args:
    analytics: An authorized Analytics Reporting API V4 service object.
  Returns:
    The Analytics Reporting API V4 response.
  """
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}],
          'dimensions': [{'name': 'ga:country'}]
        }]
      }
  ).execute()


def print_response(response):
  """Parses and prints the Analytics Reporting API V4 response.

  Args:
    response: An Analytics Reporting API V4 response.
  """
  for report in response.get('reports', []):
    columnHeader = report.get('columnHeader', {})
    dimensionHeaders = columnHeader.get('dimensions', [])
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])

    for row in report.get('data', {}).get('rows', []):
      dimensions = row.get('dimensions', [])
      dateRangeValues = row.get('metrics', [])

      for header, dimension in zip(dimensionHeaders, dimensions):
        print(header + ': ', dimension)

      for i, values in enumerate(dateRangeValues):
        print('Date range:', str(i))
        for metricHeader, value in zip(metricHeaders, values.get('values')):
          print(metricHeader.get('name') + ':', value)


def main():
  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  print_response(response)

if __name__ == '__main__':
  main()

Actually, I can't find View ID on Admin Settings. It just Account and Property. Is it because my property is App + Web and it still Beta? But, when I try to create a new property with App only, it is automatically changed to App + Web.

So confused in the first step trying Google Analytics API.

enter image description here


Solution

  • The Google Analytics Data API v1 is the new API for GA4 properties. See the devsite: https://developers.google.com/analytics/trusted-testing/analytics-data. The Data API v1 accepts a numeric GA4 property identifiers in report requests.

    Firebase show projects. The project ID and number shown in Firebase is not a GA4 Property identifier. To find your GA4 Property identifier:

    1. Navigate to the Firebase Analytics Dashboard,
    2. select the option "View your data in Google Analytics".
    3. In Google Analytics, select "Admin" and "Property Settings".
    4. A numeric "PROPERTY ID" will be shown. The Data API v1 accepts this GA4 Property Id in report request.

    App + Web Properties were recently renamed to GA4 Properties. See the blog post: https://blog.google/products/marketingplatform/analytics/new_google_analytics/.

    The Google Analytics API v3 (https://developers.google.com/analytics/devguides/reporting/core/v3) and Google Analytics Reporting API v4 (https://developers.google.com/analytics/devguides/reporting/core/v4) accept numeric view identifiers in report requests.

    GA4 Properties do not have views, and there is not a way to create views in those properties.