Integrating Google Analytics Data API for Reporting: A Complete Implementation Guide
Integrating the Google Analytics Data API (v1beta) for reporting requires enabling the analyticsdata.googleapis.com service, configuring Application Default Credentials with the analytics.readonly scope, and executing RunReportRequest calls through official client libraries like BetaAnalyticsDataClient.
The google/skills repository hosts the google-analytics-data-api-basics skill module, which provides production-ready patterns for integrating Google Analytics Data API for reporting automation. This guide distills the essential implementation steps from skills/analytics/google-analytics-data-api-basics/SKILL.md to help you query property data programmatically across Python, Java, Node.js, and other supported languages.
Enable the Analytics Data API Service
Before issuing any requests, you must activate the API in your Google Cloud project. According to the skill documentation in SKILL.md, use the Cloud CLI to enable the service and verify activation.
# Enable Google Analytics Data API
gcloud services enable analyticsdata.googleapis.com --quiet
# Verify enablement
gcloud services list --enabled --filter="analyticsdata.googleapis.com"
Configure Application Default Credentials
The skill mandates using Application Default Credentials (ADC) with specific OAuth scopes to access reporting data. Run the following command to authenticate your environment with both the Cloud Platform and Analytics read-only permissions.
gcloud auth application-default login \
--scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"
This configuration allows the BetaAnalyticsDataClient to obtain tokens automatically without embedding secrets in your code.
Run Reports with the Python Client Library
The google-analytics-data Python library provides typed request objects and automatic retry logic. After installing the package, instantiate BetaAnalyticsDataClient and construct a RunReportRequest specifying your property ID, dimensions, metrics, and date ranges.
python3 -m venv .venv
source .venv/bin/activate
pip install google-analytics-data
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import DateRange, Dimension, Metric, RunReportRequest
def run_report(property_id: str):
client = BetaAnalyticsDataClient() # Uses ADC automatically
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__":
run_report("YOUR-PROPERTY-ID")
This example references the Python quick-start patterns documented in skills/analytics/google-analytics-data-api-basics/references/python.md.
Validate Dimension and Metric Compatibility
Certain dimension and metric combinations trigger INVALID_ARGUMENT errors if queried together. The skill emphasizes using the check_compatibility method before running production reports to validate field combinations.
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
CheckCompatibilityRequest,
Compatibility,
Dimension,
Metric,
)
def check_compatibility(property_id: str):
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:
print(f"Dimension {dim.dimension_metadata.api_name} compatible: "
f"{dim.compatibility == Compatibility.COMPATIBLE}")
for met in response.metric_compatibilities:
print(f"Metric {met.metric_metadata.api_name} compatible: "
f"{met.compatibility == Compatibility.COMPATIBLE}")
if __name__ == "__main__":
check_compatibility("YOUR-PROPERTY-ID")
Client Library References for Additional Languages
While the Python implementation serves as the primary reference, the skill module provides installation and usage guides for multiple languages:
- Java:
skills/analytics/google-analytics-data-api-basics/references/java.md - Node.js:
skills/analytics/google-analytics-data-api-basics/references/nodejs.md - Go:
skills/analytics/google-analytics-data-api-basics/references/go.md - PHP:
skills/analytics/google-analytics-data-api-basics/references/php.md - .NET:
skills/analytics/google-analytics-data-api-basics/references/dotnet.md - Ruby:
skills/analytics/google-analytics-data-api-basics/references/ruby.md
Summary
Integrating Google Analytics Data API for reporting involves three core phases that isolate environment setup from application code:
- Enable the
analyticsdata.googleapis.comservice usinggcloud services enablebefore attempting any API calls - Configure Application Default Credentials with both
cloud-platformandanalytics.readonlyscopes to support automatic token handling - Use
BetaAnalyticsDataClient.run_report()to executeRunReportRequestobjects, or validate field combinations first viacheck_compatibility() - Reference language-specific guides in the
references/directory of thegoogle-analytics-data-api-basicsskill for implementation details beyond Python
Frequently Asked Questions
What OAuth scopes are required for the Google Analytics Data API?
You must include https://www.googleapis.com/auth/cloud-platform and https://www.googleapis.com/auth/analytics.readonly when running gcloud auth application-default login. Missing the analytics.readonly scope causes permission errors when the BetaAnalyticsDataClient attempts to fetch reporting data.
How do I know if my chosen dimensions and metrics are compatible?
Call the check_compatibility() method on your BetaAnalyticsDataClient instance, passing a CheckCompatibilityRequest with your proposed dimensions and metrics. The response indicates whether each field combination is valid, preventing INVALID_ARGUMENT runtime errors.
Can I integrate the Data API with languages other than Python?
Yes. The google/skills repository provides reference implementations for Java, Node.js, Go, PHP, .NET, and Ruby in the skills/analytics/google-analytics-data-api-basics/references/ directory. Each file contains language-specific installation instructions and sample usage patterns.
Why does my request return a permission denied error despite having ADC configured?
This typically occurs when the analyticsdata.googleapis.com API is not enabled in your Google Cloud project, or when your ADC session lacks the analytics.readonly scope. Verify service enablement with gcloud services list and re-authenticate with both required scopes if necessary.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →