Chuyển sang API Quản trị Google Analytics phiên bản 1

Cả kênh Alpha và Beta của API sẽ tiếp tục được hỗ trợ. Kênh Beta chứa một tập hợp con các tính năng có sẵn trong giai đoạn Alpha được coi là ổn định và dự kiến sẽ không trải qua thay đổi đáng kể trong tương lai. Các tính năng mới sẽ được bổ sung vào bản Beta khi chúng hoàn thiện.

Tài liệu này cung cấp hướng dẫn về cách di chuyển mã hiện có từ API Quản lý Google Analytics phiên bản 3 sang API Quản trị Google Analytics phiên bản 1, đồng thời cung cấp thông tin tổng quan ngắn gọn về những điểm khác biệt chính giữa hai API này.

Tại sao tôi cần phải di chuyển?

Nếu cần tạo hoặc định cấu hình tài sản Google Analytics 4, ứng dụng của bạn phải sử dụng API Quản trị phiên bản 1. API Quản lý phiên bản 3 chỉ hoạt động với các tài sản Universal Analytics và API Quản trị phiên bản 1 chỉ hoạt động với các tài sản Google Analytics 4.

Điều kiện tiên quyết

Bạn nên làm quen với các khái niệm cơ bản về API Quản trị phiên bản 1 bằng cách đọc hướng dẫn bắt đầu nhanh.

Bắt đầu

Để bắt đầu, bạn sẽ chuẩn bị một tài sản Google Analytics 4, bật API Quản trị phiên bản 1, rồi thiết lập một thư viện ứng dụng API phù hợp với nền tảng của bạn.

Chuẩn bị tài sản Google Analytics 4

Trước khi di chuyển mã để hỗ trợ API Quản trị phiên bản 1, bạn cần di chuyển trang web của mình để sử dụng tài sản Google Analytics 4.

Bật API

Nhấp vào nút này để tự động bật API Quản trị phiên bản 1 trong dự án Google Cloud mà bạn đã chọn.

Bật API Quản trị của Google Analytics

Sử dụng thư viện ứng dụng

Cài đặt thư viện ứng dụng

Nếu sử dụng thư viện ứng dụng, bạn cần cài đặt thư viện ứng dụng API Quản trị phiên bản 1 cho ngôn ngữ lập trình của mình.

Khởi chạy thư viện ứng dụng

Thư viện ứng dụng API Quản trị phiên bản 1 được thiết kế để giúp bạn bắt đầu nhanh chóng. Theo mặc định, các thư viện ứng dụng sẽ cố gắng tự động tìm thông tin đăng nhập tài khoản dịch vụ của bạn.

Một cách dễ dàng để cung cấp thông tin đăng nhập tài khoản dịch vụ là đặt biến môi trường GOOGLE_APPLICATION_CREDENTIALS, ứng dụng API sẽ sử dụng giá trị của biến này để tìm tệp JSON chứa khoá tài khoản dịch vụ.

Ví dụ: bạn có thể đặt thông tin xác thực tài khoản dịch vụ bằng cách chạy lệnh sau và sử dụng đường dẫn đến tệp JSON của tài khoản dịch vụ:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Dưới đây là các đoạn mã thường dùng để khởi chạy thư viện ứng dụng API Quản trị phiên bản 1.

Java

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

Python

client = AlphaAnalyticsAdminClient()

.NET

AlphaAnalyticsAdminClient client = AlphaAnalyticsAdminClient.Create();

1.199

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

Thay vì sử dụng biến môi trường, bạn cũng có thể truyền thông tin xác thực tới một thực thể ứng dụng API một cách rõ ràng trong quá trình khởi chạy.

Nếu bạn không sử dụng thư viện ứng dụng

Nếu sử dụng API Quản lý phiên bản 3 mà không có thư viện ứng dụng và muốn tiếp tục sử dụng bằng API Quản trị phiên bản 1, thì bạn vẫn có thể sử dụng thông tin đăng nhập của mình.

Bạn cần sử dụng tài liệu khám phá và điểm cuối HTTP mới do API Quản trị cung cấp:

Nếu mã của bạn tận dụng Tài liệu khám phá, bạn cần cập nhật mã đó thành tài liệu khám phá do API Quản trị phiên bản 1 cung cấp:

Sau khi cập nhật điểm cuối, bạn sẽ cần tự làm quen với cấu trúc yêu cầu và khái niệm mới của API Quản trị để cập nhật truy vấn JSON của mình.

Các thao tác phổ biến

Quản lý tài khoản

API Quản trị phiên bản 1 cung cấp một nhóm các phương thức quản lý tài sản và tài khoản Google Analytics tương đương với API Quản lý phiên bản 3. Ngoài ra, API Quản trị phiên bản 1 cung cấp chức năng cấp phép, xoá, cập nhật tài khoản Google Analytics.

  • Phương thức quản lý thuộc tính API Quản trị phiên bản 1 chỉ hỗ trợ các tài sản Google Analytics 4.

  • Khái niệm chế độ xem (hồ sơ) không có trong API Quản trị phiên bản 1.

  • Vì luồng dữ liệu đã được ra mắt trong Google Analytics 4, nên một số thông tin không còn xuất hiện ở cấp tài sản nữa. Ví dụ: trường websiteUrl hiện xuất hiện trong thực thể DataStream thay vì là một phần của đối tượng thuộc tính.

Liệt kê các bản tóm tắt tài khoản

Phương thức accountSummaries của API Quản trị trả về bản tóm tắt ngắn gọn về tất cả tài khoản mà phương thức gọi có thể truy cập, tương tự như phương thức accountSummaries của API Quản lý phiên bản 3.

Một điểm khác biệt quan trọng là API Quản trị phiên bản 1 chỉ trả về thông tin về các tài sản Google Analytics 4, trong khi các phản hồi của API Quản lý phiên bản 3 chứa dữ liệu về các tài sản được tạo bằng Universal Analytics. Bạn không thể truy xuất thông tin về cả hai loại thuộc tính thông qua một lệnh gọi duy nhất.

Vì không có chế độ xem (hồ sơ) trong Google Analytics 4, nên bản tóm tắt tài khoản do API Quản trị trả về không chứa thông tin về chế độ xem (hồ sơ).

Dữ liệu tóm tắt tài khoản Google Analytics 4 chỉ giới hạn ở tên tài nguyên và tên hiển thị của những tài khoản/tài sản mà người dùng hiện tại có thể sử dụng.

Sử dụng tên tài nguyên được trả về trong các trường account, property của phản hồi tóm tắt để truy xuất dữ liệu cấu hình đầy đủ bằng cách gọi các phương thức account.getproperty.get.

Yêu cầu API quản trị phiên bản 1

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

Phản hồi của API quản trị phiên bản 1

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

Yêu cầu API quản lý phiên bản 3

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

Phản hồi của API quản lý phiên bản 3

{
  "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"
            }
          ]
        },
        ...
}

Mã mẫu để gọi API Quản trị phiên bản 1 bằng thư viện ứng dụng:

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


Liệt kê tài khoản

Phương thức accounts.list của API Quản trị phiên bản 1 sẽ trả về tất cả tài khoản mà phương thức gọi có thể truy cập, tương tự như phương thức accounts.list của API Quản lý phiên bản 3.

Yêu cầu API quản trị phiên bản 1

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

Phản hồi của API quản trị phiên bản 1

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

Yêu cầu API quản lý phiên bản 3

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

Phản hồi của API quản lý phiên bản 3

{
  "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"
      }
    },
    ...
}

Xin lưu ý rằng phản hồi của API Quản trị phiên bản 1 không bao gồm thông tin về quyền hiệu quả của người dùng, cũng như trường childLink có trong API Quản lý phiên bản 3.

Mã mẫu để gọi API Quản trị phiên bản 1 bằng thư viện ứng dụng:

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)


Quản lý cơ sở lưu trú

Liệt kê cơ sở lưu trú

Phương thức properties.list của API Quản trị phiên bản 1 sẽ trả về tất cả các tài sản Google Analytics 4 mà phương thức gọi có thể truy cập, tương tự như phương thức webproperties.list của API Quản lý phiên bản 3 trả về tất cả các tài sản Universal Analytics có thể truy cập được.

Vì trường websiteUrl không còn hiển thị ở cấp tài sản trong Google Analytics 4, hãy sử dụng properties.dataStreams/list để liệt kê tất cả luồng dữ liệu được liên kết với tài sản và tra cứu trường defaultUri để truy xuất URL của trang web được liên kết với một luồng.

