Hello Analytics Reporting API v4; Python quickstart for installed applications

This tutorial walks through the steps required to access the Analytics Reporting API v4.

1. Enable the API

To get started using Analytics Reporting API v4, you need to first use the setup tool, which guides you through creating a project in the Google API Console, enabling the API, and creating credentials.

Note: To create a Web Client ID or an Installed Application Client, you need to set a product name in the consent screen. If you have not done so already you will be prompted to Configure consent screen.

Create credentials

  • Open the Credentials page.
  • Click Create credentials and select OAuth client ID
  • For the Application type select Other.
  • Name the client ID quickstart and click Create.

From the Credentials page click into the newly created client ID, and click Download JSON and save it as client_secrets.json; you will need it later in the tutorial.

2. Install the client library

Using pip along with venv is the recommended way for installing Python packages: sudo -s apt-get install python3-venv python3 -m venv analytics-quickstart source analytics-quickstart/bin/activate pip install --upgrade google-api-python-client pip install --upgrade oauth2client

3. Setup the sample

You'll need to create a single file named HelloAnalytics.py, which will contain the given sample code.

  1. Copy or download the following source code to HelloAnalytics.py.
  2. Move the previously downloaded client_secrets.json to the same directory as the sample code.
  3. Replace the value of VIEW_ID. You can use the Account Explorer to find a View ID.
"""Hello Analytics Reporting API V4."""

import argparse

from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
CLIENT_SECRETS_PATH = 'client_secrets.json' # Path to client_secrets.json file.
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'


def initialize_analyticsreporting():
  """Initializes the analyticsreporting service object.

  Returns:
    analytics an authorized analyticsreporting service object.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      CLIENT_SECRETS_PATH, scope=SCOPES,
      message=tools.message_if_missing(CLIENT_SECRETS_PATH))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage('analyticsreporting.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

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

  return analytics

def get_report(analytics):
  # Use the Analytics Service Object to query the Analytics Reporting API V4.
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}]
        }]
      }
  ).execute()


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

  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:
      dimensions = row.get('dimensions', [])
      dateRangeValues = row.get('metrics', [])

      for header, dimension in zip(dimensionHeaders, dimensions):
        print header + ': ' + dimension

      for i, values in enumerate(dateRangeValues):
        print 'Date range (' + str(i) + ')'
        for metricHeader, value in zip(metricHeaders, values.get('values')):
          print metricHeader.get('name') + ': ' + value


def main():

  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  print_response(response)

if __name__ == '__main__':
  main()

4. Run the sample

Run the sample using:

python HelloAnalytics.py
  • The application will load the authorization page in a browser.
  • If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.

When you finish these steps, the sample outputs the number of sessions for the last seven days for the given view.

Troubleshooting

AttributeError: 'Module_six_moves_urllib_parse' object has no attribute 'urlparse'

This error can occur in Mac OSX where the default installation of the "six" module (a dependency of this library) is loaded before the one that pip installed. To fix the issue, add pip's install location to the PYTHONPATH system environment variable:

  • Determine pip's install location with the following command:

    pip show six | grep "Location:" | cut -d " " -f2

  • Add the following line to your ~/.bashrc file, replacing &lt;pip_install_path&gt; with the value determined above:

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>

  • Reload your ~/.bashrc file in any open terminal windows using the following command:

    source ~/.bashrc