Accessing Google Analytics 4 data with Python

Datalina (Alina Draichuk)
4 min readJul 22, 2023

--

You may be fully new to using Python to extract GA data or you may have experience with Universal Analytics data and are looking for guides specifically for GA4 after UA went away. In any case, this article will provide a step-by-step guidance. When you get used to the workflow, the data extraction takes under 5 mins.

Prerequisites: a Google Cloud project and basic understanding of python

Photo by Christopher Gower on Unsplash

Some things to do in Google Cloud

Before the fun part with coding we need to do some arrangements.

  1. Go to your Google Cloud project (or create it if you do not have it yet): https://cloud.google.com/
  2. Go to “APIs and Services” from the side menu to “Library” and search for “Google Analytics Data API”, then click on it and enable it:

3. Then, go to the “IAM & Admin” area from the side menu and select the “Service Accounts” section.

4. Click at the top button to create a service account:

5. Give the service account some name (you can skip the next 2 optional settings areas) and click “Done”

6. After that, you will see a new account listed among your service accounts. Click on it:

7. Go to the “Keys” section and click on “Add Key” -> “Create new key” -> JSON -> “Create”

8. When you create the key, there should be started an automatic download of the key in the json format. Store the key (we will store the key on the Google Drive in this guide) and do not share it with publicly with people who should not have access to your data.

9. Copy the email address of your service account and provide it with viewer access in the Google Analytics 4 property you want to work with.

Phew, that was a lot of work! Now let’s move to the fun part!

Code

First, install the package specifically designed to provide access to the Google Analytics Data API:

!pip install google-analytics-data

Then, import the necessary libraries:

from google.oauth2 import service_account
from google.analytics.data_v1beta import BetaAnalyticsDataClient

from google.colab import drive
import pandas as pd

This piece of code will mount your Google Drive to the Colab environment. Mounting Google Drive allows you to access files and folders stored in your Google Drive directly from your Colab notebook.

drive.mount('/content/drive')

The next part will need some adjustments, change the key path to yours:

credentials = service_account.Credentials.from_service_account_file(
'path_to_your_credentials/key_name.json' #change this to your path
)

Set up the client:

client = BetaAnalyticsDataClient(credentials=credentials)

Now it’s time to get the data! :D

Adjust the parts which are commented to your needs. When you input dimensions and metrics, keep them in the specific format provided.

Please pay attention, you have to follow specific naming when you query your metrics and dimensions. You can find the naming you need to use in the GA4 Dimensions & Metrics Explorer .


# Set up GA4 request
request = {
"property": "properties/XXXXXXX", #input your property ID from Google Analytics 4 admin settings
"date_ranges": [
{
"start_date": "2023-01-01", #adjust to your start date
"end_date": "2023-03-31" #adjust to your end date
}
],
"dimensions": [ #input the dimensions you need
{
"name": "country"
},
{
"name": "city"
}
],
"metrics": [ #input the metrics you need
{
"name": "sessions"
},
{
"name": "transactions"
}
]
}

# Execute GA4 request
response = client.run_report(request)

# Extract GA4 data into pandas DataFrame
data = []
for row in response.rows:
dimension_values = [value.value for value in row.dimension_values]
metric_values = [value.value for value in row.metric_values]
data.append(dimension_values + metric_values)

columns = [dimension.name for dimension in response.dimension_headers] + [metric.name for metric in response.metric_headers]
df = pd.DataFrame(data, columns=columns)

Finally, you can call the data frame:

df

And this will output your data.

I hope the guide was helpful. Please let me know in the case of any questions or comments and have a nice day!

--

--