Yuva
Yuva

Reputation: 3153

googleapi python how to fetch / refresh access token

I am trying to setup Google Analytics to one of my blog website. I am using the google api client library. The code works fine if I manually get the access token from the site:

https://developers.google.com/oauthplayground/. I am finding difficult to have the access_token refreshed. Can someone please guide me on this?

The Python code snippet:

import httplib2
import httplib2 as lib2
import google.oauth2.credentials
# from google.auth.transport import requests
import requests
from google_auth_httplib2 import AuthorizedHttp
from oauth2client import client, GOOGLE_TOKEN_URI

from googleapiclient.discovery import build as google_build

# This is consistent for all Google services
token_uri = 'https://accounts.google.com/o/oauth2/token'

# WORKING CODE BUT REQUIRES VALID ACCESS_TOKEN
credentials = google.oauth2.credentials.Credentials(None,
                                                    refresh_token=refresh_token,
                                                  token_uri='https://accounts.google.com/o/oauth2/token',
                                                    client_id=client_id,
                                                    client_secret=client_secret)

credentials = google.oauth2.credentials.Credentials(access_token)
authorized = AuthorizedHttp(credentials=credentials)
print(access_token)

# API Name and Verison, these don't change until
# they release a new API version for us to play with.
api_name = 'analyticsreporting'
api_version = 'v4'

# Let's build the client
api_client = google_build(serviceName=api_name, version=api_version, http=authorized)

sample_request = {
    'viewId': 'xxxxxxxx',
    'dateRanges': {
        'startDate': datetime.strftime(datetime.now() - timedelta(days=120), '%Y-%m-%d'),
        'endDate': datetime.strftime(datetime.now(), '%Y-%m-%d')
    },
    'dimensions': [{'name': 'ga:date'}],
    'metrics': [{'expression': 'ga:sessions'}]
}

response = api_client.reports().batchGet(
    body={
        'reportRequests': sample_request
    }).execute()
print(response)

I have kept the ACCESS_TOKEN as none to fetch the initial access token, which seems to work, when I print it, but I couldnt get a way to refresh this access_token, using this credential API, since this doesn't have expires_at or expiry attributes as well. The URL Scope would be 'https://www.googleapis.com/auth/analytics.readonly'

When running the above code to refresh ACCESS TOKEN,I am making the error:

Traceback (most recent call last):
  File "E:/PyCharm_Workspace/MLPractices/GA3.py", line 78, in <module>
    'reportRequests': sample_request
  File "E:\PyCharm_Workspace\MLPractices\venv\lib\site-packages\googleapiclient\_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "E:\PyCharm_Workspace\MLPractices\venv\lib\site-packages\googleapiclient\http.py", line 901, in execute
    headers=self.headers,
  File "E:\PyCharm_Workspace\MLPractices\venv\lib\site-packages\googleapiclient\http.py", line 177, in _retry_request
    resp, content = http.request(uri, method, *args, **kwargs)
  File "E:\PyCharm_Workspace\MLPractices\venv\lib\site-packages\google_auth_httplib2.py", line 213, in request
    self.credentials.refresh(self._request)
  File "E:\PyCharm_Workspace\MLPractices\venv\lib\site-packages\google\oauth2\credentials.py", line 172, in refresh
    "The credentials do not contain the necessary fields need to "
google.auth.exceptions.RefreshError: The credentials do not contain the necessary fields need to refresh the access token. You must specify refresh_token, token_uri, client_id, and client_secret.

Upvotes: 1

Views: 9723

Answers (2)

Yuva
Yuva

Reputation: 3153

Thank you all. Could get the google analytics access by using Service Account credentials, instead of OAUTH - client_secrets. Using service account seem to be simple as now i dont need to refresh any tokens.

But i am thinking which one is better, and more secured, any thoughts please. Also this is the most recent reference to access Google Analytics V4, having released in 2020 Reference: https://www.jcchouinard.com/google-analytics-api-using-python/

Upvotes: 0

saravana kumar
saravana kumar

Reputation: 131

You will get the refresh token with access token for the first time. Your refresh token is long lived. So you can store it to somewhere in database so that you can use it later. Whenever you need a access token use that refresh token and generate the new one.

Google API: getting Credentials from refresh token with oauth2client.client

Above the link will help you.

Upvotes: 0

Related Questions