Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
import httplib2
from googleapiclient.discovery import build
from googleapiclient.http import HttpError
from oauth2client.client import SignedJwtAssertionCredentials
def get_metrics():
# load the service account key
# this key is managed here -
filename = 'YOUR-KEY-FILE.p12'
f = file(filename, 'rb')
key =
# create the credentials
credentials = SignedJwtAssertionCredentials('', key, scope='')
# authorize the http instance with these credentials
http = httplib2.Http()
http = credentials.authorize(http)
# construct a resource object for interacting with an api
service = build('analytics', 'v3', http=http)
# build the query
# your profile id can be found by heading to google analytics, selecting your profile, clicking the admin button,
# and then clicking view settings under the view column, the id is labelled 'View ID'
# you can see the available metrics here:
api_query =
metrics='ga:users, ga:sessions, ga:avgSessionDuration, ga:pageviews, ga:pageviewsPerSession, ga:percentNewSessions, ga:bounceRate',
# default value
metrics = None
# run it
result = api_query.execute()
values = result['rows'][0]
# covert the average session to minutes and seconds
minutes, seconds = divmod(int(float(values[2])), 60)
# the order below is the same as the order the metrics were listed above
metrics = {
'users': values[0],
'sessions': values[1],
'avg_session': '%d:%02d' % (minutes, seconds),
'pageviews': values[3],
'pages_session': '%.2f' % float(values[4]),
'new_sessions': '%.2f' % float(values[5]) + '%',
'returning_sessions': '%.2f' % (100 - float(values[5])) + '%',
'bounce_rate': '%.2f' % float(values[6]) + '%'
# handle errors in constructing a query
except TypeError, error:
print ('There was an error in constructing your query : %s' % error)
# handle api service errors
except HttpError, error:
print ('There was an API error : %s : %s' % (error.resp.status, error._get_reason()))
return metrics
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment