Google Analytics Data API Client Library

0.21.0 · active · verified Thu Apr 09

The Google Analytics Data API client library provides programmatic methods to access report data in Google Analytics 4 (GA4) properties. It is an actively maintained library within the `googleapis/google-cloud-python` ecosystem, with frequent updates that may include new features and occasional breaking changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate using a service account (via `GOOGLE_APPLICATION_CREDENTIALS` environment variable) and run a basic report on a Google Analytics 4 property to get active users by city for the last 7 days. You need to enable the Analytics Data API and configure a service account with appropriate permissions.

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

# Replace with your Google Analytics 4 property ID.
# Ensure GOOGLE_APPLICATION_CREDENTIALS environment variable is set
# to the path of your service account key file.
PROPERTY_ID = os.environ.get("GA4_PROPERTY_ID", "YOUR-GA4-PROPERTY-ID")

def run_simple_report(property_id):
    """Runs a simple report on a Google Analytics 4 property."""
    client = BetaAnalyticsDataClient()

    request = RunReportRequest(
        property=f"properties/{property_id}",
        dimensions=[Dimension(name="city")],
        metrics=[Metric(name="activeUsers")],
        date_ranges=[DateRange(start_date="7daysAgo", end_date="today")],
    )

    response = client.run_report(request)

    print(f"Report result for property: {response.property_header.property_id}")
    print("Row count: {}".format(len(response.rows)))

    print("\nReport data:")
    for row in response.rows:
        print(f"{row.dimension_values[0].value}: {row.metric_values[0].value}")

if __name__ == "__main__":
    if PROPERTY_ID == "YOUR-GA4-PROPERTY-ID":
        print("Please set the 'GA4_PROPERTY_ID' environment variable or update the script.")
        print("Also ensure 'GOOGLE_APPLICATION_CREDENTIALS' is set for authentication.")
    else:
        run_simple_report(PROPERTY_ID)

view raw JSON →