Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Accessing Google Analytic's Real-Time API
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
import httplib2
import json
# easy access to account/view/property when using multiple accounts (e.g., ios app, android app, website)
with open('/Users/adrianp/py/json/ga_cred.json') as p:
gc = json.load(p)
# get this from your google developers assumes you've already authorized the analytics api/etc
with open('/Users/adrianp/py/json/client_secrets.json') as p:
o = json.load(p)
# must set the scope to use a particular service
ga_real_scope = ''
# run through the OAuth flow and retrieve credentials
# very clear example of how to auth i found here:
flow = OAuth2WebServerFlow(o['installed']['client_id'], o['installed']['client_secret'], ga_real_scope, o['installed']['redirect_uris'][0])
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: {0}'.format(authorize_url)
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
# create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)
service = build('analytics', 'v3', http=http)
active_users =
ids='ga:' + gc['site']['view'],
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment