Google Analytics Data API v1 開發人員快速入門

在本快速入門中,您將建立並傳送 list 要求至 Google Analytics Data API v1,然後查看回應,設定並驗證 API 存取權。

您可以使用 SDK 或本機環境或 Google Cloud VM 執行個體中的 REST API 完成此快速入門導覽課程。

以下是步驟摘要:

  • 設定 Google Cloud 專案並啟用 Google Analytics Data API v1。
  • 在本機或 Cloud VM 執行個體上:
    • 安裝、初始化及驗證 Google Cloud。
    • 安裝所用語言的 SDK (選用)。
  • 設定驗證機制。
  • 設定 Google Analytics 存取權。
  • 設定 SDK。
  • 發出 API 呼叫。

設定 Google Cloud 專案

按一下下方的「Enable the Google Analytics Data API v1」按鈕,即可選取或建立新的 Google Cloud 專案,並自動啟用 Google Analytics Data API v1。

啟用 Google Analytics Data API 1.0

設定 Google Cloud

在本機電腦或 Cloud VM 執行個體上,設定並透過 Google Cloud 進行驗證。

  1. 安裝並初始化 Google Cloud。

  2. 如要確保 gcloud 元件為最新版本,請執行下列指令。

    gcloud components update

如要避免向 Google Cloud 提供專案 ID,您可以使用 gcloud config set 指令設定預設專案和區域。

設定驗證機制

本快速入門課程會使用應用程式預設憑證,根據應用程式環境自動尋找憑證,因此您不必變更用戶端程式碼來進行驗證。

Google Analytics Data API 第 1 版支援使用者帳戶服務帳戶

  • 使用者帳戶代表開發人員、管理員或任何其他與 Google API 和服務互動的使用者。
  • 服務帳戶不代表特定真人使用者。在沒有人為直接介入的情況下,例如應用程式需要存取 Google Cloud 資源時,這些服務可用於管理驗證和授權作業。

如要進一步瞭解驗證和為應用程式設定帳戶憑證,請參閱「Google 的驗證方式」。

使用者帳戶

執行下列指令,產生本機應用程式預設憑證 (ADC) 檔案。這個指令會啟動網頁流程,讓您提供使用者憑證。

  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 執行個體透過服務帳戶進行驗證的步驟:

  1. 建立服務帳戶
  2. 執行下列 gcloud CLI 指令,將服務帳戶連結至 Cloud VM 執行個體
  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。

Java

Java 用戶端程式庫安裝指南

PHP

PHP 用戶端程式庫安裝指南

Python

Python 用戶端程式庫安裝指南

Node.js

Node.js 用戶端程式庫安裝指南

.NET

.NET 用戶端程式庫安裝指南

小茹

Ruby 用戶端程式庫安裝指南

Go

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

REST

輸入下列內容來設定環境變數。 將 PROJECT_ID 替換為 Google Cloud 專案的 ID,並將 PROPERTY_ID 替換為 Google Analytics 資源的 ID。

  export PROJECT_ID=PROJECT_ID
  export PROPERTY_ID=PROPERTY_ID

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

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

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

REST

如要傳送這項要求,請透過指令列執行 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"
}