pythongoogle-analyticspython-requestsmeasurement-protocol

I cannot see Google Analytics events working, using Python requests


I'm trying to send post requests to https://www.google-analytics.com/collect? like so:

name = user.first_name
    if user.username:
      name += f'[{user.username}]'
    query_params = {
      'v': '1',
      't': 'event',
      'tid': self._config.ga_tracking_id,
      'cid': '555',
      'ec': category,
      'ea': action,
      'el': f'{name}: {label}'
    }
    query = urlencode(query_params)
    requests.post('https://www.google-analytics.com/collect?'+query)

The print output is giving me this:

https://www.google-analytics.com/collect?v=1&t=event&tid=UA-17106xxxx-1&cid=555&ec=category&ea=ACTION&el=Name%5BFullView%5D%3A+nana+with+6+results

everything look ok to me, but on my GA Events panel I don't see any report either under Real-Time or Behaviour

Any suggestion?

*** UPDATE ***

    query_params = {
      'v': '1',
      't': 'event',
      'tid': self._config.ga_tracking_id,
      'cid': '555',
      'ec': category,
      'ea': action,
      'el': f'[{now}]{name}: {label}',
      'dp': '/'
    }
    r = requests.post('https://www.google-analytics.com/collect', data=query_params)

Solution

  • Assuming this is not a brand new Google analytics account and that it is at least 72 hours old then it should be recording data.

    Post should contain post body.

    requests.post('https://www.google-analytics.com/collect?'+query)

    You are sending a post request but you are not sending the data in the post body.

    POST /collect HTTP/1.1
    Host: www.google-analytics.com
    
    v=1&t=event&tid=UA-17106xxxx-1&cid=555&ec=category&ea=ACTION&el=Name%5BFullView%5D%3A+nana+with+6+results
    

    post body

    # importing the requests library 
    import requests 
      
    # api-endpoint 
    URL = "https://www.google-analytics.com/collect"
    
    # define user
    name = user.first_name
    if user.username:
       name += f'[{user.username}]'
      
    # defining a params dict for the parameters to be sent to the API 
    PARAMS = {
      'v': '1',
      't': 'event',
      'tid': self._config.ga_tracking_id,
      'cid': '555',
      'ec': category,
      'ea': action,
      'el': f'{name}: {label}'
    }
    
    # sending POST request and saving the response as response object 
    r = requests.post(url = URL, params = PARAMS)