Google Analytics with Python - Part 1: Setup GA

Photo by Myriam Jessier / Unsplash

When you use Google Analytics for monitoring you website it stores a lot of relevant data. You can turn this data into information with the tools that Google offers, like Google Data Studio. But what if you want to have the raw data for yourself to play around with and don't what to pay for Google Analytics 360.

This is where the Google Reporting API comes into play. The Google Reporting API has multiple API's from which to choose. We are focussing on the new "Google Analytics 4 (GA4) Properties" because it's the new standard that Google is moving everyone to (eventually).


Setup a Service Account in Google

In order to extract the data from the Google Analytics Data API, we first need to setup a service account in the "Google Cloud Platform". If you don't have an account, just go to cloud.google.com and sign-up for free (You can use PayPal or a credit card for the Payment method). The features that we will be using a free, so you won't be charged.

When you account is setup you can create a new project and give it a name. I named mine "Google Analytics Extraction". Google Analytics provides a setup tool that guides you trough the necessary steps.  

Next step is to get the credentials needed for authenticating your python script. The simpelst option is to go to your newly created service account and go to the Keys tab. On that page, Generate a New Key and choose the JSON format.

After pressing Create a JSON file should be downloaded to your device. This JSON file can be used to authenticate the Service Account that will gain access to the Google Analytics Data.

Grant access to the Google Analytics Data

First step is to go to the API Quickstart for the GA4 Data API and Enable the API. In the Popup you can select the project that you've created in the previous step and Click Next.

Open the Admin section of Google Analytics, select Account or Property Access Management and click on the + sign to add an account. Now copy the email address from your service account service-account-name@project.iam.gserviceaccount.com and past it into the Email Addresses section. The service account only need Read & Analyze permisions, so make sure that is selected.

When you click Add your service account should have access.

Conclusion

We've created a Google Service Account that can access our Google Analytics data. In the next part we will use a python script to extract data from Google Analytics.

Daan Damhuis

Daan Damhuis

Netherlands