Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Hello Analytics - Google Analytics Core Reporting API v4
# -*- coding: utf-8
"""A simple example of how to access the Google Analytics API."""
import argparse
import gav4
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
def get_service(api_name, api_version, scope, key_file_location,
"""Get a service that communicates to a Google API.
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scope: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account p12 key file.
service_account_email: The service account email address.
A service that is connected to the specified API.
credentials = ServiceAccountCredentials.from_p12_keyfile(
service_account_email, key_file_location, scopes=scope)
http = credentials.authorize(httplib2.Http())
# Build the service object.
service = build(api_name, api_version, http=http)
return service
def get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.
# Get a list of all Google Analytics accounts for this user
accounts =
if accounts.get('items'):
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
# Get a list of all the properties for the first account.
properties =
if properties.get('items'):
# Get the first property id.
property = properties.get('items')[0].get('id')
# Get a list of all views (profiles) for the first property.
profiles =
if profiles.get('items'):
# return the first view (profile) id.
return profiles.get('items')[0].get('id')
return None
def get_v3_request(profile_id):
# Use the Analytics Service Object to build query the Core Reporting API v3
# for the number of sessions within the past seven days.
return {
"ids": 'ga:' + profile_id,
"start_date": '7daysAgo',
"end_date": 'today',
"metrics": 'ga:sessions'}
def main():
# Define the auth scopes to request.
scope = ['']
# Use the developer console and replace the values with your
# service account email and relative location of your key file.
service_account_email = '<Replace with your service account email address.>'
key_file_location = '<Replace with /path/to/generated/client_secrets.p12>'
# Authenticate and construct service.
service = get_service('analyticsreporting', 'v4', scope, key_file_location,
profile = 'YOUR_VIEW_ID'
v3_request = get_v3_request(profile)
v4_request = gav4.convert_request(**v3_request)
v4_response = service.reports().batchGet(body=v4_request).execute()
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment