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