遷移至 Google Analytics Admin API v1

API 的 Alpha 版和 Beta 版仍持續受到支援。Beta 版包含 Alpha 版提供的部分功能,屬於穩定版,預計未來不會發生重大變更。待新功能達到測試限制後,我們就會在 Beta 版中新增功能。

本文說明如何將現有程式碼從 Google Analytics Management API v3 遷移至 Google Analytics Admin API v1,並提供這兩種 API 主要差異的簡要說明。

為何需要遷移?

如果應用程式需要建立或設定 Google Analytics (分析) 4 資源,則必須使用 Admin API v1。Management API v3 僅適用於通用 Analytics (分析) 資源,Admin API v1 則僅適用於 Google Analytics (分析) 4 資源。

必備條件

建議您詳閱快速入門指南,熟悉 Admin API v1 的基本概念。

開始探索

首先,您需要準備 Google Analytics (分析) 4 資源、啟用 Admin API v1,然後設定適用於您平台的 API 用戶端程式庫。

準備 Google Analytics (分析) 4 資源

遷移程式碼以支援 Admin API v1 之前,請先遷移網站以使用 Google Analytics (分析) 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 = AlphaAnalyticsAdminClient()

.NET

AlphaAnalyticsAdminClient client = AlphaAnalyticsAdminClient.Create();

PHP

$client = new AlphaAnalyticsAdminClient();

Node.js

  // Imports the Google Analytics Data API client library.
  const {AlphaAnalyticsAdminClient} = 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 AlphaAnalyticsAdminClient();

除了使用環境變數以外,您也可以在初始化期間明確將憑證資訊傳送至 API 用戶端執行個體。

如果您沒有使用用戶端程式庫

如果您在沒有用戶端程式庫的情況下使用 Management API v3,而且想繼續透過 Admin API v1 執行此操作,您仍然可以使用您的憑證。

您必須使用 Admin API 提供的新 HTTP 端點和探索文件:

如果您的程式碼使用探索文件,必須將文件更新為 Admin API v1 提供的探索文件:

更新端點後,您必須熟悉新的要求結構和 Admin API 的概念,才能更新 JSON 查詢。

一般工作

管理帳戶

Admin API 第 1 版提供了一組 Google Analytics (分析) 帳戶和資源管理方式,相當於 Management API v3。此外,Admin API v1 推出了佈建刪除更新 Google Analytics (分析) 帳戶的功能。

  • Admin API v1 資源管理方法僅支援 Google Analytics (分析) 4 資源。

  • Admin API v1 中不含檢視畫面 (設定檔) 的概念。

  • 由於 Google Analytics (分析) 4 導入資料串流,因此資源層級不再顯示某些資訊。舉例來說,websiteUrl 欄位現在會顯示在 DataStream 實體中,而非屬於屬性物件的一部分。

列出帳戶摘要

Admin API 的 accountSummaries 方法會傳回呼叫端可存取的所有帳戶的輕量摘要,類似於 Management API 第 3 版的 accountSummaries 方法

重要的差別在於 Admin API v1 只會傳回 Google Analytics (分析) 4 資源的相關資訊, Management API v3 回應則包含使用通用 Analytics (分析) 建立的資源相關資料。您無法透過一次呼叫來擷取這兩種屬性的資訊。

由於 Google Analytics (分析) 4 中沒有資料檢視 (設定檔),因此 Admin API 傳回的帳戶摘要不包含資料檢視 (設定檔) 資訊。

Google Analytics (分析) 4 帳戶摘要資料僅限於目前使用者可用的帳戶/資源資源和顯示名稱。

使用摘要回應的 accountproperty 欄位傳回的資源名稱,透過呼叫 account.getproperty.get 方法擷取完整的設定資料。

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 第 3 版的 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 方法會傳回呼叫端可存取的所有 Google Analytics (分析) 4 資源,類似 Management API v3 的 webproperties.list 方法,可傳回所有可存取的通用 Analytics (分析) 資源。

由於 Google Analytics (分析) 4 的資源層級不再顯示 websiteUrl 欄位,請使用 properties.dataStreams/list 列出與資源相關聯的所有資料串流,並查詢 defaultUri 欄位,擷取與串流相關聯的網站網址。

請記下 properties.list 要求網址中的 filter 參數。參數值包含用來篩選要求結果的運算式,並可用來列出與指定 Google Analytics (分析) 帳戶 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 方法會傳回 Google Analytics (分析) 4 資源的相關資訊,類似 Management API v3 的 webproperties.get 方法

請注意,Admin API 的 properties.get 方法僅支援 Google Analytics (分析) 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 方法會建立新的 Google Analytics (分析) 4 資源,類似 Management API v3 的 webproperties.insert 方法

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 方法會更新 Google Analytics (分析) 4 資源的設定,類似 Management API v3 的 webproperties.patch 方法

請記下要求網址中的 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 Analytics Admin API 目前導入的使用者權限模型與 Management API v3 類似,但有些許差異。

  1. 您可以透過 Google Analytics Admin API 使用 帳戶 AccessBinding資源 AccessBinding 資源 (而非 Management API v3 中的 AccountUserLinkWebPropertyUserLinkProfileUserLink 資源) 管理使用者權限。
  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
預先定義的角色/分析師 合作拍片
預先定義角色/編輯者 編輯
預先定義的角色/管理員 MANAGE_USERS

predefinedRoles/no-cost-datapredefinedRoles/no-revenue-data 角色是在 Admin API v1 中導入,但在 Management API v3 中沒有對應的對應項目。

本指南說明如何管理帳戶層級的存取權繫結。如要管理資源層級存取權繫結,請按照相同程序操作,但請使用資源 AccessBinding 資源和方法取代帳戶 AccessBinding

列出帳戶存取權繫結

Admin API v1 的 accounts.accessBindings.list 方法會列出帳戶的所有存取權繫結,類似 Management API 第 3 版的 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 Analytics 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 配額變更

相較於 Management API v3,Admin API v1 提供的配額較少。

  • 根據預設,對 Admin API v1 發出的要求數預設為 GCP 專案每分鐘 600 個要求
  • 目前每項 GCP 專案的 Admin API v1 呼叫數量沒有每日上限。請注意,理論上的每日要求數量上限仍受到每分鐘要求配額的限制。
  • 我們移除了每日寫入作業次數的限制。