1
votes

I'm trying to access a user's activity in google analytics using python 3.7...I've gone through the process of getting an access token and using the code from here

https://developers.google.com/analytics/devguides/reporting/core/v4/user-reporting

The credentials work if I'm just downloading aggregate data but when I use this approach I get a 401 message that says

"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential., "status": "UNAUTHENTICATED"

If I go to the OAuth 2.0 Playground, the access token works fine. Any ideas what I'm missing here? Thanks.

url = 'https://analyticsreporting.googleapis.com/v4/userActivity:search'

payload = {
    "viewId": "xxx",
    "user": {
       "type": "CLIENT_ID",
       "userId": "xxx"
      },
"dateRange": {
    "startDate": "2019-06-13",
    "endDate": "2019-10-05",
   }
  }

hed = {
   'Authorization': 'Bearer ' + access_token,
   'Content-type': 'application/json'
 }

  r = requests.post(url, data=payload, headers=hed)
1
More info...if I just do r = requests.get(url) and print the results, it says the requested URL was not found on this server...that url is what google says I should be using.Allen

1 Answers

0
votes

You can use Google Service Account to get a token to send requests go Google Analytics API. Google Service Account is actually an implementation of RFC7523.

First, you need to create a Google Service Account, then you can use Authlib AssertionSession to access Google Analytics API directly.

Follow this guide Access Google Analytics API in Python.