Service account credentials with the Python client for the Google Drive API (v3)

EDIT: Get the full code for this post on Github. This article only contains important snippets of code that require explanation.

There are numerous ways to authenticate against the Google Drive API. If you have an application running on Google Compute Engine that needs to access Drive, a Service Account is probably the easiest way to do it. One use case is for an application to write reports or log files to Drive so that users can see them without logging into a server. Before you try this example, go through all of the steps in Google’sĀ Using OAuth 2.0 for Server to Server Applications guide and save your service account’s private key locally in JSON format. Getting credentials from a service account file is easy:

SCOPES = [
        'https://www.googleapis.com/auth/drive'
    ]
SERVICE_ACCOUNT_FILE = './name-of-service-account-key.json'
credentials = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_FILE, scopes=SCOPES)

I like this approach better than assigned a service account to a VM, because it will also work locally for development. We’ll start by creating a folder, which is the easiest file type to create, because it doesn’t involve an upload:

folder_metadata = {
    'name': 'My Test Folder',
    'mimeType': 'application/vnd.google-apps.folder'
}
cloudFolder = service.files().create(body=folder_metadata).execute()

To upload a “real” file, you first need to create a MediaFileUpload object, and then create the file.

with tempfile.NamedTemporaryFile(mode='w') as tf:
    tf.write("This is some test data")
    media = MediaFileUpload(tf.name, mimetype='text/plain')
    cloudFile = service.files().create(body=file_metadata,
        media_body=media).execute()

These files won’t be visible to you, a human user, until you share them with yourself:

cloudPermissions = service.permissions().create(fileId=cloudFile['id'],
    body={'type': 'user', 'role': 'reader', 'emailAddress': userEmail}).execute()
cp = service.permissions().list(fileId=cloudFile['id']).execute()

Finally, here is an example showing how to list the files in a particular Drive folder:

query = "'{}' in parents".format(cloudFolder['id'])
filesInFolder = service.files().list(q=query, orderBy='folder', pageSize=10).execute()

The full Python example is available at https://github.com/cfinch/Shocksolution_Examples
If you would like a C# example, check out Linda Lawton’s Google Drive API example in C#.

8 thoughts on “Service account credentials with the Python client for the Google Drive API (v3)”

  1. You might want to fix the
    SCOPES = [
    ‘https://www.googleapis.com/auth/drive’
    ]

    line.

    Thank you for the post though, very helpful šŸ™‚

    1. You have to be kidding. I went to GitHub, pulled the file, edited one tiny line to use my xxx_secrets.json, and I was done.

      This blog post got a relative beginner started in two minutes. BTW — it’s easy enough to figure out what is missing from error messages and a little bit of Google if GitHub is too much of a bother.

      I don’t mean to be rude. I get bothered when people trash authors generous enough to give us free, usable code with no strings attached beyond the GPL terms.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.