Migrate to the Google Analytics Admin API v1

Both Alpha and Beta channels of the API continue to be supported. Beta channel contains a subset of the features available in Alpha which are considered stable and not expected to undergo a significant change in the future. New features will be added to Beta once they mature.

This document provides instructions on how to migrate existing code from the Google Analytics Management API v3 to the Google Analytics Admin API v1 and gives a brief overview of key differences between the two APIs.

Why do I need to migrate?

If your application needs to create or configure a Google Analytics 4 property, it must use the Admin API v1. The Management API v3 works only with Universal Analytics properties, and the Admin API v1 works only with Google Analytics 4 properties.

Prerequisites

You should familiarize yourself with basics of the Admin API v1 by reading the quick start guide.

Get started

To begin, you will prepare a Google Analytics 4 property, enable the Admin API v1, and then set up an API client library suitable for your platform.

Prepare a Google Analytics 4 property

Before you migrate your code to support the Admin API v1, you need to migrate your website to use a Google Analytics 4 property.

Enable the API

Click this button to automatically enable the Admin API v1 in your selected Google Cloud Project.

Enable the Google Analytics Admin API

Use a client library

Install a client library

If you use a client library, you need to install the Admin API v1 client library for your programming language.

Initialize a client library

The Admin API v1 client libraries were designed to get you started fast. By default, client libraries try to automatically find your service account credentials.

An easy way to provide service account credentials is by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable, the API client will use the value of this variable to find the service account key JSON file.

For example, you can set service account credentials by running the following command and using the path to the service account JSON file:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Below are the code snippets commonly used to initialize the Admin API v1 client libraries.

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

Instead of using an environment variable, it is also possible to pass the credentials information to an API client instance explicitly during initialization.

If you don't use a client library

If you use the Management API v3 without a client library and want to continue to do so with the Admin API v1, you can still use your credentials.

You need to use the new HTTP endpoint and discovery document provided by the Admin API:

If your code takes advantage of a Discovery document, you need to update it to the discovery document provided by the Admin API v1:

After updating the endpoint, you will need to familiarize yourself with the new request structure and concepts of the Admin API in order to update your JSON query.

Common tasks

Manage accounts

Admin API v1 provides a set of Google Analytics account and property management methods comparable to the Management API v3. Additionaly, Admin API v1 introduces functionality to provision, delete, update Google Analytics accounts.

  • Only Google Analytics 4 properties are supported by the Admin API v1 property management methods.

  • The notion of views (profiles) is not present in the Admin API v1.

  • Since data streams were introduced in Google Analytics 4, certain information is no longer present at the property level. For instance, the websiteUrl field is now present in DataStream entity instead of being a part of the property object.

List account summaries

The accountSummaries method of the Admin API returns lightweight summaries of all accounts accessible by the caller, similar to the accountSummaries method of the Management API v3.

An important distinction is that the Admin API v1 only returns information about the Google Analytics 4 properties, while the Management API v3 responses contain data about properties created with Universal Analytics. It is not possible to retrieve information about both types of properties using a single call.

Since there are no views (profiles) in Google Analytics 4, account summaries returned by the Admin API do not contain view (profile) information.

The Google Analytics 4 account summary data is limited to the resource and display names of the accounts/properties available to the current user.

Use the resource names returned in the account, property fields of the summaries response to retrieve the complete configuration data by calling account.get and property.get methods.

Admin API v1 Request

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

Admin API v1 Response

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

Management API v3 Request

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

Management API v3 Response

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

Sample code for calling the Admin API v1 using client libraries:

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


List accounts

The accounts.list method of the Admin API v1 returns all accounts accessible by the caller, similar to the accounts.list method of the Management API v3.

Admin API v1 Request

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

Admin API v1 Response

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

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

Management API v3 Response

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

Note the Admin API v1 response does not include information about effective user permissions, nor the childLink field that was present in the Management API v3.

Sample code for calling the Admin API v1 using client libraries:

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)


Manage properties

List properties

The properties.list method of the Admin API v1 returns all Google Analytics 4 properties accessible by the caller, similar to the webproperties.list method of the Management API v3 which returns all accessible Universal Analytics properties.

Since the websiteUrl field is no longer present at the property level in Google Analytics 4, use properties.dataStreams/list to list all data streams associated with the property and lookup the defaultUri field to retrieve the website URL associated with a stream.

