Athletics Arena Tampere Finland

Data Project: Python with Google Analytics API

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 you having 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.

Google Setup

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 it with others.

Google Analytics

Log in to Google Analytics – In the Admin, select the view that you want to extract data from and go to User Management.

Open the service account JSON key file that you just downloaded in a text editor.

Copy the client_email and give this email read permissions.

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 as 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.

Learn More

Google Analytics – https://developers.google.com/analytics/devguides/config/?csw=1

Filters and segments – https://support.google.com/analytics/answer/7331978?hl=en

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *