Hello Analytics API: Python quickstart for service accounts  |  Analytics Management API  |  Google for Developers (2024)

Standard Universal Analytics (UA) properties stopped processing data on July 1, 2023. UA 360 properties will stop processing data on July 1, 2024, and some UA 360 features will be deprecated before then, as we migrate to Google Analytics 4. Use the Admin API to provision and manage GA4 properties.

  • Home
  • Products
  • Google Analytics
  • Configuration
  • Management API
Stay organized with collections Save and categorize content based on your preferences.

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 firstusethe setup tool, which guides you through creating a project in theGoogle API Console, enabling the API, and creating credentials.

Create a client ID

  1. Open the Service accounts page. If prompted,select a project.
  2. Click add Create Service Account, enter a name and description for the service account. You can use the default service account ID, or choose a different, unique one. When done click Create.
  3. The Service account permissions (optional) section that follows is not required. Click Continue.
  4. On the Grant users access to this service account screen, scroll down to the Create key section. Click add Create key.
  5. In the side panel that appears, select the format for your key: JSON is recommended.
  6. Click Create. Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. For information on how to store it securely, see Managing service account keys.
  7. Click Close on the Private key saved to your computer dialog, then click Done to return to the table of your service accounts.

Add service account to Google Analytics account

The newly created service account will have an email address, &ltprojectId&gt-&ltuniqueId&gt@developer.gserviceaccount.com; Use this email address to add a user to the Google analytics account you want to access via the API. For this tutorial only 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:

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 client library for python, unpack the code and run:

sudo python setup.py install

You may need to invoke the command with superuser (sudo) privileges to install to the system Python.

Step 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 within the same directory as the sample code.
  3. Replace the values of the key_file_location with the appropriate values from the Developer Console.
"""A simple example of how to access the Google Analytics API."""from apiclient.discovery import buildfrom oauth2client.service_account import ServiceAccountCredentialsdef get_service(api_name, api_version, scopes, key_file_location): """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. scopes: A list auth scopes to authorize for the application. key_file_location: The path to a valid service account JSON key file. Returns: A service that is connected to the specified API. """ credentials = ServiceAccountCredentials.from_json_keyfile_name( key_file_location, scopes=scopes) # Build the service object. service = build(api_name, api_version, credentials=credentials) return servicedef 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')[0].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')[0].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')[0].get('id') return Nonedef 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):', results.get('profileInfo').get('profileName') print 'Total Sessions:', results.get('rows')[0][0] else: print 'No results found'def main(): # Define the auth scopes to request. scope = 'https://www.googleapis.com/auth/analytics.readonly' key_file_location = '<REPLACE_WITH_JSON_FILE>' # Authenticate and construct service. service = get_service( api_name='analytics', api_version='v3', scopes=[scope], key_file_location=key_file_location) profile_id = get_first_profile_id(service) print_results(get_results(service, profile_id))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:

python HelloAnalytics.py

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 ofcode samples found in the Management API reference docs. Forexample you could try changing the code to use the accountSummaries.list method.

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 pipinstalled. To fix the issue, add pip's install location to the PYTHONPATHsystem environment variable:

  1. Determine pip's install location with the following command:

    pip show six | grep "Location:" | cut -d " " -f2
  2. Add the following line to your ~/.bashrc file, replacing <pip_install_path> with the value determined above:

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>
  3. Reload your ~/.bashrc file in any open terminal windows using the following command:

    source ~/.bashrc

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2023-12-20 UTC.

Hello Analytics API: Python quickstart for service accounts  |  Analytics Management API  |  Google for Developers (2024)
Top Articles
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6472

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.