How to trigger Google Analytics events from python?

Member

by dudley , in category: SEO Tools , 2 years ago

How to trigger Google Analytics events from python?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

2 answers

by rusty.rosenbaum , 2 years ago

@dudley 

To trigger Google Analytics events from Python, you can use the Measurement Protocol API provided by Google Analytics. Here's a step-by-step guide on how to do it:

  1. First, make sure that you have set up Google Analytics for your website or app and have created a tracking ID.
  2. Install the google-analytics-measurement-protocol Python package by running the following command in your terminal:
1
pip install google-analytics-measurement-protocol


  1. Next, import the MeasurementProtocol class from the package and create an instance of it with your tracking ID:
1
2
3
from googleanalytics import MeasurementProtocol

mp = MeasurementProtocol('GA_TRACKING_ID')


  1. Now, you can use the mp.track() method to send events to Google Analytics. The method takes various parameters, including the category, action, and label of the event, as well as the client ID and user ID (optional).


Here's an example of how to track an event:

1
mp.track('Event Category', 'Event Action', label='Event Label', client_id='CLIENT_ID', user_id='USER_ID')


Replace Event Category, Event Action, Event Label, CLIENT_ID, and USER_ID with your own values.

  1. That's it! Now, whenever you call the mp.track() method, an event will be sent to Google Analytics with the specified parameters.


Note that there are various other types of hits that you can send using the Measurement Protocol, such as pageviews, transactions, and social interactions. You can find more information on the available parameters and hit types in the Google Analytics Measurement Protocol documentation.

by clarabelle , a year ago

@dudley 

The code snippet provided in the previous response is incorrect. Here's the correct way to trigger Google Analytics events from Python:

  1. Install the google-api-python-client library by running the following command in your terminal:
1
pip install google-api-python-client


  1. Create a new project in the Google APIs Console and enable the Google Analytics Reporting API.
  2. Generate a service account key in the Google APIs Console, download the JSON file, and store it securely on your server.
  3. Import the necessary libraries and authenticate using the service account key:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

# Path to the service account key JSON file
KEY_FILE_LOCATION = '/path/to/service-account-key.json'

# Define the scope of the API access
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']

# Authenticate using the service account key
credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES)
analytics = build('analyticsreporting', 'v4', credentials=credentials)


Make sure to replace /path/to/service-account-key.json with the actual path to your service account key JSON file.

  1. Use the analytics.reports().batchGet() method to send events to Google Analytics. Here's an example of how to track an event:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
response = analytics.reports().batchGet(
  body={
    'reportRequests': [
      {
        'viewId': 'YOUR_VIEW_ID',
        'dateRanges': [{'startDate': '2022-01-01', 'endDate': '2022-01-31'}],
        'metrics': [{'expression': 'ga:totalEvents'}],
        'dimensions': [{'name': 'ga:eventCategory'}, {'name': 'ga:eventAction'}, {'name': 'ga:eventLabel'}],
        'dimensionFilterClauses': [{'filters': [{'dimensionName': 'ga:eventAction', 'operator': 'EXACT', 'expressions': ['Event Action']}]}]
      }
    ]
  }
).execute()


Replace 'YOUR_VIEW_ID' with the actual View ID of your Google Analytics property. Modify the other parameters (startDate, endDate, metrics, dimensions, dimensionFilterClauses) based on your specific event tracking requirements.

  1. Process the response to extract the event data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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', [])
    metrics = row.get('metrics', [])
  
    for header, dimension in zip(dimensionHeaders, dimensions):
      print(header + ': ' + dimension)
      
    for i, values in enumerate(metrics):
      print('Metrics:')
      
      for metricHeader, value in zip(metricHeaders, values.get('values')):
        print(metricHeader.get('name') + ': ' + value)


This code will print the event dimensions and metrics for each row of the response. You can modify the code to store the data or perform further analysis as needed.


That's it! You can use the above code as a starting point to trigger Google Analytics events from Python.