Google OAuth2 Build Google REST Api Service on Local

Oct 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 loggingfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import Flow, InstalledAppFlowfrom google.auth.transport.requests import Requestlog =...scopes = [    'https://www.googleapis.com/auth/photoslibrary.readonly'    ]creds = NoneCREDENTIALS_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 loggingfrom apiclient.discovery import buildfrom httplib2 import Httpfrom oauth2client import file, client, toolslog = ...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 photosresults = 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'])

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.