Google OAuth2 Build Google REST Api Service on Local

October 15, 2019
oauth2client or google-auth

The following code is only suitable to be used on local server/machine, as it will popup a browser at http://localhost:8090/ to perform account selection and save the credentials to a local file.

Subsequent call will read credential from local file.

OAuth Client Id and Secret

Goto Google Cloud Console -> Credentials

Create credentials -> OAuth Client Id

  • Application type: Web application
  • Name
  • Authorised redirect URIs: http://localhost:8090/ (port number might differ)

Download json and save to keys/oauth2-secret.json.

NOTE: This JSON file is security sensitive (store securely on server, never stored on client (e.g. Android))

google-auth

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
import logging

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import Flow, InstalledAppFlow
from google.auth.transport.requests import Request

log =...

scopes = [
    'https://www.googleapis.com/auth/photoslibrary.readonly'
    ]

creds = None
CREDENTIALS_FILE = 'keys/credentials.pickle'

if os.path.exists(CREDENTIALS_FILE):
    with open(CREDENTIALS_FILE, 'rb') as token:
        creds = pickle.load(token)

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'keys/oauth2-secret.json',
            scopes)
        creds = flow.run_local_server(port=8090)
        with open(CREDENTIALS_FILE, 'wb') as token:
            pickle.dump(creds, token)

service = build('photoslibrary', 'v1', credentials=creds)

results = service.mediaItems().list(
    pageSize=10
    ).execute()
items = results.get('mediaItems', [])
if not items:
    log.info('No items')
else:
    for item in items:
        log.info(item['filename'])

oauth2client (deprecated)

pip install --upgrade google-api-python-client oauth2client

NOTE: oauth2client is deprecated with v4.1.3 released on Sep 8, 2018, replace with google-auth

import logging

from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

log = ...

scopes = 'https://www.googleapis.com/auth/photoslibrary.readonly'

store = file.Storage('keys/credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('keys/oauth2-secret.json', scopes)
    creds = tools.run_flow(flow, store)

service = build('photoslibrary', 'v1', http=creds.authorize(Http()))

# get photos
results = service.mediaItems().list(
    pageSize=10
    ).execute()
items = results.get('mediaItems', [])
if not items:
    log.info('No items')
else:
    for item in items:
        log.info(item['filename'])
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.