Hãy lưu ý tham số filter trong URL của yêu cầu properties.list. Giá trị của tham số chứa một biểu thức để lọc kết quả của yêu cầu và có thể dùng để liệt kê các thuộc tính được liên kết với mã tài khoản Google Analytics nhất định hoặc với dự án Firebase đã liên kết.

Yêu cầu API quản trị phiên bản 1

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

Phản hồi của API quản trị phiên bản 1

{
  "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"
    },
    ...
}

Yêu cầu API quản lý phiên bản 3

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

Phản hồi của API quản lý phiên bản 3

{
  "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"
      }
    },
    ...
}

Mã mẫu để gọi API Quản trị phiên bản 1 bằng thư viện ứng dụng:

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


Mua tài sản

Phương thức properties.get của API Quản trị phiên bản 1 sẽ trả về thông tin về tài sản Google Analytics 4, tương tự như phương thức webproperties.get của API Quản lý phiên bản 3.

Xin lưu ý rằng phương thức properties.get của API Quản trị chỉ hỗ trợ các tài sản Google Analytics 4.

Yêu cầu API quản trị phiên bản 1

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

Phản hồi của API quản trị phiên bản 1

{
  "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"
}

Yêu cầu API quản lý phiên bản 3

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

Phản hồi của API quản lý phiên bản 3

{
  "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"
  }
}

Mã mẫu để gọi API Quản trị phiên bản 1 bằng thư viện ứng dụng:

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}")


Tạo tài sản

Phương thức properties.create của API Quản trị phiên bản 1 sẽ tạo một tài sản Google Analytics 4 mới, tương tự như phương thức webproperties.insert của API Quản lý phiên bản 3.

Yêu cầu API quản trị phiên bản 1

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"
}

Phản hồi của API quản trị phiên bản 1

{
  "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"
}

Yêu cầu API quản lý phiên bản 3

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

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

Phản hồi của API quản lý phiên bản 3

{
  "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"
  }
}

Mã mẫu để gọi API Quản trị phiên bản 1 bằng thư viện ứng dụng:

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


Cập nhật/vá thuộc tính

Phương thức properties.patch của API Quản trị phiên bản 1 sẽ cập nhật cấu hình của tài sản Google Analytics 4, tương tự như phương thức webproperties.patch của API Quản lý phiên bản 3.

Lưu ý tham số updateMask trong URL của yêu cầu, chứa danh sách các trường được phân tách bằng dấu phẩy sẽ được cập nhật. Các trường không có trong danh sách này sẽ không được cập nhật. Nếu sử dụng thư viện ứng dụng, tham số update_mask sẽ có sẵn như một phần của chữ ký phương thức.

Yêu cầu API quản trị phiên bản 1

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

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

Phản hồi của API quản trị phiên bản 1

{
  "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"
}

Yêu cầu API quản lý phiên bản 3

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

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

Phản hồi của API quản lý phiên bản 3

{
  "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"
  }
}

Mã mẫu để gọi API Quản trị phiên bản 1 bằng thư viện ứng dụng:

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


Quản lý người dùng

API Quản trị của Google Analytics hiện triển khai mô hình quản lý quyền của người dùng tương tự như API Quản lý phiên bản 3, nhưng có một số điểm khác biệt.

  1. Bạn quản lý quyền của người dùng với API Quản trị của Google Analytics bằng cách sử dụng các tài nguyên tài khoản AccessBindingthuộc tính AccessBinding thay vì các tài nguyên AccountUserLink, WebPropertyUserLinkProfileUserLink trong API Quản lý phiên bản 3.
  2. Các liên kết quyền truy cập vào tài sản trong API Quản trị Google Analytics không bao gồm quyền ngầm ẩn hoặc quyền được kế thừa từ các mối liên kết quyền truy cập vào tài khoản. Trong API Quản lý phiên bản 3, mỗi đường liên kết đến người dùng đều chứa một tập hợp permissions.effective bao gồm cả quyền ngụ ý và quyền kế thừa.

Thực thể AccessBinding chứa một người dùng (địa chỉ email) và danh sách các vai trò được cấp cho người dùng đó. Bạn có thể tạo, cập nhật hoặc xoá thực thể AccessBinding.

Sau đây là mối liên kết giữa tên vai trò của API Quản trị phiên bản 1 và tên quyền của API Quản lý phiên bản 3:

