이 빠른 시작에서는 Google 애널리틱스 Data API v1에 list
요청을 만들고 전송한 후 응답을 확인하여 API 액세스를 설정하고 확인합니다.
SDK 또는 로컬 환경의 REST API 또는 Google Cloud VM 인스턴스를 사용하여 이 빠른 시작을 완료할 수 있습니다.
다음은 단계를 요약한 내용입니다.
- Google Cloud 프로젝트를 설정하고 Google Analytics Data API v1을 사용 설정합니다.
- 로컬 머신 또는 Cloud VM 인스턴스에서 다음을 실행합니다.
- Google Cloud를 설치, 초기화, 인증합니다.
- 언어의 SDK를 설치합니다 (선택사항).
- 인증을 구성합니다.
- Google 애널리틱스 액세스를 구성합니다.
- SDK를 설정합니다.
- API를 호출합니다.
Google Cloud 프로젝트 설정
다음 Google 애널리틱스 Data API v1 사용 설정 버튼을 클릭하여 새 Google Cloud 프로젝트를 선택하거나 만들고 Google 애널리틱스 Data API v1을 자동으로 사용 설정합니다.
Google Analytics Data API v1 사용 설정Google Cloud 설정
로컬 머신 또는 Cloud VM 인스턴스에서 Google Cloud를 설정하고 인증합니다.
-
Google Cloud를 설치하고 초기화합니다.
-
gcloud
구성요소가 최신 상태인지 확인하려면 다음 명령어를 실행합니다.gcloud components update
Google Cloud에 프로젝트 ID를 제공하지 않으려면 gcloud config set
명령어를 사용하여 기본 프로젝트 및 리전을 설정하면 됩니다.
인증 구성
이 빠른 시작에서는 애플리케이션 기본 사용자 인증 정보를 사용하여 애플리케이션 환경을 기반으로 사용자 인증 정보를 자동으로 찾으므로 인증하기 위해 클라이언트 코드를 변경할 필요가 없습니다.
Google Analytics Data API v1은 사용자 계정과 서비스 계정을 지원합니다.
- 사용자 계정은 개발자, 관리자 또는 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 애널리틱스 Data API v1에 필요한 범위를 지정해야 합니다. 자세한 내용은 애플리케이션 기본 사용자 인증 정보 설정을 참고하세요.
서비스 계정
Cloud VM 인스턴스를 사용하여 서비스 계정으로 인증하는 단계는 다음과 같습니다.
- 서비스 계정을 만듭니다.
- 다음 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 애널리틱스 Data API v1에 필요한 범위를 지정해야 합니다. 자세한 내용은 애플리케이션 기본 사용자 인증 정보 설정을 참고하세요.
Google 애널리틱스 액세스 권한 구성
사용자 또는 서비스 계정과 연결된 이메일에 Google 애널리틱스 액세스 권한을 부여합니다.
프로그래밍 언어의 SDK 설정
로컬 머신에서 프로그래밍 언어의 SDK를 설치합니다.
자바
PHP
Python
Node.js
.NET
Ruby
Go
go get google.golang.org/genproto/googleapis/analytics/data/v1beta
REST
다음을 입력하여 환경 변수를 구성합니다.
PROJECT_ID
를 Google Cloud 프로젝트의 ID로 바꾸고 PROPERTY_ID
를 Google 애널리틱스 속성의 ID로 바꿉니다.
export PROJECT_ID=PROJECT_ID
export PROPERTY_ID=PROPERTY_ID
API 호출
다음 코드를 실행하여 첫 번째 호출을 실행합니다.
자바
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"
}