API 빠른 시작

이 페이지에서는 즐겨 사용하는 API에서 Google 애널리틱스 Data API v1을 시작하는 방법을 보여줍니다. 프로그래밍 언어를 빌드할 수 있습니다.

1단계: API 사용 설정

다음 버튼을 클릭하면 새 Google Cloud 프로젝트가 자동으로 생성됩니다. Google Analytics Data API v1을 사용 설정하고 이 튜토리얼에 필요한 서비스 계정을 만듭니다.

Google Analytics Data API v1 사용 설정

표시되는 대화상자에서 다운로드 클라이언트 구성을 클릭하고 파일을 저장합니다. credentials.json를 작업 디렉터리로 복사하세요.

2단계. Google 애널리틱스 속성에 서비스 계정 추가

텍스트 편집기를 사용하여 다운로드한 credentials.json 파일을 엽니다. 이전 단계에서 client_email 필드를 검색하여 서비스 계정 이메일 주소(예: "quickstart@PROJECT-ID.iam.gserviceaccount.com".

이 이메일 주소를 사용하여 사용자를 Google 애널리틱스 Data API v1을 사용하여 액세스하려는 애널리틱스 속성입니다. 이 가이드에서는 뷰어 권한만 필요합니다.

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단계. 클라이언트 라이브러리 설치

API 호출

이제 Google 애널리틱스 Data API를 사용하여 Google 애널리틱스 데이터를 쿼리할 수 있습니다. 속성 다음 코드를 실행하여 API에 대한 첫 번째 호출을 수행합니다.

자바

<ph type="x-smartling-placeholder"></ph> google-analytics-data/src/main/java/com/google/analytics/data/samples/QuickstartSample.java 를 통해 개인정보처리방침을 정의할 수 있습니다.
<ph type="x-smartling-placeholder"></ph> Cloud Shell에서 열기 GitHub에서 보기
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

<ph type="x-smartling-placeholder"></ph> google-analytics-data/quickstart.py 를 통해 개인정보처리방침을 정의할 수 있습니다.
<ph type="x-smartling-placeholder"></ph> Cloud Shell에서 열기 GitHub에서 보기
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

<ph type="x-smartling-placeholder"></ph> google-analytics-data/quickstart.js 를 통해 개인정보처리방침을 정의할 수 있습니다.
<ph type="x-smartling-placeholder"></ph> Cloud Shell에서 열기 GitHub에서 보기
  /**
   * 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

<ph type="x-smartling-placeholder"></ph> google-analytics-data/quickstart.php 를 통해 개인정보처리방침을 정의할 수 있습니다.
<ph type="x-smartling-placeholder"></ph> Cloud Shell에서 열기 GitHub에서 보기
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;
}