Vai trò API quản trị phiên bản 1 Tên quyền API quản lý phiên bản 3
Vai trò/người xem được xác định trước READ_AND_ANALYZE
Vai trò/nhà phân tích được xác định trước CỘNG TÁC
Vai trò/người chỉnh sửa được xác định trước CHỈNH SỬA
Vai trò/quản trị viên được xác định trước MANAGE_USERS

Các vai trò predefinedRoles/no-cost-data, predefinedRoles/no-revenue-data đã được ra mắt trong API Quản trị phiên bản 1 và không có mối liên kết tương ứng nào trong API Quản lý phiên bản 3.

Hướng dẫn này trình bày cách quản lý các liên kết quyền truy cập cấp tài khoản. Để quản lý các liên kết quyền truy cập ở cấp thuộc tính, hãy thực hiện theo quy trình tương tự nhưng sử dụng các tài nguyên và phương thức thuộc tính AccessBinding thay cho tài khoản AccessBinding.

Liệt kê các liên kết quyền truy cập tài khoản

Phương thức accounts.accessBindings.list của API Quản trị v1 liệt kê tất cả các liên kết quyền truy cập trên một tài khoản, tương tự như phương thức accountUserLinks.list của API Quản lý v3.

Yêu cầu API quản trị phiên bản 1

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

Phản hồi của API quản trị phiên bản 1

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

Yêu cầu API quản lý phiên bản 3

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

Phản hồi của API quản lý phiên bản 3

{
  "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"
        ]
      }
    }
  ]
}

Mã mẫu để gọi API Quản trị bằng thư viện ứng dụng:

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


Cập nhật các liên kết quyền truy cập tài khoản

Phương thức accounts.accessBindings.patch của API Quản trị phiên bản 1 sẽ cập nhật tính năng liên kết quyền truy cập của một tài khoản, tương tự như phương thức accountUserLinks.update của API Quản lý phiên bản 3.

Yêu cầu API quản trị phiên bản 1

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

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

Phản hồi của API quản trị phiên bản 1

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

Yêu cầu API quản lý phiên bản 3

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"
    ]
  }
}

Phản hồi của API quản lý phiên bản 3

{
  "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"
    ]
  }
}

Mã mẫu để gọi API Quản trị phiên bản 1 bằng thư viện ứng dụng:

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)


Tạo các liên kết quyền truy cập vào tài khoản

Phương thức accounts.accessBindings.create của API Quản trị phiên bản 1 sẽ tạo liên kết quyền truy cập trong một tài khoản, tương tự như phương thức accountUserLinks.insert của API Quản lý phiên bản 3.

Yêu cầu API quản trị phiên bản 1

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

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

Phản hồi của API quản trị phiên bản 1

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

Yêu cầu API quản lý phiên bản 3

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"
    ]
  }
}

Phản hồi của API quản lý phiên bản 3

{
  "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"
    ]
  }
}

Mã mẫu để gọi API Quản trị phiên bản 1 bằng thư viện ứng dụng:

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)


Tạo lô

API Quản trị phiên bản 1 không hỗ trợ việc phân lô nhiều lệnh gọi API Google Analytics bằng cách sử dụng loại nội dung nhiều phần/kết hợp, thay vì API Quản lý phiên bản 3.

Thay vào đó, việc tạo lô được hỗ trợ rõ ràng ở cấp độ API. Các phương thức sau đây của API Quản trị phiên bản 1 hỗ trợ chức năng tạo lô:

Mã mẫu để gọi API Quản trị phiên bản 1 bằng thư viện ứng dụng:

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


Các thay đổi về hạn mức API

API Quản trị phiên bản 1 đưa ra hạn mức ít hạn chế hơn so với API Quản lý phiên bản 3.

  • Theo mặc định, số lượng yêu cầu gửi đến API Quản trị phiên bản 1 bị giới hạn ở mức 600 yêu cầu mỗi phút đối với một dự án GCP.
  • Hiện tại, không có hạn mức hằng ngày về số lệnh gọi API Quản trị phiên bản 1 trên mỗi dự án GCP. Xin lưu ý rằng số lượng yêu cầu tối đa mỗi ngày theo lý thuyết vẫn bị giới hạn bởi hạn mức số yêu cầu mỗi phút.
  • Đã loại bỏ giới hạn riêng về số thao tác ghi mỗi ngày.