Configuring OAuth 2.0 access to the Google APIs
In an increasingly data-driven world with unprecedented access to technology just a few clicks away, being able to connect our code to leverage online platforms is crucial now more than ever.
In this blog post we’re going to cover step-by-step how to generate the necessary credentials to access the variety of services offered by the Google APIs (NOTE: we’ll be using Python for the code section at the end but the steps are almost completely independent of the programming language you’re using)
Getting into Google Cloud Platform
On top of being one of the largest cloud providers in the world, Google Cloud Platform (GCP) will be our gateway for accessing the Google API ecosystem. The GCP console will allow us to generate credentials, enable APIs, and centralize our access with a clean user interface.
Fortunately Google automatically gives all Gmail users a GCP console so no signup or configurations are necessary – all you need is an account with Google. Head on over to https://console.cloud.google.com/ and let’s get started!
Creating a project
The first step to getting API access is to create a project with GCP. Think of this as an independent collection of resources, permissions, etc. that are logically organized into a single project.
We’ll use this project to manage the APIs we’ll be enabling – to create it:
- Click the Select a project dropdown
- Click NEW PROJECT on the popup
- Type the name of your project
- Click CREATE
Now that we’ve created our project, go ahead and select it from the Select a project dropdown to set the context of our console to our freshly created project.
Registering an app
The next step before generating our credentials is to setup an OAuth consent screen and register an app. Don’t worry if you’re not planning on developing an actual end-user application – this is just something to associate our credentials with.
- Click the Navigation menu hamburger button
- Hover over APIs & Services and click OAuth consent screen
- Select External
- Click CREATE
Now go ahead and fill out information regarding our app.
TIP: only App name, User support email, and Developer contact information is required at this stage. Don’t worry about setting scopes or permissions, we’ll get to that later!
- Fill out the App information form
- Keep clicking SAVE AND CONTINUE until you get to the Summary screen
- Click BACK TO DASHBOARD at the bottom
- Click PUBLISH APP and confirm
Congratulations! Our app is registered and we can now create our credentials.
Creating credentials
The goal here is to create OAuth 2.0 Client IDs. This will provide us with necessary credentials for authorizing the API (and our code) to access our data.
- Click Credentials under APIs & Services
- Click CREATE CREDENTIALS
- Select the Application type dropdown and choose Desktop app (your use case may vary)
- Click CREATE
Now that we’ve successfully created a Client ID and Client Secret, go ahead and download the provided JSON somewhere safe as we’ll need that in a moment.
- Click DONWLOAD JSON
- Click OK
Enabling API access
For the sake of this tutorial we’re going to enable the Google Drive API. Feel free to follow along by enabling whatever API you need as the process will be the same.
- Click Library under APIs & Services
- Find the API we want to enable
- Click Enable
Optional: to track enabled APIs and their usage, click Dashboard under APIs & Services for a clean graphical view. See here to explore the APIs Google has to offer.
While we’re at it, let’s also go and copy the scopes we’ll need. You can find a complete list of scopes here – these URLs are used to let Google know during the user consent process what access our code is requesting from the user.
TIP: We recommend following security best practices and only giving the minimum amount of scope needed for you app to do what it needs to do.
Acquiring OAuth 2.0 tokens
For the final step we’re going to jump into some code and write some Python. If you would prefer a different language, check out some of Google’s other quickstarts!
Prerequisites (as indicated by Google’s Python Quickstart):
- Python 2.6 or greater.
- The pip package management tool
- A Google Cloud Platform project with the API enabled (recall for this example we’re using the Drive API)
First install the Google client library from your command line:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
And now for the big moment! It’s time to open up a user consent screen and authorize our code to access our data via the API.
The following code snippet opens the consent screen in our browser and writes the returned access and refresh tokens to a JSON file (assuming we authorize the access)
from google_auth_oauthlib.flow import InstalledAppFlow
# JSON downloaded in Step 4
CLIENT_SECRETS_FILE = "/path/to/credentials.json"
# Scope copied in Step 5
SCOPES = ["https://www.googleapis.com/auth/drive"]
# Filepath to save our refresh and access tokens
TOKEN_FILE = "token.json"
# Open user consent screen in browser
flow = InstalledAppFlow.from_client_secrets_file(
client_secrets_file=CLIENT_SECRETS_FILE,
scopes=SCOPES
)
creds = flow.run_local_server(port=0)
# Save the tokens
with open(TOKEN_FILE, "w") as outjson:
outjson.write(creds.to_json())
TIP: You might get a warning saying your app is unverified. That’s okay! We’re the ones that created the app so we of course know our own app is safe and can continue.
If you want to expose your app to end-users, you will have to go in and verify your app.
Congratulations! With that we have now saved valid access and refresh tokens to a JSON file for authenticating requests through the Google APIs. The hard part is over and we’re ready to start working with our data.
Refreshing an expired access token
Access tokens provided by Google are short-lived and need to be refreshed frequently to maintain authenticated access.
The Google Python client library provides us with safe, high-level functions for abstracting the refresh process and keeping our credentials up to date.
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
# The token file we created in Step 6
TOKEN_FILE = "token.json"
creds = Credentials.from_authorized_user_file(filename=TOKEN_FILE)
if creds.expired:
creds.refresh(Request())
Using the route1.io Python connectors
At route1.io, we’ve pulled together an open source Python package that provides various high-level wrappers and installs all the packages you need for some of marketing analytics most common APIs.
In the context of Google, we’ve provided OAuth 2.0 abstractions that will manage Steps 6 & 7 for you in just a single function call.
To get started just install:
pip install route1io-connectors
And then copy-paste this code snippet to get on your way with authorized and authenticated credentials:
SCOPES = ["https://www.googleapis.com/auth/drive"]
CLIENT_SECRETS_FILE = "/path/to/credentials.json"
TOKEN_FILE = "token.json"
creds = get_token_from_full_auth_flow(TOKEN_FILE, CLIENT_SECRETS_FILE, SCOPES)
Drop us a line
Don’t know where to get started? Looking for one of our software engineers to lend a helping hand? Feel free to contact us!