How to Get Started With Google analytics API

Introduction

Google Analytics 4 is the latest version of Google’s web and app analytics platform, providing a more adaptable data model than its predecessor. The GA4 API allows you to directly access this data for uses beyond the standard GA4 interface. This includes custom reporting, data exports, and integration into your in-house tools. This guide will cover the basics of making your first call to the GA4 API (Google Analytics Data API).

Prerequisites

Please ensure that you have the following before proceeding to the next parts of the article:

  • Google Cloud Project (GCP): A GCP project provides the framework to access Google’s cloud services. You will need an active GCP project to create the necessary resources for connecting to the GA4 API. Users with basic IAM permissions (like the default “Basic Editor” role) can create service accounts.
  • Access to a Google Analytics 4 Property (Viewer or Editor permissions): You must be able to add a service account’s email address to the GA4 Property settings and grant it the necessary permissions (“Viewer” or “Editor”).
  • Basic understanding of GCP, GA4, and Coding: While this guide will provide step-by-step instructions, a foundational understanding of Google Cloud Platform, Google Analytics 4, and some basic coding knowledge will help you follow along more effectively.

Part I. What to Do in GCP

Enable Google Analytics Data API:

  1. Project Dashboard: Go to your Google Cloud Project dashboard.
  2. APIs & Services: Navigate to the “APIs & Services” section.
  3. Search and Enable: Search for “Google Analytics Data API” and click “Enable”.

Create Service Account:

  1. APIs & Services -> Credentials: Go back to the “Credentials” subsection within “APIs & Services” in your GCP project dashboard.

  2. + Create Credentials: Click on “+ Create Credentials” and choose “Service Account”.

  3. Service Account Details: Fill in a descriptive name for your service account (e.g., “ga4-reporting-api”). You can also add a brief description if desired. Click on “Create and Continue.”

  4. Other Details: You can leave “Grant this Service Account Access to Project” and “Grant Users Access to this Service Account” empty and just proced to button “Done.”

  5. Download JSON Key: In your GCP Project, navigate to the “IAM & Admin” section and then select “Service Accounts”. Locate the service account you just created (e.g., “ga4-reporting-api”). Click on the “Keys” tab within your service account’s details. Click on the “Add Key” button, choose “Create New Key”, and select the “JSON” format. The JSON key file will be downloaded to your local computer.

    Important: Store Your Credentials Securely This JSON file contains sensitive credentials that allow access to your GA4 data. Treat it with the same care as passwords or other confidential information.

    For this tutorial: We’ll store the JSON file directly on your local machine. Create a folder named “GA4 API” and a subfolder called “Keys” within it. Place the JSON file inside the “Keys” folder and remember its location.

    Production Environments: While storing the key locally may be convenient for initial exploration, production environments demand a much more secure approach. Google Cloud Secret Manager provides a specialized service to store and manage sensitive credentials like API keys. Use that service or something similar to store your credentials.

PART II. What to Do in Google Analytics

Grant Service Account Access to GA4 Property:

  1. Find Your Service Account Email: Open the JSON key file you downloaded earlier when creating your service account in GCP. Locate the “client_email” field and copy the email address. This is the unique identifier for your service account.
  2. Navigate to Your GA4 Property: Go to the Google Analytics platform and access the specific GA4 property where you want to extract data.
  3. Admin Settings: Within your GA4 property, navigate to the “Admin” settings.
  4. Property Access Management: Look for a section labeled “Property Access Management”. This is where you’ll add new users.
  5. + Add Member: Click the button labeled “+ Add Member” to add a new member (your service account).
  6. Paste Email and Set Permissions: Paste the service account’s email address you copied earlier. Since you just need to read data, grant the “Viewer” permission level.
  7. Save: Click “Save” to finalize granting the necessary permissions to your service account.

PART III. How to Make Your First API call

This part demonstrates how to make API calls to GA4 from your local machine (Mac), which is a great starting point.

1. Setting Up Credentials: In your terminal, run the following command to provide the path to your service account credentials (the JSON file you downloaded earlier):

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Where “Path,” is absolute path to your JSON file. To get absolute path, you can right click on file, press “Option” and then pick “Save ‘Name of Your JSON’ as PathName.”

Step 2: Install Client Library: For sake of this tutorial we would assume that you have Python (version 3.7 or higher) on your local machine. It is a recommended approach to use virtual environments to work with your APIs. You can think of virtual enviroments as project where you can specify what version of language and its dependencies you need. This is useful since allow us avoid clashes between different projects on your machine. We will use venv package to create and manage python virtual environments. First, we need to create virtual environment. To do so, please open Terminal at the folder that belongs to your Google Analytics 4 API project i.e. “GA4 API” in our case. Then type the following:

python3 -m venv ga4api 
source ga4api/bin/activate
pip install google-analytics-data

Here, “ga4api” is just name of your environment. It can be anything you want. First line of code creates virtual environment, second line is activating it. Third line installs “google-analytics-data” library directly into the “ga4api” virtual environment.

Step 3: Create Python Script: Here is Python script that we can use for test call:

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    DateRange,
    Dimension,
    Metric,
    RunReportRequest,
)


def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"):
    # Make changes here
    property_id = "YOUR-GA4-PROPERTY-ID"

    client = BetaAnalyticsDataClient()

    request = RunReportRequest(
        property=f"properties/{property_id}",
        metrics=[Metric(name="conversions")],  # Fetch the conversion metric
        date_ranges=[DateRange(start_date="yesterday", end_date="yesterday")],
    )
    response = client.run_report(request)

    total_conversions = 0
    for row in response.rows:
        total_conversions += row.metric_values[0].value

    print("Total Conversions (yesterday):", total_conversions)

if __name__ == "__main__":
    sample_run_report() 

Please save it in the “GA4 API” folder under subfolder “Scripts” and give it some distinctive name, such as “test_run.py”. Inside of this script file, make sure that you replace “YOUR-GA4-PROPERTY-ID” with your Project ID. You can find your Project ID in your Google Analytics Property. Go to Admin -> under “Property” click on “Property Settings”. There you should be able to see Property ID displayed.

Step 4: Make your first API Call:

After we done with scripting, please run the following command in Terminal (bash should be opened withing activated environment):

python3 test_run.py

This should output number of conversions that you had yesterday. The output should look something like this.

Total Conversions (yesterday): 12

Conclusion

I know counting number of conversion you had yesterday is not that much given amount of steps we made so far. However, I would argue that goal of this article is to provide simple step-by-step introduction to working with APIs in Google Analytics 4. I encourage you as a user to read official documentation from Google and write your own scripts. From my experience, the most intimidating part of working with API is not actuall usage of it, but rather setting up things for the first time. Hope this guide made this experience a little less stressful for you. If you find it helpful please like the article so that more people know about it and it can help someone else.


If you found this article useful and would like to support my work, consider buying me a coffee! Just click on the button below and follow the instructions to make a donation. Your support helps me create more valuable content. Thank you!