A few times now I’ve had to use the Google Drive Python API for projects – listing files in drive, modifying sheets etc. And it always takes me forever to figure out how to setup authentication properly! In my opinion the Google Python quickstart does not provide what most users are looking for. And neither do most of the high-ranking searches for this topic. Most users want to obtain an API key that they can use forever/set as an environment variable without having to refresh tokens, use pickle, or go through browser-based OAuth flows.
The good news is, there’s a crazy simple solution: service accounts! They’re not a hack; Google talks about and recommends them. But for whatever reason they’re a solution buried under OAuth alternatives. Service accounts are special “bot” accounts which are designed to be used by servers/scripts to access APIs.
First we’ll create our service account, then we’ll learn how to use and authenticate with it in our scripts.
Creating a service account
To create a service account, first go to the Google service accounts page. Click on Create Service Account.
Fill out the details. You’re smart enough to know what roles/permissions to give it for different projects. This will depend what project you’re working on, and whether the project is within a Google Organisation etc.
Note: if you’re using the service account to access Google Docs or Google Sheets, you may need to manually add the email address as a collaborator in the sharing section of the document.
The next step is to create credentials, so we can use our service account in Python. On the row where your new account is listed, go to Actions (three dots), then Create Key. Download it as JSON.
Cool, we can now use the key in Python…
Using a service account
I don’t know about you but I don’t like the default way of loading credentials from a JSON file. You don’t want to commit a file with credentials in to Git, so provisioning the file if you want your code to run on AWS/Heroku/Anywhere else is a pain. So we’re going to use an environment variable instead!
To create the environment variable, just take the contents of the JSON key file you downloaded, smush it all onto one line to make a string, and you’re done.
Now we can use the environment variable to build our API service. Here’s an example for the Google Drive API:
And here’s an example for Google Sheets:
You can then use the
service object as usual to do whatever you need to do.
Thanks for reading, hope this was helpful!