google-analytics-data-api-basics

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Getting Started with Google Analytics Data API

Google Analytics Data API 入门指南

The Google Analytics Data API v1beta provides programmatic access to Google Analytics report data. It allows you to build customized dashboards, automate reporting workflows, and integrate Google Analytics data into your enterprise applications.
Google Analytics Data API v1beta提供了对Google Analytics报告数据的程序化访问能力。它允许您构建自定义仪表板、自动化报告工作流,并将Google Analytics数据集成到企业应用中。

Enabling the API via Cloud CLI

通过Cloud CLI启用API

Before making API calls, ensure the Google Analytics Data API is enabled in your Google Cloud project.
If
gcloud
is not found, prompt the user to install the Google Cloud CLI before running these commands.
  1. Enable the API: Use the Cloud CLI (
    gcloud
    ) to enable
    analyticsdata.googleapis.com
    .
    bash
    gcloud services enable analyticsdata.googleapis.com --quiet
    Why: Enabling the API ensures your Cloud project has the necessary quota and permissions allocated for running Google Analytics reports.
  2. Verify API Enablement:
    bash
    gcloud services list --enabled --filter="analyticsdata.googleapis.com"
在调用API之前,请确保您的Google Cloud项目中已启用Google Analytics Data API。
如果未找到
gcloud
命令,请提示用户先安装Google Cloud CLI,再运行以下命令。
  1. 启用API: 使用Cloud CLI (
    gcloud
    )启用
    analyticsdata.googleapis.com
    bash
    gcloud services enable analyticsdata.googleapis.com --quiet
    原因:启用API可确保您的Cloud项目获得运行Google Analytics报告所需的配额和权限。
  2. 验证API启用状态:
    bash
    gcloud services list --enabled --filter="analyticsdata.googleapis.com"

Authentication

身份验证

To authenticate your API requests, you must generate Application Default Credentials (ADC) and give your account the necessary scopes. Run the following command in your terminal:
bash
gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"
Why: This configures ADC in your local environment with the required Cloud Platform and Google Analytics read-only scopes, allowing the client library to automatically authenticate your requests.
要对API请求进行身份验证,您必须生成应用默认凭据(ADC)并为您的账户分配必要的权限范围。在终端中运行以下命令:
bash
gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"
原因:此命令会在您的本地环境中配置带有Cloud平台和Google Analytics只读权限范围的ADC,使客户端库能够自动对您的请求进行身份验证。

Creating a Data API Report (v1beta)

创建Data API报告(v1beta)

To create a report, use the official Google Analytics Data client library. Always prefer the
v1beta
version of the API for stability and access to current Google Analytics reporting capabilities.
[!IMPORTANT] Mandatory Agent Directive: When the user selects or requires a specific programming language, read the corresponding client library setup reference guide in
references/
listed below.
要创建报告,请使用官方Google Analytics Data客户端库。为了稳定性和访问当前Google Analytics报告功能,始终优先使用API的
v1beta
版本。
[!IMPORTANT] Agent强制指令: 当用户选择或需要特定编程语言时,请阅读下方
references/
中对应的客户端库设置参考指南。

Supported Client Libraries

支持的客户端库

Python

Python

If you need to install or set up the Google Analytics Data API client library for Python, read the setup guide:
  • Python Installation Reference (Package:
    google-analytics-data
    )
如果您需要安装或设置适用于Python的Google Analytics Data API客户端库,请阅读设置指南:
  • Python安装参考 (包:
    google-analytics-data
    )

Java

Java

If you need to install or set up the Google Analytics Data API client library for Java, read the setup guide:
  • Java Installation Reference (Artifact:
    com.google.cloud:google-cloud-analytics-data
    )
如果您需要安装或设置适用于Java的Google Analytics Data API客户端库,请阅读设置指南:
  • Java安装参考 (构件:
    com.google.cloud:google-cloud-analytics-data
    )

PHP

PHP

If you need to install or set up the Google Analytics Data API client library for PHP, read the setup guide:
  • PHP Installation Reference (Package:
    google/analytics-data
    )
