在本快速入门中,您将创建并向 Google Analytics Data API v1 发送 list
请求,然后查看响应以设置和验证您的 API 访问权限。
您可以使用 SDK、本地环境中的 REST API 或 Google Cloud 虚拟机实例完成本快速入门。
下面总结了这些步骤:
- 设置一个 Google Cloud 项目并启用 Google Analytics Data API v1。
- 在本地机器或 Cloud VM 实例上:
- 安装、初始化并使用 Google Cloud 进行身份验证。
- 安装适用于您所用语言的 SDK(可选)。
- 配置身份验证。
- 配置 Google Analytics 访问权限。
- 设置 SDK。
- 进行 API 调用。
设置 Google Cloud 项目
点击以下启用 Google Analytics Data API v1 按钮,选择或创建一个新的 Google Cloud 项目,然后自动启用 Google Analytics Data API v1。
设置 Google Cloud
在本地机器或 Cloud 虚拟机实例上,设置并使用 Google Cloud 进行身份验证。
-
安装并初始化 Google Cloud。
-
如需确保您的
gcloud
组件是最新的,请运行以下命令。gcloud components update
为避免向 Google Cloud 提供您的项目 ID,您可以使用 gcloud config set
命令设置默认项目和区域。
配置身份验证
本快速入门使用应用默认凭据根据应用环境自动查找凭据,因此您无需更改客户端代码即可进行身份验证。
Google Analytics Data API v1 支持用户账号和服务账号:
- 用户账号代表开发者、管理员或与 Google API 和服务进行交互的任何其他人员。
- 服务账号不代表特定真人用户。它们提供了一种在真人不直接参与(例如,应用需要访问 Google Cloud 资源)时管理身份验证和授权的方法。
如需详细了解身份验证以及为应用设置账号凭据,请参阅 Google 的身份验证方法。
运行以下命令,生成本地应用默认凭据 (ADC) 文件。此命令会启动一个 Web 流程,您可以在其中提供用户凭据。
gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"
请务必在命令中指定 Google Analytics Data API v1 所需的范围。 如需了解详情,请参阅设置应用默认凭据
以下是使用 Cloud VM 实例通过服务账号进行身份验证的步骤:
- 创建服务账号。
- 运行以下 gcloud CLI 命令,将服务账号附加到 Cloud 虚拟机实例:
gcloud compute instances stop YOUR-VM-INSTANCE-ID
gcloud compute instances set-service-account YOUR-VM-INSTANCE-ID \
--service-account YOUR-SERVICE-ACCOUNT-EMAIL-ALIAS \
--scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"
请务必在命令中指定 Google Analytics Data API v1 所需的范围。 如需了解详情,请参阅设置应用默认凭据
配置对 Google Analytics 的访问权限
向 Google Analytics 授予对与您的用户账号或服务账号关联的电子邮件的访问权限。
为您的编程语言设置 SDK
在本地机器上,安装适用于您所用编程语言的 SDK。
go get google.golang.org/genproto/googleapis/analytics/data/v1beta
输入以下命令来配置环境变量。
将 PROJECT_ID
替换为您的 Google Cloud 项目的 ID,并将 PROPERTY_ID
替换为您的 Google Analytics 媒体资源的 ID。
export PROJECT_ID=PROJECT_ID export PROPERTY_ID=PROPERTY_ID
进行 API 调用
运行以下代码以进行首次调用:
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.Row; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; /** * Google Analytics Data API sample quickstart application. * * <p>This application demonstrates the usage of the Analytics Data API using service account * credentials. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.QuickstartSample" * }</pre> */ public class QuickstartSample { public static void main(String... args) throws Exception { /** * TODO(developer): Replace this variable with your Google Analytics 4 property ID before * running the sample. */ String propertyId = "YOUR-GA4-PROPERTY-ID"; sampleRunReport(propertyId); } // This is an example snippet that calls the Google Analytics Data API and runs a simple report // on the provided GA4 property id. static void sampleRunReport(String propertyId) throws Exception { // Using a default constructor instructs the client to use the credentials // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty("properties/" + propertyId) .addDimensions(Dimension.newBuilder().setName("city")) .addMetrics(Metric.newBuilder().setName("activeUsers")) .addDateRanges(DateRange.newBuilder().setStartDate("2020-03-31").setEndDate("today")) .build(); // Make the request. RunReportResponse response = analyticsData.runReport(request); System.out.println("Report result:"); // Iterate through every row of the API response. for (Row row : response.getRowsList()) { System.out.printf( "%s, %s%n", row.getDimensionValues(0).getValue(), row.getMetricValues(0).getValue()); } } } }
require 'vendor/autoload.php'; use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\DateRange; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\RunReportRequest; /** * TODO(developer): Replace this variable with your Google Analytics 4 * property ID before running the sample. */ $property_id = 'YOUR-GA4-PROPERTY-ID'; // Using a default constructor instructs the client to use the credentials // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $property_id) ->setDateRanges([ new DateRange([ 'start_date' => '2020-03-31', 'end_date' => 'today', ]), ]) ->setDimensions([new Dimension([ 'name' => 'city', ]), ]) ->setMetrics([new Metric([ 'name' => 'activeUsers', ]) ]); $response = $client->runReport($request); // Print results of an API call. print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { print $row->getDimensionValues()[0]->getValue() . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL; }
from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import ( DateRange, Dimension, Metric, RunReportRequest, ) def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. # property_id = "YOUR-GA4-PROPERTY-ID" # Using a default constructor instructs the client to use the credentials # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="city")], metrics=[Metric(name="activeUsers")], date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], ) response = client.run_report(request) print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value)
/** * TODO(developer): Uncomment this variable and replace with your * Google Analytics 4 property ID before running the sample. */ // propertyId = 'YOUR-GA4-PROPERTY-ID'; // Imports the Google Analytics Data API client library. const {BetaAnalyticsDataClient} = require('@google-analytics/data'); // Using a default constructor instructs the client to use the credentials // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. const analyticsDataClient = new BetaAnalyticsDataClient(); // Runs a simple report. async function runReport() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [ { startDate: '2020-03-31', endDate: 'today', }, ], dimensions: [ { name: 'city', }, ], metrics: [ { name: 'activeUsers', }, ], }); console.log('Report result:'); response.rows.forEach((row) => { console.log(row.dimensionValues[0], row.metricValues[0]); }); } runReport();
using Google.Analytics.Data.V1Beta; using System; namespace AnalyticsSamples { class QuickStart { static void SampleRunReport(string propertyId="YOUR-GA4-PROPERTY-ID") { /** * TODO(developer): Uncomment this variable and replace with your * Google Analytics 4 property ID before running the sample. */ // propertyId = "YOUR-GA4-PROPERTY-ID"; // Using a default constructor instructs the client to use the credentials // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create(); // Initialize request argument(s) RunReportRequest request = new RunReportRequest { Property = "properties/" + propertyId, Dimensions = { new Dimension{ Name="city"}, }, Metrics = { new Metric{ Name="activeUsers"}, }, DateRanges = { new DateRange{ StartDate="2020-03-31", EndDate="today"}, }, }; // Make the request RunReportResponse response = client.RunReport(request); Console.WriteLine("Report result:"); foreach(Row row in response.Rows) { Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value); } } static int Main(string[] args) { if (args.Length > 0) { SampleRunReport(args[0]); } else { SampleRunReport(); } return 0; } } }
如需发送此请求,请从命令行运行 curl 命令,或在应用中添加 REST 调用。
curl -X POST \ -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \ -H "x-goog-user-project: ${PROJECT_ID}" \ -H "Content-Type: application/json" \ -d ' { "dateRanges": [ { "startDate": "2025-01-01", "endDate": "2025-02-01" } ], "dimensions": [ { "name": "country" } ], "metrics": [ { "name": "activeUsers" } ] }' https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runReport
响应中将包含一份报告,其中按国家/地区对活跃用户数进行了细分,例如:
{
"dimensionHeaders": [
{
"name": "country"
}
],
"metricHeaders": [
{
"name": "activeUsers",
"type": "TYPE_INTEGER"
}
],
"rows": [
{
"dimensionValues": [
{
"value": "United States"
}
],
"metricValues": [
{
"value": "3242"
}
]
},
{
"dimensionValues": [
{
"value": "(not set)"
}
],
"metricValues": [
{
"value": "3015"
}
]
},
{
"dimensionValues": [
{
"value": "India"
}
],
"metricValues": [
{
"value": "805"
}
]
}
],
"rowCount": 3,
"metadata": {
"currencyCode": "USD",
"timeZone": "America/Los_Angeles"
},
"kind": "analyticsData#runReport"
}