This post is also available in: Svenska (Swedish)
In this article I will take you through the details of writing a Python Notebook code to extract data from Google Analytics (GA4) using the Google API Python library to access Google Analytics.
Let’s get started, this involves that you have access to a Google Cloud Project – if you do not have a Google Cloud Project then you can find more details here on how to do it.
Goto API & Services in your Google Cloud Project and search for the Google Analytics API
Google has three APIs for Google analytics – and you have to enable the API that you need to use – here is a short description of what each API provides:
- Google Analytics Reporting API – Access report data in Google Analytics.
- Google Analytics API – The Analytics API provides access to Analytics configuration and reports data.
- Google Analytics Data API – Accesses report data in Google Analytics.
Google Analytics Reporting API
In this example I am using the Google Analytics Reporting API
Setting up Service Account
You would need a Service Account from your Google CLoud Project – Here are the steps for setting up a service account:
- Sign-in to Google’s developer’s console
- Activate the Google Analytics Reporting API or the ones you need
- On the credentials, page click create credentials and select Service account key.
- Create a JSON key and download it to your computer.
The last step will download to your laptop the service account key, keep this secret and do not share with others.
Log in to Google Analytics – In the Admin, select the view that you want to extract data from and go to User Management.
Now you can write your code as a cloud function or just a Python Notebook to read the analytics data.
One thing that you need to copy from Google ANalytics for this code to work is to get the view id sas we extract data from a page view.
Here is an example of a Python Notebook code snippet that uses the service account to extract data from Google Analytics.
Google Analytics – https://developers.google.com/analytics/devguides/config/?csw=1
Filters and segments – https://support.google.com/analytics/answer/7331978?hl=en