GA4 API Example Howto

How to use GA4 API with Python

Table of Contents

Goal

If you have data in your GA4 (Google Analytics 4) property and you want to access it using Python, you can use the GA4 API. In this blog, we will see how to use the GA4 API with Python to get the pageviews for a property.

Requirements

  1. Enable the Google Analytics Reporting API in the Google Cloud Console here. Here is how to link link.
  2. Create a service account within the project and download the JSON key and note down the client email. Howto
  3. Save the JSON key in the same folder as your Python script.
  4. Install the Google client library for Python. pip install google-analytics-data
  5. Add the client email to your GA4 property with the appropriate permissions i.e View, Edit, etc.
  6. Note down your property ID. You can find it in the GA4 property settings under the property name.
  7. For more dimensions, metrics and filters, refer to the GA4 API documentation

Code Sample - Pageviews by Property

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

ids = [342682434, 455436313]


def twoDaysAgoPageviews(property_id=id):
    """Runs a simple report on a Google Analytics 4 property."""

    import os
    import pathlib
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = str(
        pathlib.Path(__file__).parent.joinpath("mangoblogger-2025-1161108a34da.json")
    )
    client = BetaAnalyticsDataClient()
    request = RunReportRequest(
        property=f"properties/{property_id}",
        dimensions=[Dimension(name="dateHour")],
        metrics=[Metric(name="screenPageViews")],
        date_ranges=[DateRange(start_date="2daysAgo", end_date="today")],
    )
    response = client.run_report(request)
    sum_ = [int(row.metric_values[0].value) for row in response.rows]

    return sum(sum_)


def return_message():
    message = ""

    for id in ids:
        message += (
            f"Property ID: {id} Pageviews: {twoDaysAgoPageviews(property_id=id)}\n"
        )
    return message

Baesd on the article - https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries