Hello Analytics Reporting API v4; Python quickstart for service accounts

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.

Create credentials

  1. Open the Service accounts page. If prompted, select a project.
  2. Click Create service account.
  3. In the Create service account window, type a name for the service account, and select Furnish a new private key. Then click Create.

Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. You are responsible for storing it securely.

Add service account to the Google Analytics account

The newly created service account will have an email address that looks similar to:

quickstart@PROJECT-ID.iam.gserviceaccount.com

Use this email address to add a user to the Google analytics view you want to access via the API. For this tutorial only Read & Analyze permissions are needed.

2. Install the client library

You can either use a package manager or download and install the Python client library manually:

pip

Use pip, the recommended tool for installing Python packages:

sudo pip install --upgrade google-api-python-client

Setuptools

Use the easy_install tool included in the setuptools package:

sudo easy_install --upgrade google-api-python-client

Manual installation

Download the latest Google API python client library, unpack the code and run:

sudo python setup.py install

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.p12 to the same directory as the sample code.
  3. Replace the values of the SERVICE_ACCOUNT_EMAIL and KEY_FILE_LOCATION with the appropriate values from the Developer Console.
  4. Replace the value of VIEW_ID. You can use the Account Explorer to find a View ID.
"""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 = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_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('analytics', '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.
  """
  for report in response.get('reports', []):
    columnHeader = report.get('columnHeader', {})
    dimensionHeaders = columnHeader.get('dimensions', [])
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])

    for row in report.get('data', {}).get('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

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