เริ่มต้นใช้งาน Google Analytics Data API v1 สําหรับนักพัฒนาซอฟต์แวร์

ในบทแนะนำเริ่มต้นใช้งานนี้ คุณจะได้สร้างและส่งคําขอ list ไปยัง Google Analytics Data API v1 จากนั้นดูคําตอบเพื่อตั้งค่าและยืนยันการเข้าถึง API

คุณเริ่มต้นใช้งานอย่างรวดเร็วนี้โดยใช้ SDK หรือ REST API ในสภาพแวดล้อมภายในหรืออินสแตนซ์ VM ของ Google Cloud ได้

สรุปขั้นตอนมีดังนี้

  • สร้างโปรเจ็กต์ Google Cloud และเปิดใช้ Google Analytics Data API v1
  • ในเครื่องหรืออินสแตนซ์ VM ของ Cloud ให้ทำดังนี้
    • ติดตั้ง เริ่มต้นใช้งาน และตรวจสอบสิทธิ์กับ Google Cloud
    • ติดตั้ง SDK สำหรับภาษาของคุณ (ไม่บังคับ)
  • กำหนดค่าการตรวจสอบสิทธิ์
  • กำหนดค่าการเข้าถึง Google Analytics
  • ตั้งค่า SDK
  • เรียก API

ตั้งค่าโปรเจ็กต์ Google Cloud

คลิกปุ่มเปิดใช้ Google Analytics Data API v1 ต่อไปนี้เพื่อเลือกหรือสร้างโปรเจ็กต์ Google Cloud ใหม่ และเปิดใช้ Google Analytics Data API v1 โดยอัตโนมัติ

เปิดใช้ Google Analytics Data API v1

ตั้งค่า Google Cloud

ตั้งค่าและตรวจสอบสิทธิ์กับ Google Cloud ในเครื่องหรืออินสแตนซ์ VM ของ Cloud

  1. ติดตั้งและเริ่มต้นใช้งาน Google Cloud

  2. เรียกใช้คําสั่งต่อไปนี้เพื่อให้แน่ใจว่าคอมโพเนนต์ gcloud เป็นเวอร์ชันล่าสุด

    gcloud components update

หากไม่ต้องการป้อนรหัสโปรเจ็กต์ให้กับ Google Cloud คุณสามารถใช้คำสั่ง gcloud config set เพื่อตั้งค่าโปรเจ็กต์และภูมิภาคเริ่มต้นได้

กำหนดค่าการตรวจสอบสิทธิ์

บทแนะนำเริ่มต้นใช้งานนี้ใช้ข้อมูลเข้าสู่ระบบเริ่มต้นของแอปพลิเคชันเพื่อค้นหาข้อมูลเข้าสู่ระบบโดยอัตโนมัติตามสภาพแวดล้อมของแอปพลิเคชัน คุณจึงไม่ต้องเปลี่ยนโค้ดไคลเอ็นต์เพื่อตรวจสอบสิทธิ์

Data API v1 ของ Google Analytics รองรับบัญชีผู้ใช้และบัญชีบริการ ดังนี้

  • บัญชีผู้ใช้แสดงถึงนักพัฒนาซอฟต์แวร์ ผู้ดูแลระบบ หรือบุคคลอื่นๆ ที่โต้ตอบกับ 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 ในคําสั่ง ดูข้อมูลเพิ่มเติมได้ที่ตั้งค่าข้อมูลเข้าสู่ระบบเริ่มต้นของแอปพลิเคชัน

บัญชีบริการ

ขั้นตอนการตรวจสอบสิทธิ์ด้วยบัญชีบริการโดยใช้อินสแตนซ์ VM ของ Cloud มีดังนี้

  1. สร้างบัญชีบริการ
  2. แนบบัญชีบริการกับอินสแตนซ์ Cloud VM โดยเรียกใช้คำสั่ง gcloud CLI ต่อไปนี้
  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

คู่มือการติดตั้งไลบรารีของไคลเอ็นต์ Ruby

Go

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

REST

กำหนดค่าตัวแปรสภาพแวดล้อมโดยป้อนข้อมูลต่อไปนี้ แทนที่ PROJECT_ID ด้วยรหัสของโปรเจ็กต์ Google Cloud และแทนที่ PROPERTY_ID ด้วยรหัสของพร็อพเพอร์ตี้ Google Analytics

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