pyseo
pyseo

Reputation: 541

Google Analytics API Python Error 403 - Insufficient Permissions

I've set my analytics api and credentials, downloaded the client_secrets.json and copied the client_email.

Then, I went to my Google Analytics account > property > view > admin > User Management and added that email as a new user with read permissions. This went just fine, no error or whatsoever.

Now, when I try to make use of the api via python, i get this error:

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json returned "User does not have sufficient permissions for this profile.". Details: "User does not have sufficient permissions for this profile.">

I'm going crazy with this. Don't know what's going on and how to fix it.

Code:

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


SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'client_secrets.json'
VIEW_ID = 'view_id' #exampe '12341234'


def initialize_analyticsreporting():
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        KEY_FILE_LOCATION, SCOPES)
    analytics = build('analyticsreporting', 'v4', credentials=credentials)
    return analytics


def get_report(analytics):
    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()

Can someone help me please? Thanks!

Upvotes: 3

Views: 4869

Answers (2)

Davide Piasentin
Davide Piasentin

Reputation: 31

I had exactly the same error message and it turned out that the issue was coming from the fact that I was calling the Google Analytics Reporting API v4 for a Google Analytics GA4 property which is not supported according to Google documentation.

I tried calling the same API for a Google Analytics GA3 (Universal Analytics) property and it worked.

If you are using the latest Google Analytics (GA4) please call the Google Analytics Data API.

Link to the documentation:

Google Analytics Reporting API v4

Google Analytics Data API

Upvotes: 3

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117271

User does not have sufficient permissions for this profile.

Means that the user you are currently authenticating with does not have permissions to access the account you are trying to access.

You need to add the user via the Google analytics admin as you have done. Make sure you added it at the account level.

I would suggest that you double check that you added the correct user email address, and then check that you are using the correct view id.

User doesn't have any google analytics accounts easy solution

You miss typed something.

Upvotes: 2

Related Questions