Google Analytics Admin API v1 に移行する

API のアルファ版チャンネルとベータ版チャンネルはどちらも引き続きサポートされます。Beta チャンネルには、アルファ版で利用できる機能のうち、安定版とみなされるため、今後大幅な変更が行われる予定ではないもののサブセットが含まれています。新機能は、完成後にベータ版に追加されます。

このドキュメントでは、既存のコードを Google アナリティクス Management API v3 から Google アナリティクス Admin API v1 に移行する方法と、これら 2 つの 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 プロパティを準備する

Google アナリティクス 4 プロパティを使用するようにウェブサイトを移行してから、Admin API v1 をサポートするようコードを移行する必要があります。

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 v1 では、Management API v3 に匹敵する、Google アナリティクスのアカウントとプロパティの管理メソッドの一式が提供されます。加えて、Admin API v1 には、Google アナリティクス アカウントのプロビジョニング削除更新の機能も導入されています。

  • Google アナリティクス 4 プロパティは、Admin API v1 プロパティの管理メソッドでのみサポートされています。

  • Admin API v1 には、ビュー(旧プロファイル)の概念が存在しません。

  • データ ストリームが Google アナリティクス 4 に導入されたため、特定の情報はプロパティ レベルで存在しなくなりました。たとえば、websiteUrl フィールドは、プロパティ オブジェクトの一部ではなく、DataStream エンティティ内に存在します。

アカウント概要のリスト

Management API v3 の accountSummaries メソッドと同様、Admin API の accountSummaries メソッドは、呼び出し元がアクセス可能なすべてのアカウントの軽量型概要を返します。

重要な違いは、Admin API v1 は Google アナリティクス 4 のプロパティに関する情報のみを返すのに対し、Management API v3 レスポンスにはユニバーサル アナリティクスで作成されたプロパティに関するデータが含まれているという点です。1 回の呼び出しで両方のタイプのプロパティに関する情報を取得することはできません。

Google アナリティクス 4 にはビュー(プロファイル)がないため、Admin API から返されるアカウントの概要にはビュー(プロファイル)情報は含まれません。

Google アナリティクス 4 アカウントの概要データは、現在のユーザーが使用できるアカウント / プロパティのリソース名と表示名に限定されています。

概要レスポンスの accountproperty フィールドに返されたリソース名を使用し、account.get メソッドと property.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()


アカウントの一覧表示

Management API v3 の accounts.list メソッドと同様、Admin API v1 の 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 アナリティクス 4 プロパティを返します。この動作は、アクセス可能なすべてのユニバーサル アナリティクス プロパティを返す Management API v3 の webproperties.list メソッドと似ています。

Google アナリティクス 4 では、プロパティ レベルで websiteUrl フィールドが存在しなくなったため、プロパティに関連付けられているすべてのデータ ストリームをリストするには properties.dataStreams/list を使用し、ストリームに関連付けられているウェブサイトの URL を取得するには、defaultUri フィールドを使用します。

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


プロパティを取得する

Management API v3 の webproperties.get メソッドと同様、Admin API v1 の properties.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}")


プロパティを作成する

Management API v3 の webproperties.insert メソッドと同様、Admin API v1 の properties.create メソッドは、新しい 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_)


プロパティを更新またはパッチ適用する

Management API v3 の webproperties.patch メソッドと同様、Admin API v1 の properties.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 Analytics Admin API には現在、Management API v3 に類似したユーザー権限モデルが実装されていますが、いくつかの違いがあります。

  1. Google Analytics Admin API でユーザー権限を管理するには、Management API v3 の AccountUserLinkWebPropertyUserLinkProfileUserLink リソースの代わりに、アカウント AccessBinding リソースとプロパティ AccessBinding リソースを使用します。
  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 のリソースとメソッドを使用します。

アカウント アクセス バインディングを一覧表示する

Management API v3 の accountUserLinks.list メソッドと同様に、Admin API v1 の accounts.accessBindings.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()


アカウントのアクセス バインディングを更新する

Management API v3 の accountUserLinks.update メソッドと同様に、Admin API v1 の accounts.accessBindings.patch メソッドは、アカウントのアクセス バインディングを更新します。

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)


アカウント アクセス バインディングを作成する

Management API v3 の accountUserLinks.insert メソッドと同様に、Admin API v1 の accounts.accessBindings.create メソッドは、アカウントにアクセス バインディングを作成します。

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)


バッチ処理

Management API v3 とは異なり、Admin API v1 ではマルチパート / 混合コンテンツ タイプを使用した複数の 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 の割り当ての変更

Admin API v1 には、Management API v3 と比べてより制限の少ない割り当てが導入されています。

  • Admin API v1 へのリクエストの数はデフォルトで、GCP プロジェクトの場合 1 分あたり 600 リクエストにレート制限されています。
  • 現在、GCP プロジェクトあたりの Admin API v1 呼び出しの回数には 1 日の割り当て上限はありません。 ただし、理論上は 1 日あたりのリクエスト数は 1 分あたりのリクエスト数によって制限されます。
  • 書き込みオペレーション数に関する 1 日あたりの個別の上限は削除されました。