Google Auth in Python for API Access

Connect with Python

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

Authenticate New User Token

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

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

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.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

3 Keys to Securing Your Open Source Supply Chain

Top 10 Asp .Net Development Companies In The World

Boost Productivity, Create Company-Wide Efficiency With Citizen Developers

Implementing EIGRP Routing Protocol: Explanation and Tutorial

CSS Grid vs. Flexbox vs. Bootstrap: Which Should You Use and When?

C# Jagged Array (Array of Arrays)

Jamcracker DevOps Framework (JDF)

LIVE VIDEO STREAMING using OPEN-CV and SOCKET_PROGRAMMING

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.

More from Medium

Language Translator using Python & Strategy design pattern

How to Create a MongoDB API Endpoint on a Multi-Page Dash App

Build the Forest in Python Series: Make the Forest Thread-Safe

Python3 — fixing gunicorn and flask