Note the filter parameter in the URL of the properties.list request. The value of the parameter contains an expression for filtering the results of the request and can be used to list the properties associated with the given Google Analytics account ID, or with the linked Firebase project.

Admin API v1 Request

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

Admin API v1 Response

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

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

Management API v3 Response

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

Sample code for calling the Admin API v1 using client libraries:

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


Get property

The properties.get method of the Admin API v1 returns the information about a Google Analytics 4 property, similar to the webproperties.get method of the Management API v3.

Note that properties.get method of the Admin API supports Google Analytics 4 properties only.

Admin API v1 Request

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

Admin API v1 Response

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

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

Management API v3 Response

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

Sample code for calling the Admin API v1 using client libraries:

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


Create property

The properties.create method of the Admin API v1 creates a new Google Analytics 4 property, similar to the webproperties.insert method of the Management API v3.

Admin API v1 Request

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 Response

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

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

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

Management API v3 Response

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

Sample code for calling the Admin API v1 using client libraries:

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


Update/patch property

The properties.patch method of the Admin API v1 updates the configuration of a Google Analytics 4 property, similar to the webproperties.patch method of the Management API v3.

Note the updateMask parameter in the URL of the request, which contains the comma separated list of fields to be updated. Fields not present in this list will not be updated. If using a client library, update_mask parameter will be available as part of the method signature.

Admin API v1 Request

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

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

Admin API v1 Response

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

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 Response

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

Sample code for calling the Admin API v1 using client libraries:

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


Manage users

The Google Analytics Admin API currently implements a user permissions model similar to the Management API v3, but with a few differences.

  1. You manage user permissions with the Google Analytics Admin API using account AccessBinding and property AccessBinding resources instead of the AccountUserLink, WebPropertyUserLink and ProfileUserLink resources in the Management API v3.
  2. Property access bindings in the Google Analytics Admin API don't include implied permissions or permissions inherited from account access bindings. In the Management API v3, each user link contained a permissions.effective collection that included both implied and inherited permissions.

An AccessBinding entity contains a user (e-mail address) and a list of roles granted to the user. An AccessBinding entity can be created, updated or deleted.

The mapping between the Admin API v1 role names and Management API v3 permission names is as follows:

Admin API v1 role Management API v3 permission name
predefinedRoles/viewer READ_AND_ANALYZE
predefinedRoles/analyst COLLABORATE
predefinedRoles/editor EDIT
predefinedRoles/admin MANAGE_USERS

Roles predefinedRoles/no-cost-data, predefinedRoles/no-revenue-data were introduced in the Admin API v1 and have no corresponding mapping in the Management API v3.

This guide demonstrates how to manage account-level access bindings. To manage property-level access bindings, follow the same process but use property AccessBinding resources and methods in place of account AccessBinding.

List account access bindings

The accounts.accessBindings.list method of the Admin API v1 lists all access bindings on an account, similar to the accountUserLinks.list method of the Management API v3.

Admin API v1 Request

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

Admin API v1 Response

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

Management API v3 Request

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

Management API v3 Response

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

Sample code for calling the Admin API using client libraries:

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


Update account access bindings

The accounts.accessBindings.patch method of the Admin API v1 updates an access binding of an account, similar to the accountUserLinks.update method of the Management API v3.

Admin API v1 Request

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

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

Admin API v1 Response

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

Management API v3 Request

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 Response

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

Sample code for calling the Admin API v1 using client libraries:

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)


Create account access bindings

The accounts.accessBindings.create method of the Admin API v1 creates an access binding in an account, similar to the accountUserLinks.insert method of the Management API v3.

Admin API v1 Request

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

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

Admin API v1 Response

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

Management API v3 Request

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 Response

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

Sample code for calling the Admin API v1 using client libraries:

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)


Batching

Admin API v1 does not support batching multiple Google Analytics API calls using the multipart/mixed content type, as opposed to the Management API v3.

Instead, batching is supported explicitly on the API level. The following methods of the Admin API v1 support batching functionality:

Sample code for calling the Admin API v1 using client libraries:

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 quota changes

Admin API v1 introduces less restrictive quotas compared to the Management API v3.

  • The number of requests to the Admin API v1 is rate limited to 600 requests per minute by default for a GCP project.
  • Currently, there is no daily limit quota on the number of Admin API v1 calls per GCP project. Note that the theoretical maximum number of requests per day is still limited by the requests per minute quota.
  • A separate limit on the number of writes operations per day has been removed.