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
- Open the Service accounts page. If prompted, select a project.
- Click 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.
- The Service account permissions (optional) section that follows is not required. Click Continue.
- On the Grant users access to this service account screen, scroll down to the Create key section. Click Create key.
- In the side panel that appears, select the format for your key: JSON is recommended.
- 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.
- 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 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
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.
- Copy or download the following source code to
HelloAnalytics.py
. - Move the previously downloaded
client_secrets.json
to the same directory as the sample code. - Replace the value of the
KEY_FILE_LOCATION
with the appropriate path to the downloadedclient_secrets.json
. - 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('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. """ 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<pip_install_path>
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