Google Analytics Admin API v1로 이전

API의 알파 및 베타 채널 모두 계속 지원됩니다. 베타 채널에는 알파에서 사용할 수 있는 기능의 하위 집합이 포함되어 있으며, 이러한 기능은 안정적이고 향후 큰 변화가 없을 것으로 예상됩니다. 새로운 기능은 기능이 개발되면 베타에 추가될 예정입니다.

이 문서에서는 기존 코드를 Google Analytics Management API v3에서 Google Analytics Admin API v1로 이전하는 방법을 안내하고 두 API 간 주요 차이점을 간략히 설명합니다.

이전을 해야 하는 이유는 무엇인가요?

애플리케이션에서 Google 애널리틱스 4 속성을 만들거나 구성해야 하는 경우 Admin API v1을 사용해야 합니다. Management API v3는 유니버설 애널리틱스 속성에서만 작동하며 Admin API v1은 Google 애널리틱스 4 속성에서만 작동합니다.

기본 요건

빠른 시작 가이드를 참고하여 Admin API v1의 기본 사항을 숙지하는 것이 좋습니다.

사용해 보기

시작하려면 Google 애널리틱스 4 속성을 준비하고 Admin API v1을 사용 설정한 다음, 플랫폼에 적합한 API 클라이언트 라이브러리를 설정합니다.

Google 애널리틱스 4 속성 준비

Admin API v1을 지원하도록 코드를 이전하기 전에 Google 애널리틱스 4 속성을 사용할 수 있도록 웹사이트를 이전해야 합니다.

API 사용 설정

선택한 Google Cloud 프로젝트에서 Admin API v1을 자동으로 사용 설정하려면 이 버튼을 클릭합니다.

Google Analytics Admin API 사용 설정

클라이언트 라이브러리 사용

클라이언트 라이브러리 설치

클라이언트 라이브러리를 사용하는 경우, 프로그래밍 언어에 사용할 Admin API v1 클라이언트 라이브러리를 설치해야 합니다.

클라이언트 라이브러리 초기화

Admin API v1 클라이언트 라이브러리는 개발자가 빠르게 시작할 수 있도록 설계되었습니다. 기본적으로 클라이언트 라이브러리는 서비스 계정 사용자 인증 정보를 자동으로 찾으려고 시도합니다.

GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정하면 서비스 계정 사용자 인증 정보를 쉽게 제공할 수 있으며, API 클라이언트가 이 변수의 값을 사용하여 서비스 계정 키 JSON 파일을 찾습니다.

예를 들어 다음 명령어를 실행하고 서비스 계정 JSON 파일 경로를 사용하여 서비스 계정 사용자 인증 정보를 설정할 수 있습니다.

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

다음은 Admin API v1 클라이언트 라이브러리를 초기화하는 데 일반적으로 사용되는 코드 스니펫입니다.

