Search code examples
pythongoogle-analyticsgoogle-analytics-api

Google Analytics Admin API - create user link not working?


I'm trying to add a user link to an analytics account (add an admin to the account) and it was working before, but now when I try to use the same function I get this error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/google/api_core/grpc_helpers.py", line 72, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/grpc/_channel.py", line 946, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "/usr/local/lib/python3.10/dist-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking
    raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
        status = StatusCode.UNIMPLEMENTED
        details = "The GRPC target is not implemented on the server, host: analyticsadmin.googleapis.com, method: /google.analytics.admin.v1alpha.AnalyticsAdminService/BatchCreateUserLinks."
        debug_error_string = "UNKNOWN:Error received from peer ipv6:%5B2607:f8b0:4002:c00::5f%5D:443 {created_time:"2023-10-05T15:27:15.904224325-04:00", grpc_status:12, grpc_message:"The GRPC target is not implemented on the server, host: analyticsadmin.googleapis.com, method: /google.analytics.admin.v1alpha.AnalyticsAdminService/BatchCreateUserLinks."}"
>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  ...
    client.batch_create_user_links(
  File "/usr/local/lib/python3.10/dist-packages/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py", line 2661, in batch_create_user_links
    response = rpc(
  File "/usr/local/lib/python3.10/dist-packages/google/api_core/gapic_v1/method.py", line 113, in __call__
    return wrapped_func(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/google/api_core/timeout.py", line 120, in func_with_timeout
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/google/api_core/grpc_helpers.py", line 74, in error_remapped_callable
    raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.MethodNotImplemented: 501 The GRPC target is not implemented on the server, host: analyticsadmin.googleapis.com, method: /google.analytics.admin.v1alpha.AnalyticsAdminService/BatchCreateUserLinks.

Here's the python code I'm using:

from google.analytics.admin import AnalyticsAdminServiceClient

CREDENTIALS_FILE_PATH = './analytics-credentials.json'

from google_auth_oauthlib import flow
from google.analytics.admin_v1alpha.types import CreateUserLinkRequest, UserLink, BatchCreateUserLinksRequest

def list_accounts(credentials=None):
    client = AnalyticsAdminServiceClient(credentials=credentials)

    # Make the request
    results = client.list_account_summaries()

    # Displays the configuration information for all Google Analytics accounts
    # available to the authenticated user.
    print("Result:")
    for account in results:

        print(account.account)

        #add user
        if account.account == 'accounts/123456789':
            print(account)

            client.batch_create_user_links(
                BatchCreateUserLinksRequest(
                    parent=account.account, 
                    requests=[
                        CreateUserLinkRequest(
                            user_link=UserLink(
                                email_address="example@email.com", 
                                direct_roles=['predefinedRoles/admin']
                            )
                        )
                    ],
                    notify_new_users=True
                )
            )


def get_credentials(token=None):
    """Creates an OAuth2 credentials instance."""

    if token:
        #read CREDENTIALS_FILE_PATH as json
        import json
        with open(CREDENTIALS_FILE_PATH) as json_file:
            data = json.load(json_file)['web']
            from google.oauth2.credentials import Credentials

            return Credentials(
                token=token,
                token_uri=data['token_uri'],
                client_id=data['client_id'],
                client_secret=data['client_secret'],
                scopes=["https://www.googleapis.com/auth/analytics.edit", "https://www.googleapis.com/auth/analytics.manage.users"]
            )



    
    appflow = flow.InstalledAppFlow.from_client_secrets_file(
        CREDENTIALS_FILE_PATH,
        scopes=["https://www.googleapis.com/auth/analytics.edit", "https://www.googleapis.com/auth/analytics.manage.users"],

    launch_browser = True
    if launch_browser:
        appflow.run_local_server()
    else:
        appflow.run_console()

    
    #print the access token

    print(appflow.credentials.token)

    return appflow.credentials
    




def main():
    credentials = get_credentials()
    list_accounts(credentials)

if __name__ == "__main__":
    main()

I also tried the create_user_link method with the same issue. I can't figure out why this would have been working before but no longer works, any ideas? I know the API is in alpha/beta, maybe the endpoint has been removed and the library has not been updated (I updated the library with no success)?


Solution

  • UserLinks has been replaced by AccessBindings, see the announcement here: https://developers.google.com/analytics/devguides/config/admin/v1/changelog#2023-02-24_access_bindings_are_replacing_user_links_for_user_permissions_management

    Docs about AccessBindings are here: https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.accessBindings#AccessBinding