OAuth2 Google Calendar API Full Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import flask | |
import google.oauth2.credentials | |
import google_auth_oauthlib.flow | |
import os | |
from flask import Flask | |
from flask import redirect | |
from flask import request | |
from googleapiclient.discovery import build | |
# set up a Flow object that reads the clients from our secrets file with the | |
# corresponding scope | |
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( | |
'client_secrets.json', | |
scopes=['https://www.googleapis.com/auth/calendar']) | |
# indicate the redirect URI that we placed in the console redirect URI when we | |
# created the oauth credentials | |
flow.redirect_uri = 'http://localhost:8080/oauth2redirect' | |
# generates the auth URL that we need to redirect users to where the user | |
# gets the oauth consent screen and we get the access code to later exchange for an | |
# auth token | |
authorization_url, _ = flow.authorization_url( | |
# enables us to grab a refresh token without the user granting us access | |
# a second time if needed | |
access_type='offline', | |
include_granted_scopes='true') | |
# create our Flask web app | |
app = Flask(__name__) | |
# this allows transport over HTTP for development purposes, if excluded | |
# HTTPS is needed | |
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' | |
@app.route("/test-api-request") | |
def test_api_request(): | |
"""Tests an API request to Google Calendar.""" | |
# grab the credentials from our flask session, in production | |
# you will probably store this in some persistent database per user | |
credentials = google.oauth2.credentials.Credentials( | |
**flask.session['credentials']) | |
# build the Google Calendar service which we use to represent the Google Calendar | |
# API | |
gcal = build('calendar', 'v3', credentials=credentials) | |
# grabs Google Calendar events for the particular user who authorized the app | |
events_result = gcal.events().list(calendarId='primary', | |
maxResults=10, singleEvents=True).execute() | |
# return a JSON response to the front end that shows the results | |
return { | |
"msg": "successfully processed request", | |
"data": events_result | |
} | |
@app.route("/authorize-user") | |
def auth_user(): | |
""" | |
Redirects a user to Google's authorization server to show the OAuth | |
Consent screen and get user consent. | |
""" | |
return redirect(authorization_url) | |
@app.route("/oauth2redirect") | |
def oauth2_redirect(): | |
""" | |
The redirect URI that Google hits after user grants access in the OAuth | |
consent screen where we fetch the access token from the access code given in the | |
URL and set them in the flask session. | |
""" | |
# grabs the URL response from the redirect after auth | |
authorization_response = request.url | |
# fetchs the access code from the request url response | |
# and then exchanges it for the token | |
flow.fetch_token(authorization_response=authorization_response) | |
# grab and set credentials into your flask session | |
# TODO: in production move these credentials to a persistent data store. | |
credentials = flow.credentials | |
flask.session['credentials'] = { | |
'token': credentials.token, | |
'refresh_token': credentials.refresh_token, | |
'token_uri': credentials.token_uri, | |
'client_id': credentials.client_id, | |
'client_secret': credentials.client_secret, | |
'scopes': credentials.scopes} | |
return flask.redirect(flask.url_for('test_api_request')) | |
if __name__ == "__main__": | |
app.secret_key = "development" | |
app.run(port=8080, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment