How to authorize a Python Google API client service given an OAuth2 access_token?

4.8k views Asked by At

I have implemented the python-social-auth library for Google OAuth2 in my Django project, and am successfully able to log users in with it. The library stores the access_token received in the response for Google's OAuth2 flow.

My question is: use of the google-api-python-client seems to rely on creating and authorizing a credentials object, then using it to build an API service like so:

...
# send user to Google consent URL, get auth_code in response

credentials = flow.step2_exchange(auth_code)
http_auth = credentials.authorize(httplib2.Http())

from apiclient.discovery import build
service = build('gmail', 'v1', http=http_auth)

# use service for API calls...

Since I'm starting with an access_token provided by python-social-auth, how do I create & authorize the API client service for future API calls?

Edit: to clarify, the code above is from the examples provided by Google.

3

There are 3 answers

2
danielx On BEST ANSWER

Given you already have the OAuth2 access token you can use the AccessTokenCredentials class.

The oauth2client.client.AccessTokenCredentials class is used when you have already obtained an access token by some other means. You can create this object directly without using a Flow object.

Example:

import httplib2
from googleapiclient.discovery import build
from oauth2client.client import AccessTokenCredentials

credentials = AccessTokenCredentials(access_token, user_agent)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('gmail', 'v1', http=http)
1
Mohamed Karim Bouaziz On

You can check examples provided by Google Guide API, for example: sending email via gmail application, https://developers.google.com/gmail/api/guides/sending

0
Tanmay Singhal On

If you have an already refreshed latest access token which is not expired, then you can get service variable as:

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials


creds = Credentials("<ACCESS_TOKEN>")
service = build('gmail', 'v1', credentials=creds)

# Call the Gmail API