การเริ่มต้นใช้งาน API อย่างรวดเร็ว

หน้านี้แสดงวิธีเริ่มต้นใช้งาน Google Analytics Data API v1 ในรายการโปรด ภาษาโปรแกรมโดยใช้ไลบรารีของไคลเอ็นต์

ขั้นตอนที่ 1 เปิดใช้ API

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

เปิดใช้ Google Analytics Data API เวอร์ชัน 1

ในกล่องโต้ตอบที่ปรากฏขึ้น ให้คลิกดาวน์โหลดการกำหนดค่าไคลเอ็นต์ และบันทึกไฟล์ credentials.json ไปยังไดเรกทอรีที่ใช้งานอยู่

ขั้นตอนที่ 2 เพิ่มบัญชีบริการลงในพร็อพเพอร์ตี้ Google Analytics

ใช้เครื่องมือแก้ไขข้อความเปิดไฟล์ credentials.json ที่ดาวน์โหลดไว้ ขั้นตอนก่อนหน้าและค้นหาฟิลด์ client_email เพื่อให้ได้ค่า อีเมลบัญชีบริการ เช่น "quickstart@PROJECT-ID.iam.gserviceaccount.com".

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

ขั้นตอนที่ 3 กำหนดค่าการตรวจสอบสิทธิ์

แอปพลิเคชันนี้แสดงการใช้งาน Google Analytics Data API v1 โดยใช้ service บัญชี ข้อมูลเข้าสู่ระบบ

อ่านเพิ่มเติมสำหรับ วิธีการสร้างและตั้งค่าข้อมูลเข้าสู่ระบบของบัญชีบริการสำหรับ แอปพลิเคชัน

วิธีหนึ่งในการระบุข้อมูลเข้าสู่ระบบของบัญชีบริการคือการตั้งค่า ตัวแปรสภาพแวดล้อม GOOGLE_APPLICATION_CREDENTIALS ไคลเอ็นต์ API จะใช้ค่าของตัวแปรนี้เพื่อค้นหาบัญชีบริการ ไฟล์คีย์ JSON

หากต้องการตั้งค่าข้อมูลเข้าสู่ระบบของแอปพลิเคชันในตัวอย่างนี้ ให้เรียกใช้คำสั่งต่อไปนี้ และใช้เส้นทางไปยังไฟล์ JSON ของบัญชีบริการที่ดาวน์โหลดไว้ในขั้นตอนที่ 1 ดังนี้

 export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

เช่น

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

ขั้นตอนที่ 4 ติดตั้งไลบรารีของไคลเอ็นต์

ทำการเรียก API

ตอนนี้คุณสามารถใช้ Google Analytics Data API เพื่อค้นหาข้อมูลใน Google Analytics เรียกใช้โค้ดต่อไปนี้เพื่อเรียกใช้ 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-GA"4-PROPERTY-ID)
     "   {
            /**
             * TODO(developer): Uncomment this variable and replace with your
             *  Google Analytics 4 property ID before running the sample.
             */
            // propertyId = YOUR-GA4-PROP"ERTY-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/ + property"Id,
       "         Dimensions = { new Dimension{ Name=city}, },
             "   M"etrics = { new Metric{ Name=activeUsers}, },
       "         Da"teRanges = { new DateRange{ StartDate=2020-03-31, EndDate=today"}, },
    "        };"

   "         // Make the request
            var response = client.RunReport(request);

            Console.WriteLine(Report result:);
            fo"reach(Row row "in response.Rows)
            {
                Console.WriteLine({0}, {1}, row.DimensionValues[0].V"alue, ro"w.MetricValues[0].Value);
            }
        }
        static int Main(string[] args)
        {
            SampleRunReport();
            return 0;
        }
    }
}
QuickStart.cs

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