Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Got 403 error when connecting to Google Analytics with Python 2.7.x

I tried to get data from Google Analytics API with Python client(google-api-python-client). Here's the code I used:

from apiclient import discovery
from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http

with open("ManagementGate-622edd43c0dd.p12") as f:
    private_key = f.read()

credentials = SignedJwtAssertionCredentials(
    '[email protected]',
    private_key,
    'https://www.googleapis.com/auth/analytics.readonly')

http_auth = credentials.authorize(Http())

service = discovery.build('analytics', 'v3', http=http_auth)

result = service.data().ga().get(
      ids='ga:79873569',
      start_date='7daysAgo',
      end_date='today',
      metrics='ga:visits,ga:sessions,ga:pageviews').execute()

I created a Service Account on Credentials Page. However, I got an error as below:

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/analytics/v3/data/ga?metrics=ga%3Avisits%2Cga%3Asessions%2Cga%3Apageviews&alt=json&end-date=today&ids=ga%3A79873569&start-date=7daysAgo returned "User does not have any Google Analytics account.">

The instructions I followed are from: https://developers.google.com/accounts/docs/OAuth2ServiceAccount Is there anything else I need to do? And why did I get this error? I already enabled Analytics API on APIs page.

like image 874
david30xie Avatar asked Dec 28 '14 07:12

david30xie


People also ask

How do I fix Google authorization error 403?

"code": 403, "message": "The user does not have sufficient permissions for file {fileId}." To fix this error, instruct the user to contact the file's owner and request edit access. You can also check user access levels in the metadata retrieved by files.

How to get access to Google Analytics?

You can sign in to your Analytics account from http://www.google.com/analytics. Click Sign in (at top right), and select Analytics. If you are already signed in to Google (e.g. you are signed in to your Gmail account), you'll be taken directly to the Analytics user interface.


1 Answers

You are trying to access the Google Analytics API using a service account. A service account by default does not have access to any Google Analytics accounts.

What you need to do is take the Service account email address from the Google Developer console. Go to the Admin section of the Google Analytics Website. Give this service account access at the ACCOUNT level it must be the ACCOUNT level to the Google Analytics account you wish to access.

It wont work at the Web property or the view level it must be the Account level.

like image 181
DaImTo Avatar answered Oct 13 '22 00:10

DaImTo