Skip to content

Instantly share code, notes, and snippets.

Created July 25, 2016 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/b102d536369baee7b5d752b13ebdf995 to your computer and use it in GitHub Desktop.
Save anonymous/b102d536369baee7b5d752b13ebdf995 to your computer and use it in GitHub Desktop.
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,
service_account_email):
"""Get a service that communicates to a Google API.
Args:
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.
Returns:
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 = service.management().accounts().list().execute()
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 = service.management().webproperties().list(
accountId=account).execute()
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 = service.management().profiles().list(
accountId=account,
webPropertyId=property).execute()
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 = ['https://www.googleapis.com/auth/analytics.readonly']
# 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,
service_account_email)
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()
print(v4_response)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment