This tutorial walks through the steps required to access a Google Analytics account, query the Analytics APIs, handle the API responses, and output the results. The Core Reporting API v3.0, Management API v3.0, and OAuth2.0 are used in this tutorial.
Step 1: Enable the Analytics API
To get started using Google Analytics API, 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 a client ID
- Open the Service accounts page. If prompted, select a project.
- Click Create service account.
- In the Create service account window, type a name for the service account, and select Furnish a new private key. If you want to grant G Suite domain-wide authority to the service account, also select Enable G Suite Domain-wide Delegation. 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 Google Analytics account
The newly created service account will have an email address,
Use this email address to
a user to the Google analytics account you want to access via the API.
For this tutorial only
& Analyze permissions are needed.
Step 2: Install the Google Client Library
You can either use a package manager or download and install the Python client library manually:
Use pip, the recommended tool for installing Python packages:
sudo pip install --upgrade google-api-python-client
Use the easy_install tool included in the setuptools package:
sudo easy_install --upgrade google-api-python-client
Download the latest client library for python, unpack the code and run:
sudo python setup.py install
You may need to invoke the command with superuser (
privileges to install to the system Python.
Step 3: Setup the sample
You'll need to create a single file named
which will contain the given sample code.
- Copy or
download the following source code to
- Move the previously downloaded
client_secrets.p12within the same directory as the sample code.
- Replace the values of the
key_file_locationwith the appropriate values from the Developer Console.
"""A simple example of how to access the Google Analytics API.""" import argparse 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').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').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').get('id') return None def get_results(service, profile_id): # Use the Analytics Service Object to query the Core Reporting API # for the number of sessions within the past seven days. return service.data().ga().get( ids='ga:' + profile_id, start_date='7daysAgo', end_date='today', metrics='ga:sessions').execute() def print_results(results): # Print data nicely for the user. if results: print 'View (Profile): %s' % results.get('profileInfo').get('profileName') print 'Total Sessions: %s' % results.get('rows') else: print 'No results found' 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('analytics', 'v3', scope, key_file_location, service_account_email) profile = get_first_profile_id(service) print_results(get_results(service, profile)) if __name__ == '__main__': main()
Step 4: Run the sample
After you have enabled the Analytics API, installed the Google APIs client library for Python, and set up the sample source code the sample is ready to run.
Run the sample using:
When you finish these steps, the sample outputs the name of the authorized user's first Google Analytics view (profile) and the number of sessions for the last seven days.
With the authorized Analytics service object you can now run any of code samples found in the Management API reference docs. For example you could try changing the code to use the accountSummaries.list method.
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
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
<pip_install_path>with the value determined above:
~/.bashrcfile in any open terminal windows using the following command: