Google API Helper

Ferris’ Google API Helper makes it easy to use Google’s recommended best practices when interacting with Google APIs via the Google API Client Library.

Building Clients

Once you’ve obtained credentials using OAuth2 it’s fairly straightforward to build a client.

ferris.core.google_api_helper.build(serviceName, version, credentials)[source]

Build a Google API client and caches it in the in-process cache. This reduces the number of calls to the discovery API as well as making it easy to share the client across multiple parts of code with little effort.

Usage is exactly like apiclient.discovery.build:

drive = build("drive", "v2", credentials)

Exponential Backoff

Google recommends using exponential backoff when making API requests. This is especially important when making lots of calls. The helper provides a couple of utilities for this purpose.

ferris.core.google_api_helper.retry_execute(request)[source]

Executes the given request from the Google API client and applies the appropriate retry policy. This ensures that if your request fails due to internal server error or quota denial the request will be automatically retried.

Example:

request = service.files().list()
result = retry_execute(request)
ferris.core.google_api_helper.retries(f)[source]

Shortcut decorator that uses the appropraite retry policy for dealing with Google APIs.

Will retry if an HttpError in the 5xx range is raise, but will fail if the error is in the 4xx range.

This is useful over retry_execute because it can retry an entire function, not just a single request.

Example:

@retries
def rename_file():
    client = build('drive', 'v2')
    client.files().update(fileId="123", data={"name": "Test"}).execute()

Discovery Document Caching

The API Client uses a discovery document to determine information about an API. The helper ensures that this document is cached so that building a client doesn’t incur reloading the discovery document every time. You do not have to do anything to take advantage of this; it happens automatically.