API 快速入门

本页介绍了如何借助客户端库以您喜爱的编程语言开始使用 Google Analytics(分析)Data API v1。

第 1 步:启用 API

点击此按钮即可创建一个新的 Cloud Platform 项目,自动启用 Google Analytics(分析)Data API v1,并创建本教程所需的服务帐号:

启用 Google Analytics(分析)Data API v1

在出现的对话框中,点击下载客户端配置,并将文件 credentials.json 保存到您的工作目录中。

第 2 步:将服务账号添加到 Google Analytics(分析)4 媒体资源

使用文本编辑器打开上一步中下载的 credentials.json 文件,然后搜索 client_email 字段,以获取类似于以下内容的服务帐号电子邮件地址:

quickstart@PROJECT-ID.iam.gserviceaccount.com

使用此电子邮件地址向您希望通过 Google Analytics Data API v1 访问的 Google Analytics(分析)4 媒体资源添加用户。在本教程中,仅需要 Viewer 权限。

第 3 步:配置身份验证

此应用演示了如何通过服务账号凭据使用 Google Analytics(分析)Data API v1。

点此可详细了解如何为应用创建和设置服务帐号凭据。

提供服务帐号凭据的一种简单方法是设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量,API 客户端将使用此变量的值查找服务帐号密钥 JSON 文件。

如需在此示例中设置应用凭据,请运行以下命令,并使用在第 1 步下载的服务帐号 JSON 文件的路径:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/credentials.json"

第 4 步:安装客户端库

Java

Java 客户端库安装指南

Python

Python 客户端库安装指南

Node.js

Node.js 客户端库安装指南

.NET

.NET 客户端库安装指南

PHP

PHP 客户端库安装指南

Go

go get google.golang.org/genproto/googleapis/analytics/data/v1beta

进行 API 调用

现在,您可以使用 Google Analytics(分析)Data API 查询 Google Analytics(分析)4 媒体资源。运行以下代码以执行对 API 的首次调用:

Java

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());
      }
    }
  }
}

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="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)


Node.js

  /**
   * 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();

.NET

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
            var 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)
        {
            SampleRunReport();
            return 0;
        }
    }
}

PHP

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;
}

恭喜!您已向 Google Analytics(分析)Data API 发送了您的第一个请求。