Google Auth in Python for API Access

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 = ‘'
# 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(
# 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(
credentials.expiry = datetime.fromtimestamp(
# 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 = (
+ <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’]



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Zachary Smith

Zachary Smith

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