Google APIs

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

ferris3.google_apis.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 similar to apiclient.discovery.build, however, instead of passing an http instance you just pass in valid credentials and this method will handle constructing an appropriate http instance for you.

Example:

credentials = oauth2.build_service_account_credentials(["https://www.googleapis.com/auth/drive"])
drive = build("drive", "v2", credentials)

As demonstrated, valid credentials can be obtained with the help of ferris3.oauth2 or with any valid credentials from Google’s oauth2client.

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.

ferris3.google_apis.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)
ferris3.google_apis.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.