Google Auth in Python for API Access

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

Connect with Python

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.

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)

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’]

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