Quickstart and Basic Usage¶
Authorizing server to server communications with Google’s APIs should be easy. This library attempts to streamline this process. Here we will describe all the steps needed to Authorize yourself with Google’s services and make requests to the API, without going through a three-party oauth flow.
Storing the credentials¶
It is generally bad practice to store sensitive information in code. For this reason, the GClient Service Account Auth supports accessing sensitive information from environment variables. Instead of passing the email and key into AuthorizedService directly, this information can be stored in environment variables.
If you store the service account email in the environment variable GCLIENT_SERVICE_ACCOUNT_EMAIL, and a path to the private key in the environment variable GCLIENT_KEY_LOCATION, then this library will automatically fetch the appropriate information, without you having to include the email and key arguments for AuthorizedService.
If this information is stored in environment variables, creating an authorized service is as simple as
Using the instance to access an API¶
Once you have an AuthorizedService object, you can make calls using the python interface defined by Google’s apiclient library through the service attribute of your AuthorizedService object. For example, the Google Analytics API provides a number of methods, one of which is the data method, which we will show an example of calling below
from service_account_auth import AuthorizedService ga_service = AuthorizedService( 'myproject-id-888', 'analytics', 'v3' ) data = ga_service.service.data().ga().get( ids='ga:88888888', dimensions='ga:browser', metrics='ga:pageviews', start_date='2015-01-19', end_date='2015-01-20' ).execute()
The example above gets data on the number of pageviews by browser made to our site tracked by google analytics.
Knowing what methods to call does require some knowledge of what methods are available. For Google Analytics in particular it would be useful to use an external library to simplify the interface.
Use with other libraries¶
The GA Grab library can be used to make querying Google Analytics much easier.
Google provides python client libraries for many of its APIs. This library can create authorized service objects for the following APIs:
- Created with AuthorizedService('proj-id', 'bigquery', 'v2').
- Analytics Read-only
- Created with AuthorizedService('proj-id', 'analytics-read', 'v3').
- Analytics Read/Write
- Created with AuthorizedService('proj-id', 'analytics', 'v3').
For many of those not listed here, support is as simple as providing the correct scope url for the API. Contributions are appreciated, even as simple as filing an issue. See Contributing.