Migrate to the Google Analytics Admin API v1

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.

Note that the Admin API v1 is currently in Alpha, and is subject to change.

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 (AlphaAnalyticsAdminClient analyticsAdmin = AlphaAnalyticsAdminClient.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 WebDataStream 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/v1alpha/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():
    """Returns summaries of all accounts accessible by the caller."""
    client = AnalyticsAdminServiceClient()
    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/v1alpha/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.

A response includes even those accounts that might not currently have any Google Analytics 4 properties.

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():
    """Lists the Google Analytics accounts available to the current user."""
    client = AnalyticsAdminServiceClient()
    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.webDataStreams/list to list all Web 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/v1alpha/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):
    """Lists Google Analytics 4 properties under the specified parent account
    that are available to the current user."""
    client = AnalyticsAdminServiceClient()
    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/v1alpha/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):
    """Retrieves the Google Analytics 4 property details."""
    client = AnalyticsAdminServiceClient()
    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/v1alpha/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):
    """Creates a Google Analytics 4 property."""
    client = AnalyticsAdminServiceClient()
    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/v1alpha/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):
    """Updates the Google Analytics 4 property."""
    client = AnalyticsAdminServiceClient()
    # 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

Admin API v1 Alpha currently implements a user permissions model similar to the Management API v3. User permissions management functionality is likely to undergo significant changes in the upcoming release of the Admin API.

Just as with the Management API v3, you can manage user permissions by creating links between a user and an account or a Google Analytics 4 property. A userLink entity contains a user id (e-mail address) and a list of permissions granted to the user. A user link entity can be updated or deleted.

Permission names used in the Admin API v1 differ from the permission names in the Management API v3, while maintaining a similar meaning:

Admin API v1 permission name Management API v3 permission name
predefinedRoles/read READ_AND_ANALYZE
predefinedRoles/collaborate COLLABORATE
predefinedRoles/edit EDIT
predefinedRoles/manage-users MANAGE_USERS

The accounts.userLinks.list method of the Admin API v1 lists all user links 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/userLinks?key=[YOUR_API_KEY]

Admin API v1 Response

{
  "userLinks": [
    {
      "name": "accounts/XXXXXX/userLinks/XXXXXX",
      "emailAddress": "XXXXXX",
      "directRoles": [
        "predefinedRoles/edit",
        "predefinedRoles/manage-users"
      ]
    }
  ]
}

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 v1 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_user_links(account_id)


def list_account_user_links(account_id):
    """Lists user links under the specified parent account."""
    client = AnalyticsAdminServiceClient()
    results = client.list_user_links(parent=f"accounts/{account_id}")

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


The accounts.userLinks.list method of the Admin API v1 updates a user link on 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/userLinks/104236685715552897132?key=[YOUR_API_KEY]

{
  "directRoles": [
    "predefinedRoles/edit",
    "predefinedRoles/manage-users"
  ]
}

Admin API v1 Response

{
  "name": "accounts/XXXXXX/userLinks/104236685715552897132",
  "emailAddress": "USER-EMAIL",
  "directRoles": [
    "predefinedRoles/edit",
    "predefinedRoles/manage-users"
  ]
}

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 UserLink


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 user link ID (e.g. "123456") before running the sample.
    account_user_link_id = "YOUR-ACCOUNT-USER-LINK-ID"

    update_account_user_link(account_id, account_user_link_id)


def update_account_user_link(account_id, account_user_link_id):
    """Updates the account user link."""
    client = AnalyticsAdminServiceClient()
    # This call updates the email address and direct roles of the user link.
    # The user link to update is specified in the `name` field of the `UserLink`
    # instance.
    user_link = client.update_user_link(
        user_link=UserLink(
            name=f"accounts/{account_id}/userLinks/{account_user_link_id}",
            direct_roles=["predefinedRoles/collaborate"],
        ),
    )

    print("Result:")
    print(user_link)


The accounts.userLinks.create method of the Admin API v1 create a user link on 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/userLinks?key=[YOUR_API_KEY]

{
  "directRoles": [
    "predefinedRoles/edit",
    "predefinedRoles/manage-users"
  ],
  "emailAddress": "USER-EMAIL"
}

Admin API v1 Response

{
  "name": "accounts/XXXXXX/userLinks/104236685715552897132",
  "emailAddress": "USER-EMAIL",
  "directRoles": [
    "predefinedRoles/edit",
    "predefinedRoles/manage-users"
  ]
}

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 CreateUserLinkRequest
from google.analytics.admin_v1alpha.types import UserLink


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_user_link(account_id, email_address)


def create_account_user_link(account_id, email_address):
    """Creates a user link for the account."""
    client = AnalyticsAdminServiceClient()
    user_link = client.create_user_link(
        CreateUserLinkRequest(
            parent=f"accounts/{account_id}",
            user_link=UserLink(
                email_address=email_address, direct_roles=["predefinedRoles/read"]
            ),
            notify_new_user=True,
        )
    )

    print("Result:")
    print(user_link)


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 BatchCreateUserLinksRequest
from google.analytics.admin_v1alpha.types import CreateUserLinkRequest
from google.analytics.admin_v1alpha.types import UserLink


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_user_link(account_id, email_address)


def batch_create_account_user_link(account_id, email_address):
    """Creates a user link for the account using a batch call."""
    client = AnalyticsAdminServiceClient()
    response = client.batch_create_user_links(
        BatchCreateUserLinksRequest(
            parent=f"accounts/{account_id}",
            requests=[
                CreateUserLinkRequest(
                    user_link=UserLink(
                        email_address=email_address,
                        direct_roles=["predefinedRoles/read"],
                    )
                )
            ],
            notify_new_users=True,
        )
    )

    print("Result:")
    for user_link in response.user_links:
        print(user_link)
        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.