Hướng dẫn nhanh dành cho nhà phát triển về API Dữ liệu của Google Analytics phiên bản 1

Trong hướng dẫn nhanh này, bạn sẽ tạo và gửi các yêu cầu list đến Google Analytics Data API phiên bản 1, sau đó xem các phản hồi để thiết lập và xác minh quyền truy cập API.

Bạn có thể hoàn tất hướng dẫn nhanh này bằng cách sử dụng một SDK hoặc API REST trong môi trường cục bộ hoặc phiên bản máy ảo Google Cloud.

Dưới đây là phần tóm tắt các bước:

  • Thiết lập một dự án Google Cloud và bật API Dữ liệu Google Analytics phiên bản 1.
  • Trên máy cục bộ hoặc phiên bản máy ảo trên đám mây:
    • Cài đặt, khởi chạy và xác thực bằng Google Cloud.
    • Cài đặt SDK cho ngôn ngữ của bạn (không bắt buộc).
  • Định cấu hình tính năng xác thực.
  • Định cấu hình quyền truy cập vào Google Analytics.
  • Thiết lập SDK.
  • Thực hiện lệnh gọi API.

Thiết lập dự án trên Google Cloud

Nhấp vào nút Bật API Dữ liệu Google Analytics phiên bản 1 sau đây để chọn hoặc tạo một dự án Google Cloud mới và tự động bật API Dữ liệu Google Analytics phiên bản 1.

Bật API Dữ liệu Google Analytics phiên bản 1

Thiết lập Google Cloud

Trên máy cục bộ hoặc phiên bản máy ảo trên đám mây, hãy thiết lập và xác thực bằng Google Cloud.

  1. Cài đặt và khởi chạy Google Cloud.

  2. Để đảm bảo các thành phần gcloud của bạn luôn mới nhất, hãy chạy lệnh sau.

    gcloud components update

Để tránh cung cấp mã dự án cho Google Cloud, bạn có thể sử dụng lệnh gcloud config set để đặt dự án và khu vực mặc định.

Định cấu hình tính năng xác thực

Phần bắt đầu nhanh này sử dụng Thông tin xác thực mặc định của ứng dụng để tự động tìm thông tin xác thực dựa trên môi trường ứng dụng, vì vậy, bạn không phải thay đổi mã ứng dụng để xác thực.

API Dữ liệu Google Analytics phiên bản 1 hỗ trợ tài khoản người dùngtài khoản dịch vụ:

  • Tài khoản người dùng đại diện cho một nhà phát triển, quản trị viên hoặc bất kỳ người nào khác tương tác với các API và dịch vụ của Google.
  • Tài khoản dịch vụ không đại diện cho một người dùng cụ thể. Các API này cung cấp một cách để quản lý việc xác thực và uỷ quyền khi không có con người tham gia trực tiếp, chẳng hạn như khi một ứng dụng cần truy cập vào tài nguyên của Google Cloud.

Để tìm hiểu thêm về việc xác thực và thiết lập thông tin xác thực tài khoản cho ứng dụng, hãy xem bài viết Các phương thức xác thực tại Google.

Tài khoản người dùng

Tạo tệp Thông tin xác thực mặc định của ứng dụng (ADC) cục bộ bằng cách chạy lệnh sau. Lệnh này sẽ khởi chạy một luồng web để bạn cung cấp thông tin xác thực người dùng.

  gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.readonly"

Hãy nhớ chỉ định các phạm vi mà API Dữ liệu Google Analytics phiên bản 1 yêu cầu trong lệnh. Để biết thêm thông tin, hãy xem bài viết Thiết lập thông tin xác thực mặc định của ứng dụng

Tài khoản dịch vụ

Dưới đây là các bước xác thực bằng tài khoản dịch vụ bằng một phiên bản máy ảo trên đám mây:

  1. Tạo tài khoản dịch vụ.
  2. Đính kèm tài khoản dịch vụ vào thực thể máy ảo trên Google Cloud bằng cách chạy lệnh gcloud CLI sau:
  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"

Hãy nhớ chỉ định các phạm vi mà API Dữ liệu Google Analytics phiên bản 1 yêu cầu trong lệnh. Để biết thêm thông tin, hãy xem bài viết Thiết lập thông tin xác thực mặc định của ứng dụng

Định cấu hình quyền truy cập vào Google Analytics

Cấp quyền truy cập cho Google Analytics vào email liên kết với tài khoản người dùng hoặc tài khoản dịch vụ của bạn.

Thiết lập SDK cho ngôn ngữ lập trình

Trên máy cục bộ, hãy cài đặt SDK cho ngôn ngữ lập trình của bạn.

Java

Hướng dẫn cài đặt thư viện ứng dụng Java

PHP

Hướng dẫn cài đặt thư viện ứng dụng PHP

Python

Hướng dẫn cài đặt thư viện ứng dụng Python

Node.js

Hướng dẫn cài đặt thư viện ứng dụng Node.js

.NET

Hướng dẫn cài đặt thư viện ứng dụng.NET

Ruby

Hướng dẫn cài đặt thư viện ứng dụng Ruby

Go

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

REST

Định cấu hình các biến môi trường bằng cách nhập nội dung sau. Thay thế PROJECT_ID bằng mã nhận dạng của dự án Google Cloud và PROPERTY_ID bằng mã nhận dạng của tài sản Google Analytics.

  export PROJECT_ID=PROJECT_ID
  export PROPERTY_ID=PROPERTY_ID

Thực hiện lệnh gọi API

Chạy mã sau để thực hiện lệnh gọi đầu tiên:

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

Để gửi yêu cầu này, hãy chạy lệnh curl từ dòng lệnh hoặc đưa lệnh gọi REST vào ứng dụng.

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

Phản hồi sẽ chứa một báo cáo có số người dùng đang hoạt động được phân tích theo quốc gia, ví dụ:

{
  "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"
}