如果您需要安装或设置适用于PHP的Google Analytics Data API客户端库,请阅读设置指南:
  • PHP安装参考 (包:
    google/analytics-data
    )

Node.js

Node.js

If you need to install or set up the Google Analytics Data API client library for Node.js, read the setup guide:
  • Node.js Installation Reference (Package:
    @google-analytics/data
    )
如果您需要安装或设置适用于Node.js的Google Analytics Data API客户端库,请阅读设置指南:
  • Node.js安装参考 (包:
    @google-analytics/data
    )

Go

Go

If you need to install or set up the Google Analytics Data API client library for Go, read the setup guide:
  • Go Installation Reference (Package:
    cloud.google.com/go/analytics/data/apiv1beta
    )
如果您需要安装或设置适用于Go的Google Analytics Data API客户端库,请阅读设置指南:
  • Go安装参考 (包:
    cloud.google.com/go/analytics/data/apiv1beta
    )

.NET

.NET

If you need to install or set up the Google Analytics Data API client library for .NET / C#, read the setup guide:
  • .NET Installation Reference (Package:
    Google.Analytics.Data.V1Beta
    )
如果您需要安装或设置适用于.NET / C#的Google Analytics Data API客户端库,请阅读设置指南:
  • .NET安装参考 (包:
    Google.Analytics.Data.V1Beta
    )

Ruby

Ruby

If you need to install or set up the Google Analytics Data API client library for Ruby, read the setup guide:
  • Ruby Installation Reference (Gem:
    google-analytics-data-v1beta
    )
[!NOTE] Additional Resources: For further examples of calling the Data API with Java, PHP, Node.js, .NET, Python and REST, as well as hints on authentication with a service account, refer to the official Data API Quickstart.
如果您需要安装或设置适用于Ruby的Google Analytics Data API客户端库,请阅读设置指南:
  • Ruby安装参考 (Gem:
    google-analytics-data-v1beta
    )
[!NOTE] 额外资源: 有关使用Java、PHP、Node.js、.NET、Python和REST调用Data API的更多示例,以及使用服务账户进行身份验证的提示,请参考官方Data API快速入门

Python Quick Start

Python快速入门

  1. Install the Client Library:
    bash
    pip install google-analytics-data
    If
    pip
    is not available, prompt the user to install
    pip
    before installing the client library.
  2. Run a Report Request: Below is a complete example demonstrating how to query a Google Analytics property for active users and sessions grouped by city and date. Replace
    YOUR-PROPERTY-ID
    with your actual Google Analytics property ID (e.g.,
    1234567
    ).
    python
    from google.analytics.data_v1beta import BetaAnalyticsDataClient
    from google.analytics.data_v1beta.types import DateRange, Dimension, Metric, RunReportRequest
    
    def sample_run_report(property_id: str):
        # Initialize the client.
        # Assumes Application Default Credentials (ADC) are configured in your environment.
        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)
    
        print(f"Report result for property {property_id}:")
        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__":
        sample_run_report("YOUR-PROPERTY-ID")
    Why: Using
    BetaAnalyticsDataClient
    and
    RunReportRequest
    ensures compatibility with the v1beta endpoint and strongly typed request validation.
  1. 安装客户端库:
    bash
    pip install google-analytics-data
    如果未找到
    pip
    ,请提示用户先安装
    pip
    ,再安装客户端库。
  2. 运行报告请求: 以下是一个完整示例,演示如何查询Google Analytics属性的活跃用户和按城市与日期分组的会话数据。将
    YOUR-PROPERTY-ID
    替换为您实际的Google Analytics属性ID(例如:
    1234567
    )。
    python
    from google.analytics.data_v1beta import BetaAnalyticsDataClient
    from google.analytics.data_v1beta.types import DateRange, Dimension, Metric, RunReportRequest
    
    def sample_run_report(property_id: str):
        # Initialize the client.
        # Assumes Application Default Credentials (ADC) are configured in your environment.
        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)
    
        print(f"Report result for property {property_id}:")
        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__":
        sample_run_report("YOUR-PROPERTY-ID")
    原因:使用
    BetaAnalyticsDataClient
    RunReportRequest
    可确保与v1beta端点兼容,并提供强类型的请求验证。

