How to Programmatically Access Google Analytics Reports with the Data API

Use the Google Analytics Data API (v1β) to programmatically access Google Analytics reports by enabling the API, authenticating with Application Default Credentials, and executing RunReportRequest calls through official client libraries.

This guide covers the complete workflow for retrieving Google Analytics data programmatically, based on the reference implementation in google/skills. The Google Analytics Data API replaces the older Reporting API v4 and provides direct access to GA4 properties with modern client libraries for Python, Java, Node.js, Go, .NET, PHP, and Ruby.

Enable the Google Analytics Data API

Before making any requests, you must activate the Data API for your Google Cloud project. This authorization step grants your project permission to access Google Analytics reporting services.

The repository provides Cloud CLI instructions in [skills/analytics/google-analytics-data-api-basics/SKILL.md](https://github.com/google/skills/blob/main/skills/analytics/google-analytics-data-api-basics/SKILL.md#enabling-the-api-via-cloud-cli):

gcloud services enable analyticsdata.googleapis.com --project=YOUR_PROJECT_ID

Verify enablement through the Google Cloud Console or by running gcloud services list --enabled.

Authenticate with Application Default Credentials

All programmatic access to Google Analytics reports requires authenticated requests. The Data API uses Application Default Credentials (ADC) to simplify credential management across environments.

Configure ADC with the required scopes as documented in [SKILL.md](https://github.com/google/skills/blob/main/skills/analytics/google-analytics-data-api-basics/SKILL.md#authentication):

gcloud auth application-default login \
  --scopes="https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/analytics.readonly"

This command:

  1. Opens a browser for OAuth 2.0 authentication
  2. Stores credentials locally for the client library to discover automatically
  3. Grants read-only analytics access plus Cloud platform permissions

For production workloads, use service accounts instead of user credentials.

Install the Official Client Library

The repository maintains language-specific setup guides in the references/ directory. For Python, follow [references/python.md](https://github.com/google/skills/blob/main/skills/analytics/google-analytics-data-api-basics/references/python.md):

pip install google-analytics-data

Available client libraries by language:

  • Python: google-analytics-data
  • Java: com.google.cloud:google-cloud-analytics-data
  • Node.js: @google-analytics/data
  • Go: cloud.google.com/go/analytics/data/apiv1beta
  • .NET: Google.Analytics.Data.V1Beta
  • PHP: google/analytics-data
  • Ruby: google-analytics-data-v1beta

Construct a RunReportRequest

The core structure for programmatically accessing Google Analytics reports is the RunReportRequest object. Define your data requirements through four key components:

Component Purpose Example
Property ID Identifies the GA4 property properties/1234567
Dimensions Breakdown attributes city, date, itemName
Metrics Quantitative measurements activeUsers, sessions, totalRevenue
Date Ranges Time period for analysis 2026-05-01 to today

The API schema defines all valid dimension and metric names. Incompatible combinations trigger INVALID_ARGUMENT errors.

Query Google Analytics Data: Complete Python Example

This runnable example from the [SKILL.md](https://github.com/google/skills/blob/main/skills/analytics/google-analytics-data-api-basics/SKILL.md) source demonstrates the full workflow:

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


def run_report(property_id: str):
    """Retrieve active users and sessions by city and date."""
    # Client automatically discovers ADC credentials

    client = BetaAnalyticsDataClient()

    request = RunReportRequest(
        property=f"properties/{property_id}",
        dimensions=[
            Dimension(name="city"),
            Dimension(name="date")
        ],
        metrics=[
            Metric(name="activeUsers"),
            Metric(name="sessions")
        ],
        date_ranges=[
            DateRange(start_date="2026-05-01", end_date="today")
        ],
    )

    response = client.run_report(request)

    for row in response.rows:
        print(
            f"City: {row.dimension_values[0].value}, "
            f"Date: {row.dimension_values[1].value}, "
            f"Active Users: {row.metric_values[0].value}, "
            f"Sessions: {row.metric_values[1].value}"
        )


if __name__ == "__main__":
    # Replace with your GA4 property ID (digits only, no "properties/" prefix)

    run_report("YOUR-PROPERTY-ID")

The BetaAnalyticsDataClient handles gRPC communication, request serialization, response parsing, and automatic retries.

Validate Dimensions and Metrics Before Querying

Prevent runtime errors by validating compatibility before executing expensive report requests. The Data API provides checkCompatibility() for this purpose, as documented in [SKILL.md](https://github.com/google/skills/blob/main/skills/analytics/google-analytics-data-api-basics/SKILL.md#metrics-and-dimensions-compatibility-check):

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    CheckCompatibilityRequest,
    Compatibility,
    Dimension,
    Metric,
)


def check_compatibility(property_id: str):
    """Validate that requested dimensions and metrics can be queried together."""
    client = BetaAnalyticsDataClient()

    request = CheckCompatibilityRequest(
        property=f"properties/{property_id}",
        dimensions=[
            Dimension(name="itemName"),
            Dimension(name="date")
        ],
        metrics=[
            Metric(name="activeUsers"),
            Metric(name="totalRevenue")
        ],
    )

    response = client.check_compatibility(request)

    for dim in response.dimension_compatibilities:
        compatible = dim.compatibility == Compatibility.COMPATIBLE
        print(f"Dimension '{dim.dimension_metadata.api_name}' compatible: {compatible}")

    for met in response.metric_compatibilities:
        compatible = met.compatibility == Compatibility.COMPATIBLE
        print(f"Metric '{met.metric_metadata.api_name}' compatible: {compatible}")


if __name__ == "__main__":
    check_compatibility("YOUR-PROPERTY-ID")

Run this check before production report generation to catch schema violations early.

Handle API Responses and Pagination

The RunReportResponse contains:

  • Row data: Dimension and metric values as repeated fields
  • Metadata: Information about the returned columns
  • Totals: Aggregated values when requested
  • Row count: Total matching rows (may exceed returned rows)

For large result sets, the API paginates automatically. The client library handles pagination tokens transparently in iterators like response.rows.

Summary

To programmatically access Google Analytics reports:

  • Enable the Data API via Cloud CLI (gcloud services enable analyticsdata.googleapis.com)
  • Authenticate with Application Default Credentials (gcloud auth application-default login)
  • Install the official client library for your language (Python: pip install google-analytics-data)
  • Validate dimension/metric compatibility using checkCompatibility() when combining uncommon fields
  • Execute run_report() with a properly constructed RunReportRequest containing property ID, dimensions, metrics, and date ranges

The architecture follows a client SDK → authenticated request → Google Analytics Data service pattern with automatic retry handling and pagination support.

Frequently Asked Questions

What is the difference between the Google Analytics Data API and the Reporting API v4?

The Data API (v1β) is designed specifically for GA4 properties and represents the current recommended approach. The Reporting API v4 only supports Universal Analytics properties, which Google is deprecating. The Data API uses modern client libraries, supports real-time data, and provides compatibility checking capabilities that v4 lacks.

How do I find my GA4 property ID for API requests?

Your property ID appears in the GA4 interface as a numeric identifier (typically 7-10 digits). In API requests, prefix it with properties/ to form the full resource name: properties/1234567. Do not confuse this with the tracking ID (G-XXXXXXXXXX) used in measurement protocol implementations.

Can I use service accounts instead of user credentials for authentication?

Yes, service accounts are recommended for production workloads that programmatically access Google Analytics reports. Create a service account in Google Cloud Console, download the JSON key file, and set the GOOGLE_APPLICATION_CREDENTIALS environment variable to its path. The BetaAnalyticsDataClient discovers these credentials automatically through ADC.

Why does my report request return an INVALID_ARGUMENT error?

This error indicates incompatible dimensions or metrics in your RunReportRequest. Use the checkCompatibility() method demonstrated above to identify which fields conflict. Common issues include combining inventory dimensions with user-based metrics, or requesting deprecated field names that have been replaced in the GA4 schema.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →