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

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.google<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>apis.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#.

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.