google-analytics-data-api-basics
google/skills
启用 Google Analytics 数据 API,通过 gcloud 进行身份验证,并使用 v1beta 客户端库创建自定义报告。
...展开全部Google Analytics 数据 API 入门指南
Google Analytics 数据 API v1beta 提供了对 Google Analytics 报告数据的程序化访问。它允许您构建自定义仪表板、 实现报告工作流自动化,并将 Google Analytics 数据集成到您的企业 应用程序中。
通过 Cloud CLI 启用 API
在进行 API 调用之前,请确保您的 Google Cloud 项目中已启用 Google Analytics 数据 API。
如果 gcloud 未找到,请提示用户在
运行这些命令之前安装 Google Cloud CLI。
启用 API:使用 Cloud CLI (
gcloud) 启用analyticsdata.googleapis.com.gcloud services enable analyticsdata.googleapis.com --quiet原因:启用 API 可确保您的 Cloud 项目拥有运行 Google Analytics 报告所需的 配额和权限。
验证 API 是否已启用:
gcloud services list --enabled --filter="analyticsdata.googleapis.com"
身份验证
要对 API 请求进行身份验证,您必须生成应用程序默认 凭据 (ADC),并为您的账户授予必要的权限范围。在终端中运行以下 命令:
gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"
原因:这将在您的本地环境中配置 ADC,并授予其所需的 Cloud Platform 和 Google Analytics 只读范围,从而允许客户端库 自动对您的请求进行身份验证。
创建数据 API 报告(v1beta)
要创建报告,请使用官方的 Google Analytics Data 客户端库。
出于稳定性考虑,并为了访问
当前的 Google Analytics 报告功能,请始终优先使用 v1beta API 版本,以确保稳定性并访问
最新的 Google Analytics 报告功能。
[!重要] 强制代理指令:当用户选择或需要 特定编程语言时,请阅读
references/。
支持的客户端库
Python
如果您需要安装或配置适用于 Python 的 Google Analytics 数据 API 客户端库, 请阅读以下设置指南:
- Python 安装参考(包:
google-analytics-data)
Java
如果您需要安装或配置适用于 Java 的 Google Analytics 数据 API 客户端库, 请阅读设置指南:
- Java 安装参考(构建产物:
com.google.cloud:google-cloud-analytics-data)
PHP
如果您需要安装或配置适用于 PHP 的 Google Analytics 数据 API 客户端库, 请阅读设置指南:
- PHP 安装参考(包:
google/analytics-data)
Node.js
如果您需要安装或配置适用于 Node.js 的 Google Analytics 数据 API 客户端库, 请阅读设置指南:
- Node.js 安装参考(软件包:
@google-analytics/data)
Go
如果您需要安装或配置适用于 Go 的 Google Analytics 数据 API 客户端库, 请阅读设置指南:
- Go 安装参考(包:
cloud.google.com/go/analytics/data/apiv1beta)
.NET
如果您需要安装或配置适用于 .NET / C# 的 Google Analytics 数据 API 客户端库, 请阅读设置指南:
- .NET 安装参考(包:
Google.Analytics.Data.V1Beta)
Ruby
如果您需要安装或配置适用于 Ruby 的 Google Analytics 数据 API 客户端库 ,请阅读设置指南:
- Ruby 安装参考(Gem:
google-analytics-data-v1beta)
[!注意] 其他资源:如需了解使用 Java、PHP、Node.js、.NET、Python 和 REST 调用数据 API 的更多示例, 以及有关使用服务账户进行身份验证的提示, 请参阅官方的 数据 API 快速入门指南。
Python 快速入门
安装客户端库:
pip install google-analytics-data如果
pip不可用,请提示用户在pip, 再安装客户端库。运行报告请求:以下是一个完整的示例,演示如何 查询 Google Analytics 属性中的活跃用户和会话,并按城市和日期分组。 请将
YOUR-PROPERTY-ID替换为您的实际 Google Analytics 属性 ID(例如,1234567).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 端点的兼容性,并支持强类型请求 验证。
指标和维度模式
在构建您的 RunReportRequest时,必须为
维度和指标使用有效的API名称。请参阅官方
数据API架构文档
以获取可用字段的完整、权威列表。
常用维度
维度代表数据的分类属性。
city: 用户的城镇或城市。country:用户的国家/地区。date: 事件发生日期,格式为 YYYYMMDD。deviceCategory: 移动设备类别(例如,台式机、移动设备、 平板电脑)。eventName: 触发的事件名称。pageTitle: 网页的标题。
常用指标
指标代表定量测量值。
activeUsers: 活跃用户数量。eventCount: 事件总数。sessions:会话总数。screenPageViews:应用界面或网页的浏览次数。totalRevenue:来自购买、订阅和 广告的总收入。
指标与维度兼容性检查
某些维度和指标无法在同一份报告
请求中同时查询。如果您遇到 INVALID_ARGUMENT 关于字段不兼容的
错误,请验证您的字段组合。若需通过编程方式访问 Data API
架构,请使用 getMetadata()。若要在运行报告前通过编程方式检查
特定维度和指标组合的兼容性,请使用
checkCompatibility() 方法。
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")
---
name: google-analytics-data-api-basics
description: Enables the Google Analytics Data API, authenticates via gcloud, and creates customized reports using the v1beta client library.
---
# Getting Started with 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.
## Enabling the API via Cloud CLI
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"
```
## 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.*
## Creating a Data API Report (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.
### Supported Client Libraries
#### 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](references/python.md) *(Package:
`google-analytics-data`)*
#### 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](references/java.md) *(Artifact:
`com.google.cloud:google-cloud-analytics-data`)*
#### 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](references/php.md) *(Package:
`google/analytics-data`)*
#### 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](references/nodejs.md) *(Package:
`@google-analytics/data`)*
#### 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](references/go.md) *(Package:
`cloud.google.com/go/analytics/data/apiv1beta`)*
#### .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](references/dotnet.md) *(Package:
`Google.Analytics.Data.V1Beta`)*
#### 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](references/ruby.md) *(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](https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart).
### Python Quick Start
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.*
## 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](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema)
for the complete, authoritative list of available fields.
### 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.
### 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.
### 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")
```
所有文件
0 个文件安装 google-analytics-data-api-basics
下载技能文件并将其解压到 .claude/skills/ 目录中。
下载ZIP克隆仓库并复制技能文件到您的项目中。
git clone https://github.com/google/skills/tree/main/skills/analytics/google-analytics-data-api-basics # Copy SKILL.md to your .claude/skills/ directory
复制





首页
