The Task

Most Google API docs are difficult to follow, especially the Google Analytics API docs. One of the most challenging aspects of the Google Analytics 3 (Universal Analytics) Reporting API v4 I’ve encountered is the overall lack of applicable documentation. Most of the API docs provide examples that use OAuth 2.0 through a sign-in. However, some tasks (such as automation) need a simple approach that doesn’t require access to account-level information. This is where service accounts come in handy. After reading this article, you will learn how to interact with the Google Analytics Reporting API v4 with Python.

Google Cloud Console

The first thing we need to do is to create a project inside of Google Cloud Console here: https://console.cloud.google.com/projectcreate. From here, name your project, select an organization if applicable, and press ‘create.’

Next, we’ll need to enable the GA Reporting API. From the Home page of your new project, go to APIs & Services -> Dashboard. Then click ‘ENABLE APIS AND SERVICES.’

Next, search up Google Analytics Reporting and select the resulting API:

Then, click ‘ENABLE’:

Now, navigate to https://console.cloud.google.com/iam-admin/serviceaccounts/create and follow the steps to create your credentials for a service account. Make sure to add an owner role. You should now have a service account created:

Google Analytics Reporting API v4 with Python Enabled Service Account

Next, inside of the ‘KEYS’ section add a JSON key and download the file. Now we’re ready to use the Google Analytics Reporting API v4 with Python!

API Setup

For this task, we are going to use Python and the google-api-python-client package. Use the below command to install the library with pip:

py -m pip install google-api-python-client

Now the library should be installed. Let’s give our service account access to our GA account so that we can begin to use the API. You can find your service account email inside the IAM and Admin menu:

Google Analytics Reporting API v4 with Python Added Service Account

Finally, we can get into the code!

The Code

Here is a complete code example to get you started with querying data from your views:

"""Hello Analytics Reporting API V4."""

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


SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'json file goes here'
VIEW_ID = 'your view id'


def initialize_analyticsreporting():
  """Initializes an Analytics Reporting API V4 service object.

  Returns:
    An authorized Analytics Reporting API V4 service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  analytics = build('analyticsreporting', 'v4', credentials=credentials)

  return analytics


def get_report(analytics):
  """Queries the Analytics Reporting API V4.

  Args:
    analytics: An authorized Analytics Reporting API V4 service object.
  Returns:
    The Analytics Reporting API V4 response.
  """
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}],
          'dimensions': [{'name': 'ga:country'}]
        }]
      }
  ).execute()


def print_response(response):
  """Parses and prints the Analytics Reporting API V4 response.

  Args:
    response: An Analytics Reporting API V4 response.
  """
  print(response)
  
def main():
  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  print_response(response)

if __name__ == '__main__':
  main()

Make sure you change the top three variables to your values. SCOPES should stay the same as we are only using read-only permissions with this API.

Breakdown

First, the initialize_analyticsreporting() function creates a service object that enables us to define our specific Google API and credentials.

def initialize_analyticsreporting():
  """Initializes an Analytics Reporting API V4 service object.

  Returns:
    An authorized Analytics Reporting API V4 service object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  analytics = build('analyticsreporting', 'v4', credentials=credentials)

  return analytics

Second, the get_report(analytics) function uses the batchGet method to query data with the API. You can follow the docs here https://developers.google.com/analytics/devguides/reporting/core/v4/basics to build out queries based on available fields. Make sure you follow the syntax very closely.

def get_report(analytics):
  """Queries the Analytics Reporting API V4.

  Args:
    analytics: An authorized Analytics Reporting API V4 service object.
  Returns:
    The Analytics Reporting API V4 response.
  """
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}],
          'dimensions': [{'name': 'ga:country'}]
        }]
      }
  ).execute()

Third, the print_response(response) function prints out the JSON response provided by the second function.

def print_response(response):
  """Parses and prints the Analytics Reporting API V4 response.

  Args:
    response: An Analytics Reporting API V4 response.
  """
  print(response)

Finally, the main function executes all these functions in order and passes the resulting parameters.

def main():
  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  print_response(response)

As you can see. We can make a call to Google Analytics to retrieve JSON data without a sign-in or OAuth 2.0 token.

Google Analytics Reporting API v4 with Python Reponse

In conclusion, I hope this helps with automated reporting tasks where sign-in or user data isn’t required.

Need extra help? Sign-up here for tutoring: https://codedogtutoring.com/connect/