Google Analytics API request (python)

Google Analytics Reporting Api gives you a lot of possibilities like downloading your data without sampling, exporting it to databases or just ability to work with raw data (for example in Jupyter Notebooks).
The easiest way I`ve found to make a API request to Google Analytics:

1. Create a Google Cloud Platform project and enable the Google Analytics Reporting API:
https://console.developers.google.com/start/api?id=analyticsreporting.googleapis.com&credential=client_key

2. Create the service account, create and download a private key:
https://console.developers.google.com/iam-admin/serviceaccounts

3. Add the email of your servise account as a user to your Google Analytics account.

4. Install the client library:
pip install --upgrade google-api-python-client

5. Run the code (replace ‘your_private_key.json’ and ‘Google Analytics view ID’ with your values)

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'your_private_key.json'
VIEW_ID = 'Google Analytics view ID'

def initialize_analyticsreporting():
    credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES)
    analytics = build('analyticsreporting', 'v4', credentials=credentials)
    return analytics

def get_report(analytics):
    return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}],
          'dimensions': [{'name': 'ga:date'}]
        }]
      }
  ).execute()

response = get_report(initialize_analyticsreporting())
print(response)

This request will return you data in json format, but you can transform it into the Pandas dataframe for easier manipulation. I`ve found the great function that would do that here:
https://www.themarketingtechnologist.co/getting-started-with-the-google-analytics-reporting-api-in-python/

import numpy as np
import pandas as pd
def print_response(response):
    list = []
    for report in response.get('reports', []):
        columnHeader = report.get('columnHeader', {})
        dimensionHeaders = columnHeader.get('dimensions', [])
        metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
        rows = report.get('data', {}).get('rows', [])
        for row in rows:
            dict = {}
            dimensions = row.get('dimensions', [])
            dateRangeValues = row.get('metrics', [])
            for header, dimension in zip(dimensionHeaders, dimensions):
                dict[header] = dimension
            for i, values in enumerate(dateRangeValues):
                for metric, value in zip(metricHeaders, values.get('values')):
                    if ',' in value or '.' in value:
                        dict[metric.get('name')] = float(value)
                    else:
                        dict[metric.get('name')] = int(value)
            list.append(dict)
        df = pd.DataFrame(list)
        return df
print(print_response(response))

More info:
https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py

Leave a Reply

Your email address will not be published. Required fields are marked *

www.000webhost.com