Metrics and Dimensions Schema

指标与维度架构

When constructing your
RunReportRequest
, you must use valid API names for dimensions and metrics. Refer to the official Data API Schema documentation for the complete, authoritative list of available fields.
构建
RunReportRequest
时,您必须使用维度和指标的有效API名称。请参考官方Data API架构文档获取完整的权威可用字段列表。

Commonly Used Dimensions

常用维度

Dimensions represent categorical attributes of your data.
  • city
    : The town or city of the user.
  • country
    : The country of the user.
  • date
    : The date of the event, formatted as YYYYMMDD.
  • deviceCategory
    : The category of mobile device (e.g., desktop, mobile, tablet).
  • eventName
    : The name of the triggered event.
  • pageTitle
    : The title of the web page.
维度代表数据的分类属性。
  • city
    : 用户所在的城镇或城市。
  • country
    : 用户所在的国家。
  • date
    : 事件日期,格式为YYYYMMDD。
  • deviceCategory
    : 移动设备类别(例如:桌面设备、移动设备、平板设备)。
  • eventName
    : 触发事件的名称。
  • pageTitle
    : 网页标题。

Commonly Used Metrics

常用指标

Metrics represent quantitative measurements.
  • activeUsers
    : The number of active users.
  • eventCount
    : The total count of events.
  • sessions
    : The total number of sessions.
  • screenPageViews
    : The number of app screens or web pages viewed.
  • totalRevenue
    : The total revenue from purchases, subscriptions, and advertising.
指标代表量化测量值。
  • activeUsers
    : 活跃用户数量。
  • eventCount
    : 事件总次数。
  • sessions
    : 会话总次数。
  • screenPageViews
    : 应用屏幕或网页的浏览次数。
  • totalRevenue
    : 来自购买、订阅和广告的总收入。

Metrics and Dimensions Compatibility Check

指标与维度兼容性检查

Some dimensions and metrics cannot be queried together in the same report request. If you encounter an
INVALID_ARGUMENT
error regarding incompatible fields, verify your field combinations For programmatic access to the Data API schema, use
getMetadata()
. To programmatically check the compatibility of specific dimension and metric combinations before running a report, use the
checkCompatibility()
method.
python
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import CheckCompatibilityRequest, Compatibility, Dimension, Metric

def sample_check_compatibility(property_id: str):
    client = BetaAnalyticsDataClient()

    # Define the dimensions and metrics you want to query together.
    # For example, checking if 'itemDescription' (an e-commerce dimension)
    # is compatible with 'activeUsers' and 'totalRevenue'.
    request = CheckCompatibilityRequest(
        property=f"properties/{property_id}",
        dimensions=[
            Dimension(name="itemDescription"),
            Dimension(name="date")
        ],
        metrics=[
            Metric(name="activeUsers"),
            Metric(name="totalRevenue")
        ],
    )
    response = client.check_compatibility(request)

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

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

if __name__ == "__main__":
    sample_check_compatibility("YOUR-PROPERTY-ID")
某些维度和指标无法在同一个报告请求中一起查询。如果您遇到关于字段不兼容的
INVALID_ARGUMENT
错误,请验证您的字段组合。要以程序化方式访问Data API架构,请使用
getMetadata()
方法。要在运行报告前以程序化方式检查特定维度和指标组合的兼容性,请使用
checkCompatibility()
方法。
python
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import CheckCompatibilityRequest, Compatibility, Dimension, Metric

def sample_check_compatibility(property_id: str):
    client = BetaAnalyticsDataClient()

    # Define the dimensions and metrics you want to query together.
    # For example, checking if 'itemDescription' (an e-commerce dimension)
    # is compatible with 'activeUsers' and 'totalRevenue'.
    request = CheckCompatibilityRequest(
        property=f"properties/{property_id}",
        dimensions=[
            Dimension(name="itemDescription"),
            Dimension(name="date")
        ],
        metrics=[
            Metric(name="activeUsers"),
            Metric(name="totalRevenue")
        ],
    )
    response = client.check_compatibility(request)

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

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

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