Skip to content

Instantly share code, notes, and snippets.

@ivanvenosdel
Last active January 20, 2021 04:01
Show Gist options
  • Save ivanvenosdel/eacd20bd5d7858c1f17b3b998572a69e to your computer and use it in GitHub Desktop.
Save ivanvenosdel/eacd20bd5d7858c1f17b3b998572a69e to your computer and use it in GitHub Desktop.
Python "requests", Google Analytics Realtime Reporting API (for oauth2 service accounts)
"""
Using "requests" to access Google Analytics Realtime Reporting API from python service
NOTE on google docs: The realtime reporting docs have samples for google-api-python-client.
**They do not work** at the time of this writing. The GA docs sample seems to refer to features that don't actually exist.
In any case, the new RR API is restfull and requests is a pleasent library so here is how to use it instead.
pip requirements: oauth2client, requests
"""
import httplib2
import requests
from oauth2client.service_account import ServiceAccountCredentials
# Build service account credentials from json string, this approach is most useful for servers without a file store
# Alternatively, ServiceAccountCredentials.from_json_keyfile_name may be used to load directly from file.
keyfile_dict = json.loads('json-based keyfile contents')
credentials = ServiceAccountCredentials.from_json_keyfile_dict(keyfile_dict, scopes=['https://www.googleapis.com/auth/analytics.readonly'])
# Create requests session object (avoids need to pass in headers with every request)
session = requests.Session()
session.headers= {'Authorization': 'Bearer ' + credentials.get_access_token().access_token}
# Enjoy!
url_kwargs = {
'view_id': 1234, # Can be obtained from here: https://ga-dev-tools.appspot.com/account-explorer/
'get_args': 'metrics=rt:activeUsers' # https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime/get
}
response = session.get('https://www.googleapis.com/analytics/v3/data/realtime?ids=ga:{view_id}&{get_args}'.format(**url_kwargs))
response.raise_for_status()
result = response.json()
@thalesnzn
Copy link

I'm having this error:
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url:

@na5imuzzaman
Copy link

import httplib2
import json
import requests
from oauth2client.service_account import ServiceAccountCredentials

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'key.json'
VIEW_ID = '28075'

# Build service account credentials from json string, this approach is most useful for servers without a file store
# Alternatively, ServiceAccountCredentials.from_json_keyfile_name may be used to load directly from file.
# keyfile_dict = json.loads('key.json')
# credentials = ServiceAccountCredentials.from_json_keyfile_dict(keyfile_dict, scopes=['https://www.googleapis.com/auth/analytics.readonly'])

credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

# Create requests session object (avoids need to pass in headers with every request)
session = requests.Session()
session.headers= {'Authorization': 'Bearer ' + credentials.get_access_token().access_token}

# Enjoy!
url_kwargs = {
    'view_id': 238075,  # Can be obtained from here: https://ga-dev-tools.appspot.com/account-explorer/
    'get_args': 'metrics=rt:activeUsers'  # https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime/get
}
response = session.get('https://www.googleapis.com/analytics/v3/data/realtime?ids=ga:{view_id}&{get_args}'.format(**url_kwargs))
response.raise_for_status()
result = response.json()
print(result)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment