I recently needed to display a visitor counter on a website by some client’s weird demand. Maybe the 90s are coming back. Anyway, I thought it makes sense to query Google Analytics directly, but Google’s API example were not really helping. After some digging around, I finally found a solution. You’ll need oauth2client and google-api-python-client for it to work. Then follow these instructions on Google Developers to create a service account that only has access to the API without the need for a human to request some oauth token. It will give you a private key to work with.
from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials import httplib2 def get_analytics_visitors(): Â Â Â f = file('privatekey.p12', 'rb') Â Â Â key = f.read() Â Â Â f.close() Â Â Â credentials = SignedJwtAssertionCredentials('[email protected]', Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â key, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â scope='https://www.googleapis.com/auth/analytics.readonly') Â Â Â http = httplib2.Http() Â Â Â http = credentials.authorize(http) Â Â Â service = build('analytics', 'v3', http=http) Â Â Â data_query = service.data().ga().get(**{ Â Â Â Â Â Â Â 'ids': 'ga:YOUR_PROFILE_ID_NOT_UA', Â Â Â Â Â Â Â 'metrics': 'ga:visitors', Â Â Â Â Â Â Â 'start_date': '2013-01-01', Â Â Â Â Â Â Â 'end_date': '2015-01-01' Â Â Â Â Â Â Â }) Â Â Â feed = data_query.execute() Â Â Â return feed['rows'][0][0]