简体   繁体   中英

Google Analytics Reporting API v4 using Python Error 403

я столкнулся с такой проблемой, при создании связи Google Analytics Reporting API v4 for Python получаю ошибку

<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.">

У меня права администратора Google Analytics и я предоставил права для сервисного аккаунта на чтение. В console.cloud.google создал сервисный аккаунт и включил Analytics Reporting API Действовал по инструкции https://www.jcchouinard.com/google-analytics-api-using-python/

I tried to solve this problem created a new project in https://console.cloud.google.com/ added a new service account to it (created new keys) and added a service account to Google Analytics (with administrator rights) and included Analytics Reporting API. I also tried to substitute the Google Analytics viewId of the account and the viewId of the resource. I tried to use the code from the official source Hello Analytics Reporting API v4; Python quickstart for service accounts https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py as well as from third parties https://www.jcchouinard.com/google-analytics-api-using-python/ Example

            #Load Libraries
            from oauth2client.service_account import ServiceAccountCredentials
            from apiclient.discovery import build
            import httplib2
            import pandas as pd
            
            #Create service credentials
            #Rename your JSON key to client_secrets.json and save it to your working folder
            credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', ['https://www.googleapis.com/auth/analytics.readonly'])
            
            #Create a service object
            http = credentials.authorize(httplib2.Http())
            service = build('analytics', 'v4', http=http, discoveryServiceUrl=('https://analyticsreporting.googleapis.com/$discovery/rest'))
            response = service.reports().batchGet(
                body={
                    'reportRequests': [
                        {
                            'viewId': 'XXXXXXXX', #Add View ID from GA
                            'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}],
                            'metrics': [{'expression': 'ga:sessions'}], 
                            'dimensions': [{"name": "ga:pagePath"}], #Get Pages
                            "filtersExpression":"ga:pagePath=~products;ga:pagePath!@/translate", #Filter by condition "containing products"
                            'orderBys': [{"fieldName": "ga:sessions", "sortOrder": "DESCENDING"}], 
                            'pageSize': 100
                        }]
                }
            ).execute()
            
            #create two empty lists that will hold our dimentions and sessions data
            dim = []
            val = []
            
            #Extract Data
            for report in response.get('reports', []):
            
                columnHeader = report.get('columnHeader', {})
                dimensionHeaders = columnHeader.get('dimensions', [])
                metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
                rows = report.get('data', {}).get('rows', [])
            
                for row in rows:
            
                    dimensions = row.get('dimensions', [])
                    dateRangeValues = row.get('metrics', [])
            
                    for header, dimension in zip(dimensionHeaders, dimensions):
                        dim.append(dimension)
            
                    for i, values in enumerate(dateRangeValues):
                        for metricHeader, value in zip(metricHeaders, values.get('values')):
                            val.append(int(value))
            
            #Sort Data
            val.reverse()
            dim.reverse()
            
            df = pd.DataFrame() 
            df["Sessions"]=val
            df["pagePath"]=dim
            df=df[["pagePath","Sessions"]]
            df
            
            #Export to CSV
            df.to_csv("page_by_session.csv")`

User does not have sufficient permissions for this profile.

Is a standard error message. It means that the user you are currently authenticated with. Does not have access to the profile you are trying to request data for.

You are trying to access this view id

viewId': 'XXXXXXXX', #Add View ID from GA

Using service account authencation

credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', ['https://www.googleapis.com/auth/analytics.readonly'])

But you have not granted the service account access to that view.

Go to the google analytics website under the admin section and add take the service account email address its the only value in that file with an @ in it and add it as a user.

It will then have access.

User doesn't have any google analytics accounts easy solution

This is what the admin section of a Universal analytics account looks like.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM