이 빠른 시작에서는 Google 애널리틱스 Admin API에 list
요청을 만들고 전송한 후 응답을 확인하여 API 액세스를 설정하고 확인합니다.
SDK 또는 로컬 환경의 REST API 또는 Google Cloud VM 인스턴스를 사용하여 이 빠른 시작을 완료할 수 있습니다.
다음은 단계를 요약한 내용입니다.
- Google Cloud 프로젝트를 설정하고 Google 애널리틱스 관리 API를 사용 설정합니다.
- 로컬 머신 또는 Cloud VM 인스턴스에서 다음을 실행합니다.
- Google Cloud를 설치, 초기화, 인증합니다.
- 사용 언어의 SDK를 설치합니다 (선택사항).
- 인증을 구성합니다.
- Google 애널리틱스 액세스를 구성합니다.
- SDK를 설정합니다.
- API를 호출합니다.
Google Cloud 프로젝트 설정
다음 Google 애널리틱스 Admin API 사용 설정 버튼을 클릭하여 새 Google Cloud 프로젝트를 선택하거나 만들고 Google 애널리틱스 Admin API를 자동으로 사용 설정합니다.
Google Cloud 설정
로컬 머신 또는 Cloud VM 인스턴스에서 Google Cloud를 설정하고 인증합니다.
-
Google Cloud를 설치하고 초기화합니다.
-
gcloud
구성요소가 최신 상태인지 확인하려면 다음 명령어를 실행합니다.gcloud components update
Google Cloud에 프로젝트 ID를 제공하지 않으려면 gcloud config set
명령어를 사용하여 기본 프로젝트 및 리전을 설정하면 됩니다.
인증 구성
이 빠른 시작에서는 애플리케이션 기본 사용자 인증 정보를 사용하여 애플리케이션 환경을 기반으로 사용자 인증 정보를 자동으로 찾으므로 인증하기 위해 클라이언트 코드를 변경할 필요가 없습니다.
Google 애널리틱스 Admin API는 사용자 계정과 서비스 계정을 지원합니다.
- 사용자 계정은 개발자, 관리자 또는 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 애널리틱스 Admin API에 필요한 범위를 지정해야 합니다. 자세한 내용은 애플리케이션 기본 사용자 인증 정보 설정을 참고하세요.
서비스 계정으로 인증하는 단계는 다음과 같습니다.
- 서비스 계정을 만듭니다.
- 다음 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 애널리틱스 Admin API에 필요한 범위를 지정해야 합니다. 자세한 내용은 애플리케이션 기본 사용자 인증 정보 설정을 참고하세요.
Google 애널리틱스 액세스 권한 구성
사용자 또는 서비스 계정과 연결된 이메일에 Google 애널리틱스 액세스 권한을 부여합니다.
프로그래밍 언어의 SDK 설정
로컬 머신에서 프로그래밍 언어의 SDK를 설치합니다.
go get google.golang.org/genproto/googleapis/analytics/admin/v1beta
다음을 입력하여 환경 변수를 구성합니다.
PROJECT_ID
를 Google Cloud 프로젝트의 ID로 바꿉니다.
EXPORT PROJECT_ID=PROJECT_ID
API 호출
다음 코드를 실행하여 첫 번째 호출을 실행합니다.
import com.google.analytics.admin.v1beta.Account; import com.google.analytics.admin.v1beta.AnalyticsAdminServiceClient; import com.google.analytics.admin.v1beta.AnalyticsAdminServiceClient.ListAccountsPage; import com.google.analytics.admin.v1beta.AnalyticsAdminServiceClient.ListAccountsPagedResponse; import com.google.analytics.admin.v1beta.ListAccountsRequest; /** * This application demonstrates the usage of the Analytics Admin API using service account * credentials. For more information on service accounts, see * https://cloud.google.com/iam/docs/understanding-service-accounts. * * <p>The following document provides instructions on setting service account credentials for your * application: https://cloud.google.com/docs/authentication/production * * <p>In a nutshell, you need to: * * <ol> * <li>Create a service account and download the key JSON file as described at * https://cloud.google.com/docs/authentication/production#creating_a_service_account. * <li>Provide service account credentials using one of the following options: * <ul> * <li>Set the {@code GOOGLE_APPLICATION_CREDENTIALS} environment variable. The API client * will use the value of this variable to find the service account key JSON file. See * https://cloud.google.com/docs/authentication/production#setting_the_environment_variable * for more information. * <p>OR * <li>Manually pass the path to the service account key JSON file to the API client by * specifying the {@code keyFilename} parameter in the constructor. See * https://cloud.google.com/docs/authentication/production#passing_the_path_to_the_service_account_key_in_code * for more information. * </ul> * </ol> * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.admin.samples.QuickstartSample" * }</pre> */ public class QuickstartSample { public static void main(String... args) throws Exception { listAccounts(); } // This is an example snippet that calls the Google Analytics Admin API and lists all Google // Analytics accounts available to the authenticated user. static void listAccounts() throws Exception { // Instantiates a client using default credentials. // See https://cloud.google.com/docs/authentication/production for more information // about managing credentials. try (AnalyticsAdminServiceClient analyticsAdmin = AnalyticsAdminServiceClient.create()) { // Calls listAccounts() method of the Google Analytics Admin API and prints // the response for each account. ListAccountsPagedResponse response = analyticsAdmin.listAccounts(ListAccountsRequest.newBuilder().build()); for (ListAccountsPage page : response.iteratePages()) { for (Account account : page.iterateAll()) { System.out.printf("Account name: %s%n", account.getName()); System.out.printf("Display name: %s%n", account.getDisplayName()); System.out.printf("Country code: %s%n", account.getRegionCode()); System.out.printf("Create time: %s%n", account.getCreateTime().getSeconds()); System.out.printf("Update time: %s%n", account.getUpdateTime().getSeconds()); System.out.println(); } } } } }
require 'vendor/autoload.php'; use Google\Analytics\Admin\V1beta\Account; use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\ListAccountsRequest; /** * 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. // See https://cloud.google.com/docs/authentication/production for more information // about managing credentials. $client = new AnalyticsAdminServiceClient(); // Calls listAccounts() method of the Google Analytics Admin API and prints // the response for each account. $request = new ListAccountsRequest(); $response = $client->listAccounts($request); print 'Result:' . PHP_EOL; foreach ($response->iterateAllElements() as $account) { print 'Account name: ' . $account->getName() . PHP_EOL; print 'Display name: ' . $account->getDisplayName() . PHP_EOL; print 'Country code: ' . $account->getRegionCode() . PHP_EOL; print 'Create time: ' . $account->getCreateTime()->getSeconds() . PHP_EOL; print 'Update time: ' . $account->getUpdateTime()->getSeconds() . PHP_EOL; }
def list_accounts(transport: str = None): """ Lists the available Google Analytics accounts. Args: transport(str): The transport to use. For example, "grpc" or "rest". If set to None, a transport is chosen automatically. """ from google.analytics.admin import AnalyticsAdminServiceClient # Using a default constructor instructs the client to use the credentials # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. client = AnalyticsAdminServiceClient(transport=transport) results = client.list_accounts() # Displays the configuration information for all Google Analytics accounts # available to the authenticated user. print("Result:") for account in results: print(account)
// Imports the Google Analytics Admin API client library. const analyticsAdmin = require('@google-analytics/admin'); // Using a default constructor instructs the client to use the credentials // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient(); // Lists all Google Analytics accounts available to the authenticated user. async function listAccounts() { // Uses listAccounts() with no arguments to fetch all pages. For more // information on pagination in the Node.js library, see: // https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination const [response] = await analyticsAdminClient.listAccounts(); console.log('Accounts:'); for (const account of response) { console.log('Account name:', account.name); console.log('Display name:', account.displayName); console.log('Region code:', account.regionCode); console.log('Create time:', account.createTime.seconds); console.log('Update time:', account.updateTime.seconds); } } listAccounts();
using Google.Analytics.Admin.V1Beta; using Google.Api.Gax; using System; namespace AnalyticsSamples { class QuickStart { static void Main(string[] args) { AnalyticsAdminServiceClient client = AnalyticsAdminServiceClient.Create(); PagedEnumerable<ListAccountsResponse, Account> response = client.ListAccounts( new ListAccountsRequest() ); foreach( Account account in response ) { Console.WriteLine("Account name: {0}", account.Name); Console.WriteLine("Display name: {0}", account.DisplayName); Console.WriteLine("Region code: {0}", account.RegionCode); Console.WriteLine("Update time: {0}", account.UpdateTime); Console.WriteLine("Create time: {0}", account.CreateTime); Console.WriteLine(); } } } }
이 요청을 전송하려면 명령줄에서 curl 명령어를 실행하거나 애플리케이션에 REST 호출을 포함하세요.
curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \ -H "x-goog-user-project: ${PROJECT_ID}" \ -H "Content-Type: application/json" \ https://analyticsadmin.googleapis.com/v1beta/accounts
샘플 코드 응답에는 사용자 또는 서비스 계정이 볼 수 있는 Google 애널리틱스 계정이 나열됩니다.
{
"accounts": [
{
"name": "accounts/123456789",
"createTime": "2025-01-01T00:12:23.456Z",
"createTime": "2025-01-01T00:12:23.456Z",
"displayName": "Demo Account",
"regionCode": "US",
"gmpOrganization": "marketingplatformadmin.googleapis.com/organizations/abcdef12345678"
}
}