Google Auth in Python for API Access

Zachary Smith
5 min readApr 25, 2019

A simple, straightforward guide to authenticating access to Google apps API interface in Python

Connect with Python

Since I have been unable to find a post that concisely describes how to use Google’s “Google Auth Library for Python”, I thought I would create one.

This guide will assume that you know how to create a project on Google Developer Console and obtain the “client secrets” for that project. It will also assume that you are able to navigate the documentation for Google APIs to be able to build out request strings and parameters as is necessary for your application.

I am going to outline a straightforward presentation of the classes that make it easy to flow through the process of obtaining an “authenticated user token”. This token enables initialization of an authorized session through which requests can be made. Also, how to refresh an already authenticated and saved token to obtain an authorized session for making requests.

Finally, a note on security before we get started. Since this API allows you to build applications which access many Google Apps through a person’s Google Account, I highly suggest being careful with the client secrets file and the user authentication token, should you choose to save these somewhere. (The client secrets file you will have to save somewhere.) At the very least add these files to your .gitignore and keep them out of any git repositories.

There’s more than one way to write a program, so just pick something.

This is the easiest process that I have figured out for authenticating a user token to access Google Drive, Sheets, Word, etc. Being in an organization that uses all of these Google products and frequently saves important data in Sheets, I find this especially useful. I have the need to analyze some of that data, using the API allows me to cut out the tedious process of saving a Sheet locally. Also, allowing me to avoid keeping all those files organized on disk. Not to mention that the data stays realtime.

The libraries we will be using are google-auth (https://google-auth.readthedocs.io/en/latest/user-guide.html) and google-auth-oauthlib (https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.html). There is one class that makes it easy to obtain a new user authentication token, google_auth_oauthlib.flow.Flow. Then to use a saved token you will need two other classes — google.auth.transport.requests.AuthorizedSession & google.oauth2.credentials.Credentials.

From here it’s really simple. As I’ve said, there are two work flows — one performing authorization that generates a user token and another using a saved user token and refreshing it. If you don’t already have a user token, you will have to use the first process above to get that token, which can be saved for later use in the second process.

Authenticate New User Token

There are several ways to handle generating the token, the easiest of which is to print the authorization URL to the terminal for copy and paste into a browser. Then prompt the user for the authentication token and wait for input to continue.

from google_auth_oauthlib.flow import Flow
import json
# Name of client secrets file
client_secrets_filename = ‘client_secrets.json’
# Set the scope - can be a list of scope strings
scope = ‘https://www.googleapis.com/auth/spreadsheets'
# Load the client secrets file
with open(client_secrets_file, "r") as read_file:
client_secrets_dict = json.load(read_file)
# Initialize flow object
flow = Flow.from_client_secrets_file(
client_secrets_file=’client_secrets_filename’,
scopes=scope,
redirect_uri=client_secrets_dict[‘installed’][‘redirect_uris’]
)
# Get authorization url
auth_url, _ = flow.authorization_url(prompt=’consent’)
print(‘Please go to this URL: {}’.format(auth_url))# Input authorization code
code = input(‘Enter the authorization code:’)
token = flow.fetch_token(code=code)# Obtain authorized session
session = flow.authorized_session()

Reuse Saved User Token

You may want to allow your application to save the user’s token to be loaded later and reused. This avoids the steps required to utilize the authentication URL and to enter the authorization code into the command line. In these situations we can simply refresh this token and use it to create an authorized session.

from google.auth.transport.requests import AuthorizedSession
from google.oauth2.credentials import Credentials
from datetime import datetime
import json
# Load saved token
with open(token_filename, 'r') as read_file:
token_dict = json.load(read_file)
# Initialize credentials object
credentials = Credentials(
token=token_dict[‘access_token’],
refresh_token=token_dict[‘refresh_token’],
id_token=token_dict[‘id_token’],
token_uri=token_dict[‘refresh_uri’],
client_id=token_dict[‘client_id’],
client_secret=token_dict[‘client_secret’],
scopes=token_dict[‘scope’]
)
credentials.expiry = datetime.fromtimestamp(
float(token_dict['expires_at'])
)
# Obtain authorized session
session = AuthorizedSession(credentials)

Now that we have an authorized session object, we simply have to create the appropriate Google API request string and parameter set and give them to a session.get() request. Then, by adding .json() to the end, the returned request will be a Python dictionary.

Example Request

Here is an example of setting up a request to push data to a specific range within a Sheet. The structure and necessary fields in the req_st and parameters variables are specified in the Sheets API documentation.

req_str = (
‘https://sheets.googleapis.com/v4/spreadsheets/'
+ <spreadsheet_id>
+ ‘/values:batchUpdate’
)
parameters = {
‘valueInputOption’: ‘RAW’,
‘data’: {
‘range’: <worksheet_name> + ‘!’ + <sheet_range>,
‘majorDimension’: <major_dimension>, # ‘ROWS’ or ‘COLUMNS’
‘values’: <data>
}
}
# Make HTTP request
sheet_data = session.get(req_str, params=param).json()
# Select sheet data out of all other information related
# to request response
values = sheet_data[‘valueRanges’][0][‘values’]

As you can see, once we have an authorized session, we can use Google’s API documentation as a guide for building all sorts of requests.

Of note though, is that the token allow generation of a session that will only have access to the scope you have initialized the token with. For example if you generated the session with a token authenticated in a scope allowing access to Sheets, but try to make a request to Docs, you will get an error.

That’s it. It really is that simple to get set up to make requests of Google’s API. I invite you to look over the documentation of both google-auth and google-auth-oauthlib as they both have many more options and features than I have described here.

--

--

Zachary Smith

Engineer and Data Scientist. Creative and Maker. Straddling the world of artist and engineer.