Java

    try (AnalyticsAdminServiceClient analyticsAdmin = AnalyticsAdminServiceClient.create()) {

Python

client = BetaAnalyticsAdminClient()

.NET

BetaAnalyticsAdminClient client = BetaAnalyticsAdminClient.Create();

2,399필리핀

$client = new AlphaAnalyticsAdminClient();

Node.js

  // 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();

환경 변수를 사용하는 대신, 초기화 과정에서 사용자 인증 정보 정보를 API 클라이언트 인스턴스에 명시적으로 전달할 수 있습니다.

클라이언트 라이브러리를 사용하지 않는 경우

클라이언트 라이브러리 없이 Management API v3를 사용하고 Admin API v1에서도 계속 클라이언트 라이브러리를 사용하지 않으려면, 사용자 인증 정보를 그대로 사용하면 됩니다.

Admin API에서 제공하는 새 HTTP 엔드포인트 및 검색 문서를 사용해야 합니다.

코드가 검색 문서를 활용하는 경우, Admin API v1에서 제공하는 검색 문서로 업데이트해야 합니다.

엔드포인트를 업데이트한 후, JSON 쿼리를 업데이트하려면 Admin API의 새로운 요청 구조와 개념을 숙지해야 합니다.

일반적인 작업

계정 관리

Admin API v1은 Management API v3와 비슷한 일련의 Google 애널리틱스 계정 및 속성 관리 메서드를 제공합니다. 또한 Admin API v1에는 Google 애널리틱스 계정을 프로비저닝, 삭제, 업데이트하는 기능이 도입되었습니다.

  • Admin API v1 속성 관리 메서드는 Google 애널리틱스 4 속성만 지원합니다.

  • Admin API v1에는 보기(프로필) 개념이 없습니다.

  • Google 애널리틱스 4에 데이터 스트림이 도입되었으므로, 특정 정보는 더 이상 속성 수준에서 존재하지 않습니다. 예를 들어 이제 websiteUrl 필드는 속성 개체의 일부가 아니라 DataStream 항목에 표시됩니다.

계정 요약 나열

Admin API의 accountSummaries 메서드Management API v3의 accountSummaries 메서드와 마찬가지로, 호출자가 액세스할 수 있는 모든 계정의 간단한 요약을 반환합니다.

중요한 차이점은 Admin API v1은 Google 애널리틱스 4 속성에 관한 정보만 반환하지만, Management API v3 응답은 유니버설 애널리틱스로 생성된 속성에 대한 데이터를 포함한다는 점입니다. 단일 호출을 사용하여 두 가지 유형의 속성에 대한 정보를 모두 검색할 수는 없습니다.

Google 애널리틱스 4에는 보기(프로필)가 없으므로 Admin API에서 반환하는 계정 요약에는 보기(프로필) 정보가 포함되지 않습니다.

Google 애널리틱스 4 계정 요약 데이터는 현재 사용자가 사용할 수 있는 계정/속성의 리소스 및 표시 이름으로 제한됩니다.

account.getproperty.get 메서드를 호출하여 전체 구성 데이터를 검색할 수 있도록 요약 응답의 account, property 필드에서 반환된 리소스 이름을 사용합니다.

Admin API v1 요청

GET https://analyticsadmin.googleapis.com/v1beta/accountSummaries?key=[YOUR_API_KEY]

Admin API v1 응답

{
  "accountSummaries": [
    {
      "name": "accountSummaries/XXXXXX",
      "account": "accounts/XXXXXX",
      "displayName": "Test",
      "propertySummaries": [
        {
          "property": "properties/XXXXXX",
          "displayName": "Test App"
        }
      ]
    },
    ...
}

Management API v3 요청

GET https://analytics.googleapis.com/analytics/v3/management/accountSummaries?key=[YOUR_API_KEY]

Management API v3 응답

{
  "kind": "analytics#accountSummaries",
  "username": "XXXXXX",
  "totalResults": 9,
  "startIndex": 1,
  "itemsPerPage": 1000,
  "items": [
    {
      "id": "XXXXXX",
      "kind": "analytics#accountSummary",
      "name": "Test Account",
      "webProperties": [
        {
          "kind": "analytics#webPropertySummary",
          "id": "UA-XXXXXX",
          "name": "Test Property",
          "internalWebPropertyId": "XXXXXX",
          "level": "STANDARD",
          "websiteUrl": "XXXXXX",
          "profiles": [
            {
              "kind": "analytics#profileSummary",
              "id": "XXXXXX",
              "name": "Test Profile",
              "type": "WEB"
            }
          ]
        },
        ...
}

클라이언트 라이브러리를 사용하여 Admin API v1을 호출하기 위한 샘플 코드는 다음과 같습니다.

Python

from google.analytics.admin import AnalyticsAdminServiceClient


def list_account_summaries(transport: str = None) -> None:
    """
    Prints summaries of all accounts accessible by the caller.

    Args:
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    client = AnalyticsAdminServiceClient(transport=transport)
    results = client.list_account_summaries()

    print("Result:")
    for account_summary in results:
        print("-- Account --")
        print(f"Resource name: {account_summary.name}")
        print(f"Account name: {account_summary.account}")
        print(f"Display name: {account_summary.display_name}")
        print()
        for property_summary in account_summary.property_summaries:
            print("-- Property --")
            print(f"Property resource name: {property_summary.property}")
            print(f"Property display name: {property_summary.display_name}")
            print()


계정 나열

Admin API v1의 accounts.list 메서드Management API v3의 accounts.list 메서드와 마찬가지로, 호출자가 액세스할 수 있는 모든 계정을 반환합니다.

Admin API v1 요청

GET https://analyticsadmin.googleapis.com/v1beta/accounts?key=[YOUR_API_KEY]

Admin API v1 응답

{
  "accounts": [
    {
      "name": "accounts/XXXXXX",
      "createTime": "2020-02-21T00:17:33.282Z",
      "updateTime": "2021-01-07T02:47:57.386Z",
      "displayName": "Test Account",
      "regionCode": "US"
    },
  ...
}

Management API v3 요청

GET https://analytics.googleapis.com/analytics/v3/management/accounts?key=[YOUR_API_KEY]

Management API v3 응답

{
  "kind": "analytics#accounts",
  "username": "XXXXXX",
  "totalResults": 9,
  "startIndex": 1,
  "itemsPerPage": 1000,
  "items": [
    {
      "id": "XXXXXX",
      "kind": "analytics#account",
      "selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX",
      "name": "Test Account",
      "permissions": {
        "effective": [
          "COLLABORATE",
          "EDIT",
          "READ_AND_ANALYZE"
        ]
      },
      "created": "2020-02-21T00:17:33.282Z",
      "updated": "2021-01-07T02:47:57.386Z",
      "childLink": {
        "type": "analytics#webproperties",
        "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties"
      }
    },
    ...
}

Admin API v1 응답에는 효과적인 사용자 권한도 Management API v3에 있던 childLink 필드에 대한 정보도 포함되지 않습니다.

클라이언트 라이브러리를 사용하여 Admin API v1을 호출하기 위한 샘플 코드는 다음과 같습니다.

Python

from google.analytics.admin import AnalyticsAdminServiceClient

from accounts_get import print_account


def list_accounts(transport: str = None):
    """
    Lists the Google Analytics accounts available to the current user.

    Args:
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    client = AnalyticsAdminServiceClient(transport=transport)
    results = client.list_accounts()

    print("Result:")
    for account in results:
        print_account(account)


속성 관리

속성 나열

Admin API v1의 properties.list 메서드는 액세스 가능한 모든 유니버설 애널리틱스 속성을 반환하는 Management API v3의 webproperties.list 메서드와 마찬가지로, 호출자가 액세스할 수 있는 모든 Google 애널리틱스 4 속성을 반환합니다.

Google 애널리틱스 4의 속성 수준에서 websiteUrl 필드가 더 이상 존재하지 않으므로 properties.dataStreams/list를 사용하여 속성과 연결된 모든 데이터 스트림을 나열하고 defaultUri 필드를 조회하여 스트림과 연결된 웹사이트 URL을 검색합니다.

properties.list 요청의 URL에서 filter 매개변수를 확인합니다. 매개변수 값에는 요청 결과를 필터링하기 위한 표현식이 포함되며, 지정된 Google 애널리틱스 계정 ID 또는 연결된 Firebase 프로젝트와 연결된 속성을 나열하는 데 사용할 수 있습니다.

Admin API v1 요청

GET https://analyticsadmin.googleapis.com/v1beta/properties?filter=parent:accounts/XXXXXX&key=[YOUR_API_KEY]

Admin API v1 응답

{
  "properties": [
    {
      "name": "properties/XXXXXX",
      "parent": "accounts/XXXXXX",
      "createTime": "2020-10-29T04:02:49.124Z",
      "updateTime": "2020-10-29T04:02:49.124Z",
      "displayName": "Test Property",
      "timeZone": "America/Los_Angeles",
      "currencyCode": "USD"
    },
    ...
}

Management API v3 요청

GET https://analytics.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties?key=[YOUR_API_KEY]

Management API v3 응답

{
  "kind": "analytics#webproperties",
  "username": "XXXXXX",
  "totalResults": 33,
  "startIndex": 1,
  "itemsPerPage": 1000,
  "items": [
    {
      "id": "UA-XXXXXX-1",
      "kind": "analytics#webproperty",
      "selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties/UA-XXXXXX-1",
      "accountId": "XXXXXX",
      "internalWebPropertyId": "XXXXXX",
      "name": "Test Account",
      "websiteUrl": "XXXXXX",
      "level": "PREMIUM",
      "profileCount": 4,
      "industryVertical": "HEALTH",
      "defaultProfileId": "XXXXXX",
      "dataRetentionTtl": "INDEFINITE",
      "dataRetentionResetOnNewActivity": true,
      "permissions": {
        "effective": [
          "COLLABORATE",
          "EDIT",
          "READ_AND_ANALYZE"
        ]
      },
      "created": "2020-02-21T00:28:47.287Z",
      "updated": "2021-01-27T21:39:22.704Z",
      "parentLink": {
        "type": "analytics#account",
        "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX"
      },
      "childLink": {
        "type": "analytics#profiles",
        "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties/UA-XXXXXX-1/profiles"
      }
    },
    ...
}

클라이언트 라이브러리를 사용하여 Admin API v1을 호출하기 위한 샘플 코드는 다음과 같습니다.

Python

from google.analytics.admin import AnalyticsAdminServiceClient
from google.analytics.admin_v1alpha.types import ListPropertiesRequest


def run_sample():
    """Runs the sample."""
    # TODO(developer): Replace this variable with your Google Analytics
    #  account ID (e.g. "123456") before running the sample.
    account_id = "YOUR-GA-ACCOUNT-ID"
    list_properties(account_id)


def list_properties(account_id: str, transport: str = None):
    """
    Lists Google Analytics 4 properties under the specified parent account
    that are available to the current user.

    Args:
        account_id(str): The Google Analytics account ID.
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    client = AnalyticsAdminServiceClient(transport=transport)
    results = client.list_properties(
        ListPropertiesRequest(filter=f"parent:accounts/{account_id}", show_deleted=True)
    )

    print("Result:")
    for property_ in results:
        print(property_)
        print()


속성 가져오기

Admin API v1의 properties.get 메서드Management API v3의 webproperties.get 메서드와 마찬가지로, Google 애널리틱스 4 속성에 대한 정보를 반환합니다.

Admin API의 properties.get 메서드는 Google 애널리틱스 4 속성만 지원합니다.

Admin API v1 요청

GET https://analyticsadmin.googleapis.com/v1beta/properties/XXXXXX?key=[YOUR_API_KEY]

Admin API v1 응답

{
  "name": "properties/XXXXXX",
  "parent": "accounts/XXXXXX",
  "createTime": "2021-04-30T21:32:49.804Z",
  "updateTime": "2021-04-30T21:32:49.804Z",
  "displayName": "Test Property",
  "industryCategory": "FINANCE",
  "timeZone": "America/Los_Angeles",
  "currencyCode": "USD"
}

Management API v3 요청

GET https://analytics.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties/UA-XXXXXX-3?key=[YOUR_API_KEY]

Management API v3 응답

{
  "id": "UA-XXXXXX-3",
  "kind": "analytics#webproperty",
  "selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties/UA-XXXXXX-3",
  "accountId": "XXXXXX",
  "internalWebPropertyId": "XXXXXX",
  "name": "Test 2",
  "websiteUrl": "YOUR-WEBSITE-URL",
  "level": "STANDARD",
  "profileCount": 0,
  "industryVertical": "FINANCE",
  "dataRetentionTtl": "MONTHS_26",
  "dataRetentionResetOnNewActivity": true,
  "permissions": {
    "effective": [
      "COLLABORATE",
      "EDIT",
      "MANAGE_USERS",
      "READ_AND_ANALYZE"
    ]
  },
  "created": "2021-05-20T05:35:51.985Z",
  "updated": "2021-05-20T05:41:39.219Z",
  "parentLink": {
    "type": "analytics#account",
    "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX"
  },
  "childLink": {
    "type": "analytics#profiles",
    "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties/UA-XXXXXX-3/profiles"
  }
}

클라이언트 라이브러리를 사용하여 Admin API v1을 호출하기 위한 샘플 코드는 다음과 같습니다.

Python

from google.analytics.admin import AnalyticsAdminServiceClient
from google.analytics.admin_v1alpha.types import IndustryCategory


def run_sample():
    """Runs the sample."""
    # TODO(developer): Replace this variable with your Google Analytics 4
    #  property ID (e.g. "123456") before running the sample.
    property_id = "YOUR-GA4-PROPERTY-ID"
    get_property(property_id)


def get_property(property_id: str, transport: str = None):
    """
    Retrieves the Google Analytics 4 property details.

    Args:
        property_id(str): The Google Analytics Property ID.
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    client = AnalyticsAdminServiceClient(transport=transport)
    property_ = client.get_property(name=f"properties/{property_id}")

    print("Result:")
    print_property(property_)


def print_property(property):
    """Prints the Google Analytics 4 property details."""
    print(f"Resource name: {property.name}")
    print(f"Parent: {property.parent}")
    print(f"Display name: {property.display_name}")
    print(f"Create time: {property.create_time}")
    print(f"Update time: {property.update_time}")
    # print(f"Delete time: {property.delete_time}")
    # print(f"Expire time: {property.expire_time}")

    if property.industry_category:
        print(f"Industry category: {IndustryCategory(property.industry_category).name}")

    print(f"Time zone: {property.time_zone}")
    print(f"Currency code: {property.currency_code}")


속성 만들기

Admin API v1의 properties.create 메서드Management API v3의 webproperties.insert 메서드와 마찬가지로, 새 Google 애널리틱스 4 속성을 만듭니다.

Admin API v1 요청

POST https://analyticsadmin.googleapis.com/v1beta/properties?key=[YOUR_API_KEY]

{
  "displayName": "Test Property",
  "industryCategory": "AUTOMOTIVE",
  "currencyCode": "USD",
  "timeZone": "America/Los_Angeles",
  "parent": "accounts/XXXXXX"
}

Admin API v1 응답

{
  "name": "properties/XXXXXX",
  "parent": "accounts/XXXXXX",
  "createTime": "2021-05-20T09:16:08.458Z",
  "updateTime": "2021-05-20T09:16:08.458Z",
  "displayName": "Test Property",
  "industryCategory": "AUTOMOTIVE",
  "timeZone": "America/Los_Angeles",
  "currencyCode": "USD"
}

Management API v3 요청

POST https://analytics.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties?key=[YOUR_API_KEY]

{
  "name": "Test",
  "websiteUrl": "YOUR-WEBSITE-URL"
}

Management API v3 응답

{
  "id": "UA-XXXXXX-3",
  "kind": "analytics#webproperty",
  "selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties/UA-XXXXXX-3",
  "accountId": "XXXXXX",
  "internalWebPropertyId": "XXXXXX",
  "name": "Test",
  "websiteUrl": "YOUR-WEBSITE-URL",
  "level": "STANDARD",
  "profileCount": 0,
  "dataRetentionTtl": "MONTHS_26",
  "dataRetentionResetOnNewActivity": true,
  "permissions": {
    "effective": [
      "COLLABORATE",
      "EDIT",
      "MANAGE_USERS",
      "READ_AND_ANALYZE"
    ]
  },
  "created": "2021-05-20T05:35:51.985Z",
  "updated": "2021-05-20T05:35:51.985Z",
  "parentLink": {
    "type": "analytics#account",
    "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX"
  },
  "childLink": {
    "type": "analytics#profiles",
    "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties/UA-XXXXXX-3/profiles"
  }
}

클라이언트 라이브러리를 사용하여 Admin API v1을 호출하기 위한 샘플 코드는 다음과 같습니다.

Python

from google.analytics.admin import AnalyticsAdminServiceClient
from google.analytics.admin_v1alpha.types import Property


def run_sample():
    """Runs the sample."""

    # !!! ATTENTION !!!
    #  Running this sample may change/delete your Google Analytics account
    #  configuration. Make sure to not use the Google Analytics account ID from
    #  your production environment below.

    # TODO(developer): Replace this variable with your Google Analytics
    #  account ID (e.g. "123456") before running the sample.
    account_id = "YOUR-GA-ACCOUNT-ID"
    create_property(account_id)


def create_property(account_id: str, transport: str = None):
    """
    Creates a Google Analytics 4 property.

    Args:
        account_id(str): The Google Analytics Account ID.
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    client = AnalyticsAdminServiceClient(transport=transport)
    property_ = client.create_property(
        property=Property(
            parent=f"accounts/{account_id}",
            currency_code="USD",
            display_name="Test property",
            industry_category="OTHER",
            time_zone="America/Los_Angeles",
        )
    )

    print("Result:")
    print(property_)


속성 업데이트/패치

Admin API v1의 properties.patch 메서드Management API v3의 webproperties.patch 메서드와 마찬가지로, Google 애널리틱스 4 속성의 구성을 업데이트합니다.

쉼표로 구분된 업데이트 대상 필드 목록이 포함된 요청의 URL에서 updateMask 매개변수를 확인합니다. 이 목록에 없는 필드는 업데이트되지 않습니다. 클라이언트 라이브러리를 사용하는 경우, 메서드 서명의 일부로 update_mask 매개변수를 사용할 수 있습니다.

Admin API v1 요청

PATCH https://analyticsadmin.googleapis.com/v1beta/properties/XXXXXX?updateMask=displayName,industryCategory&key=[YOUR_API_KEY]

{
  "displayName": "New Property Name",
  "industryCategory": "FINANCE"
}

Admin API v1 응답

{
  "name": "properties/XXXXXX",
  "parent": "accounts/XXXXXX",
  "createTime": "2021-04-30T21:32:49.804Z",
  "updateTime": "2021-05-20T09:25:14.810Z",
  "displayName": "New Property Name",
  "industryCategory": "FINANCE",
  "timeZone": "America/Los_Angeles",
  "currencyCode": "USD"
}

Management API v3 요청

PATCH https://analytics.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties/UA-XXXXXX-3?key=[YOUR_API_KEY]

{
  "name": "New Property Name",
  "industryVertical": "FINANCE"
}

Management API v3 응답

{
  "id": "UA-XXXXXX-3",
  "kind": "analytics#webproperty",
  "selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties/UA-XXXXXX-3",
  "accountId": "XXXXXX",
  "internalWebPropertyId": "XXXXXX",
  "name": "New Property Name",
  "websiteUrl": "XXXXXX",
  "level": "STANDARD",
  "profileCount": 0,
  "industryVertical": "FINANCE",
  "dataRetentionTtl": "MONTHS_26",
  "dataRetentionResetOnNewActivity": true,
  "permissions": {
    "effective": [
      "COLLABORATE",
      "EDIT",
      "MANAGE_USERS",
      "READ_AND_ANALYZE"
    ]
  },
  "created": "2021-05-20T05:35:51.985Z",
  "updated": "2021-05-20T05:41:39.219Z",
  "parentLink": {
    "type": "analytics#account",
    "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX"
  },
  "childLink": {
    "type": "analytics#profiles",
    "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/webproperties/UA-XXXXXX-3/profiles"
  }
}

클라이언트 라이브러리를 사용하여 Admin API v1을 호출하기 위한 샘플 코드는 다음과 같습니다.

Python

from google.analytics.admin import AnalyticsAdminServiceClient
from google.analytics.admin_v1alpha.types import Property
from google.protobuf.field_mask_pb2 import FieldMask


def run_sample():
    """Runs the sample."""

    # !!! ATTENTION !!!
    #  Running this sample may change/delete your Google Analytics account
    #  configuration. Make sure to not use the Google Analytics property ID from
    #  your production environment below.

    # TODO(developer): Replace this variable with your Google Analytics 4
    #  property ID (e.g. "123456") before running the sample.
    property_id = "YOUR-GA4-PROPERTY-ID"
    update_property(property_id)


def update_property(property_id: str, transport: str = None):
    """
    Updates the Google Analytics 4 property.

    Args:
        property_id(str): The Google Analytics Property ID.
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    client = AnalyticsAdminServiceClient(transport=transport)
    # This call updates the display name, industry category and time zone of the
    # property, as indicated by the value of the `update_mask` field.
    # The property to update is specified in the `name` field of the `Property`
    # instance.
    property_ = client.update_property(
        property=Property(
            name=f"properties/{property_id}",
            display_name="This is an updated test property",
            industry_category="GAMES",
            time_zone="America/New_York",
        ),
        update_mask=FieldMask(paths=["display_name", "time_zone", "industry_category"]),
    )

    print("Result:")
    print(property_)


사용자 관리

Google 애널리틱스 Admin API는 현재 Management API v3와 유사한 사용자 권한 모델을 구현하지만 몇 가지 차이점이 있습니다.

  1. Management API v3에서는 AccountUserLink, WebPropertyUserLink, ProfileUserLink 리소스 대신 계정 AccessBinding속성 AccessBinding 리소스를 사용하여 Google 애널리틱스 Admin API로 사용자 권한을 관리합니다.
  2. Google Analytics Admin API의 속성 액세스 바인딩에는 계정 액세스 바인딩에서 상속된 묵시적 권한 또는 권한이 포함되지 않습니다. Management API v3에서는 각 사용자 링크에 암시적 권한과 상속된 권한이 모두 포함된 permissions.effective 컬렉션이 포함되었습니다.

AccessBinding 항목에는 사용자 (이메일 주소)와 사용자에게 부여된 역할 목록이 포함됩니다. AccessBinding 항목을 생성, 업데이트 또는 삭제할 수 있습니다.

Admin API v1 역할 이름과 Management API v3 권한 이름 간의 매핑은 다음과 같습니다.

Admin API v1 역할 Management API v3 권한 이름
사전 정의된 역할/뷰어 READ_AND_ANALYZE
사전 정의된 역할/분석가 COLLABORATE
사전 정의된 역할/편집자 수정
사전 정의된 역할/관리자 MANAGE_USERS

역할 predefinedRoles/no-cost-data, predefinedRoles/no-revenue-data는 Admin API v1에 도입되었으며 Management API v3에는 상응하는 매핑이 없습니다.

이 가이드에서는 계정 수준 액세스 결합을 관리하는 방법을 보여줍니다. 속성 수준 액세스 결합을 관리하려면 동일한 프로세스를 따르되 계정 AccessBinding 대신 속성 AccessBinding 리소스와 메서드를 사용하세요.

계정 액세스 결합 나열

Admin API v1의 accounts.accessBindings.list 메서드Management API v3의 accountUserLinks.list 메서드와 마찬가지로, 계정의 모든 액세스 바인딩을 나열합니다.

Admin API v1 요청

GET https://analyticsadmin.googleapis.com/v1alpha/accounts/XXXXXX/accessBindings/XXXXXXXX

Admin API v1 응답

{
  "accessBindings": [
    {
      "name": "accounts/XXXXXX/accessBindings/XXXXXX",
      "user": "XXXXXX",
      "roles": [
        "predefinedRoles/editor",
        "predefinedRoles/admin"
      ]
    }
  ]
}

Management API v3 요청

GET https://analytics.googleapis.com/analytics/v3/management/accounts/XXXXXX/entityUserLinks?key=[YOUR_API_KEY]

Management API v3 응답

{
  "kind": "analytics#entityUserLinks",
  "totalResults": 1,
  "startIndex": 1,
  "itemsPerPage": 1000,
  "items": [
    {
      "id": "XXXXXX:XXXXXX",
      "kind": "analytics#entityUserLink",
      "selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/entityUserLinks/XXXXXX:XXXXXX",
      "entity": {
        "accountRef": {
          "id": "XXXXXX",
          "kind": "analytics#accountRef",
          "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX",
          "name": "This is a test account"
        }
      },
      "userRef": {
        "kind": "analytics#userRef",
        "id": "XXXXXX",
        "email": "XXXXXX"
      },
      "permissions": {
        "effective": [
          "COLLABORATE",
          "EDIT",
          "MANAGE_USERS",
          "READ_AND_ANALYZE"
        ],
        "local": [
          "EDIT",
          "MANAGE_USERS"
        ]
      }
    }
  ]
}

클라이언트 라이브러리를 사용하여 Admin API를 호출하는 샘플 코드:

Python

from google.analytics.admin import AnalyticsAdminServiceClient


def run_sample():
    """Runs the sample."""
    # TODO(developer): Replace this variable with your Google Analytics
    #  account ID (e.g. "123456") before running the sample.
    account_id = "YOUR-GA-ACCOUNT-ID"
    list_account_access_bindings(account_id)


def list_account_access_bindings(account_id: str, transport: str = None):
    """
    Lists access bindings under the specified parent account.

    Args:
        account_id(str): The id of the account.
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    client = AnalyticsAdminServiceClient(transport=transport)
    results = client.list_access_bindings(parent=f"accounts/{account_id}")

    print("Result:")
    for access_binding in results:
        print(access_binding)
        print()


계정 액세스 결합 업데이트

Admin API v1의 accounts.accessBindings.patch 메서드Management API v3의 accountUserLinks.update 메서드와 마찬가지로, 계정의 액세스 바인딩을 업데이트합니다.

Admin API v1 요청

PATCH https://analyticsadmin.googleapis.com/v1alpha/accounts/XXXXXX/accessBindings/XXXXXXXX

{
  "roles": [
    "predefinedRoles/editor",
    "predefinedRoles/admin"
  ]
}

Admin API v1 응답

{
  "name": "accounts/XXXXXX/accessBindings/XXXXXXXX",
  "user": "USER-EMAIL",
  "directRoles": [
    "predefinedRoles/editor",
    "predefinedRoles/admin"
  ]
}

Management API v3 요청

PUT https://analytics.googleapis.com/analytics/v3/management/accounts/XXXXXX/entityUserLinks/XXXXXX%3A104236685715552897132?key=[YOUR_API_KEY]

{
  "entity": {
    "accountRef": {
      "id": "XXXXXX"
    }
  },
  "userRef": {
    "email": "XXXXXX"
  },
  "permissions": {
    "local": [
      "EDIT",
      "MANAGE_USERS"
    ]
  }
}

Management API v3 응답

{
  "id": "XXXXXX:104236685715552897132",
  "kind": "analytics#entityUserLink",
  "selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/entityUserLinks/XXXXXX:104236685715552897132",
  "entity": {
    "accountRef": {
      "id": "XXXXXX",
      "kind": "analytics#accountRef",
      "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX",
      "name": "This is a test account"
    }
  },
  "userRef": {
    "kind": "analytics#userRef",
    "id": "104236685715552897132",
    "email": "XXXXXX"
  },
  "permissions": {
    "effective": [
      "COLLABORATE",
      "EDIT",
      "MANAGE_USERS",
      "READ_AND_ANALYZE"
    ],
    "local": [
      "EDIT",
      "MANAGE_USERS"
    ]
  }
}

클라이언트 라이브러리를 사용하여 Admin API v1을 호출하기 위한 샘플 코드는 다음과 같습니다.

Python

from google.analytics.admin import AnalyticsAdminServiceClient
from google.analytics.admin_v1alpha.types import AccessBinding


def run_sample():
    """Runs the sample."""

    # !!! ATTENTION !!!
    #  Running this sample may change/delete your Google Analytics account
    #  configuration. Make sure to not use the Google Analytics property ID from
    #  your production environment below.

    # TODO(developer): Replace this variable with your Google Analytics
    #  account ID (e.g. "123456") before running the sample.
    account_id = "YOUR-GA-ACCOUNT-ID"

    # TODO(developer): Replace this variable with your Google Analytics
    #  account access binding ID (e.g. "123456") before running the sample.
    account_access_binding_id = "YOUR-ACCOUNT-ACCESS-BINDING-ID"

    update_account_access_binding(account_id, account_access_binding_id)


def update_account_access_binding(
    account_id: str, account_access_binding_id: str, transport: str = None
):
    """
    Updates the account access binding.

    Args:
        account_id(str): The Google Analytics Account ID.
        account_access_binding_id(str): Google Analytics account access binding ID.
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    client = AnalyticsAdminServiceClient(transport=transport)
    # This call updates the roles of the access binding. The access binding to
    # update is specified in the `name` field of the `AccessBinding` instance.
    access_binding = client.update_access_binding(
        access_binding=AccessBinding(
            name=f"accounts/{account_id}/accessBindings/{account_access_binding_id}",
            roles=["predefinedRoles/collaborate"],
        ),
    )

    print("Result:")
    print(access_binding)


계정 액세스 결합 만들기

Admin API v1의 accounts.accessBindings.create 메서드Management API v3의 accountUserLinks.insert 메서드와 마찬가지로, 계정에 액세스 바인딩을 만듭니다.

Admin API v1 요청

POST https://analyticsadmin.googleapis.com/v1alpha/accounts/XXXXXX/accessBindings

{
  "roles": [
    "predefinedRoles/editor",
    "predefinedRoles/admin"
  ],
  "user": "USER-EMAIL"
}

Admin API v1 응답

{
  "name": "accounts/XXXXXX/accessBindings/XXXXXXXX",
  "user": "USER-EMAIL",
  "roles": [
    "predefinedRoles/editor",
    "predefinedRoles/admin"
  ]
}

Management API v3 요청

POST https://analytics.googleapis.com/analytics/v3/management/accounts/XXXXXX/entityUserLinks?key=[YOUR_API_KEY]

{
  "entity": {
    "accountRef": {
      "id": "XXXXXX"
    }
  },
  "userRef": {
    "email": "XXXXXX"
  },
  "permissions": {
    "local": [
      "EDIT",
      "MANAGE_USERS"
    ]
  }
}

Management API v3 응답

{
  "id": "XXXXXX:114236685715552897132",
  "kind": "analytics#entityUserLink",
  "selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX/entityUserLinks/XXXXXX:114236685715552897132",
  "entity": {
    "accountRef": {
      "id": "XXXXXX",
      "kind": "analytics#accountRef",
      "href": "https://www.googleapis.com/analytics/v3/management/accounts/XXXXXX",
      "name": "This is a test account"
    }
  },
  "userRef": {
    "kind": "analytics#userRef",
    "id": "114236685715552897132",
    "email": "XXXXXX"
  },
  "permissions": {
    "effective": [
      "COLLABORATE",
      "EDIT",
      "MANAGE_USERS",
      "READ_AND_ANALYZE"
    ],
    "local": [
      "EDIT",
      "MANAGE_USERS"
    ]
  }
}

클라이언트 라이브러리를 사용하여 Admin API v1을 호출하기 위한 샘플 코드는 다음과 같습니다.

Python

from google.analytics.admin import AnalyticsAdminServiceClient
from google.analytics.admin_v1alpha.types import (
    AccessBinding,
    CreateAccessBindingRequest,
)


def run_sample():
    """Runs the sample."""

    # !!! ATTENTION !!!
    #  Running this sample may change/delete your Google Analytics account
    #  configuration. Make sure to not use the Google Analytics account ID from
    #  your production environment below.

    # TODO(developer): Replace this variable with your Google Analytics
    #  account ID (e.g. "123456") before running the sample.
    account_id = "YOUR-GA-ACCOUNT-ID"

    # TODO(developer): Replace this variable with an email address of the user to
    #  link. This user will be given access to your account after running the
    #  sample.
    email_address = "TEST-EMAIL-ADDRESS"

    create_account_access_binding(account_id, email_address)


def create_account_access_binding(
    account_id: str, email_address: str, transport: str = None
):
    """
    Creates a access binding for the account.

    Args:
        account_id(str): The Google Analytics Account ID.
        email_address(str): Email address of the access binding user.
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    client = AnalyticsAdminServiceClient(transport=transport)
    access_binding = client.create_access_binding(
        CreateAccessBindingRequest(
            parent=f"accounts/{account_id}",
            access_binding=AccessBinding(
                user=email_address, roles=["predefinedRoles/read"]
            ),
        )
    )

    print("Result:")
    print(access_binding)


일괄 처리

Admin API v1은 Management API v3와 달리, 멀티파트/혼합 콘텐츠를 통한 여러 Google 애널리틱스 API 호출의 일괄 처리를 지원하지 않습니다.

대신 API 수준에서는 일괄 처리가 명시적으로 지원됩니다. Admin API v1의 다음 메서드는 일괄 처리 기능을 지원합니다.

클라이언트 라이브러리를 사용하여 Admin API v1을 호출하기 위한 샘플 코드는 다음과 같습니다.

Python

from google.analytics.admin import AnalyticsAdminServiceClient
from google.analytics.admin_v1alpha.types import (
    AccessBinding,
    BatchCreateAccessBindingsRequest,
    CreateAccessBindingRequest,
)


def run_sample():
    """Runs the sample."""

    # !!! ATTENTION !!!
    #  Running this sample may change/delete your Google Analytics account
    #  configuration. Make sure to not use the Google Analytics account ID from
    #  your production environment below.

    # TODO(developer): Replace this variable with your Google Analytics
    #  account ID (e.g. "123456") before running the sample.
    account_id = "YOUR-GA-ACCOUNT-ID"

    # TODO(developer): Replace this variable with an email address of the user to
    #  link. This user will be given access to your account after running the
    #  sample.
    email_address = "TEST-EMAIL-ADDRESS"

    batch_create_account_access_binding(account_id, email_address)


def batch_create_account_access_binding(
    account_id: str, email_address: str, transport: str = None
):
    """
    Creates a access binding for the account using a batch call.

    Args:
        account_id(str): The Google Analytics Account ID.
        email_address(str): Email address of the access binding user.
        transport(str): The transport to use. For example, "grpc"
            or "rest". If set to None, a transport is chosen automatically.
    """
    client = AnalyticsAdminServiceClient(transport=transport)
    response = client.batch_create_access_bindings(
        BatchCreateAccessBindingsRequest(
            parent=f"accounts/{account_id}",
            requests=[
                CreateAccessBindingRequest(
                    access_binding=AccessBinding(
                        user=email_address,
                        roles=["predefinedRoles/read"],
                    )
                )
            ],
        )
    )

    print("Result:")
    for access_binding in response.access_bindings:
        print(access_binding)
        print()


API 할당량 변경사항

Admin API v1에서는 Management API v3에 비해 덜 제한적인 할당량을 사용합니다.

  • Admin API v1에 대한 요청 수는 GCP 프로젝트에서 기본적으로 분당 요청 600개로 제한됩니다.
  • 현재 GCP 프로젝트당 Admin API v1 호출 수에는 일일 한도 할당량이 없습니다. 이론적으로 가능한 일일 최대 요청 수는 분당 요청 할당량으로 제한됩니다.
  • 일일 쓰기 작업 수에 대한 별도 제한은 없어졌습니다.