You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Analytics Admin API添加用户链接失败排查求助

问题

此前通过Google Analytics Admin API为分析账号添加管理员(创建用户链接)的功能可正常使用,现在调用相同代码时返回501 MethodNotImplemented错误,核心错误信息如下:

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.

同时尝试create_user_link方法也遇到相同问题,已更新相关库但未解决,怀疑是alpha阶段的API端点被移除但客户端库未同步更新。

使用的Python代码如下:

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

问题原因及解决办法

原因

你的猜测完全正确:Google Analytics Admin API的v1alpha属于预览测试版本,Google会随时调整、移除该版本的API端点和方法,而你当前使用的客户端库未同步更新,导致调用了服务器已废弃的方法。

解决办法

  1. 切换至稳定版API
    放弃v1alpha预览版本,改用正式稳定的v1版本。该版本的API规范已固化,不会随意变更,能彻底避免这类兼容性问题。

  2. 调整代码适配v1版本

    • 导入路径从google.analytics.admin_v1alpha改为google.analytics.admin_v1
    • 用户链接相关方法已拆分细化:
      • 单个创建:使用create_account_user_link(账号维度)或create_property_user_link(媒体资源维度),替代原create_user_link
      • 批量创建:使用batch_create_account_user_links或batch_create_property_user_links,替代原batch_create_user_links
    • 角色参数direct_roles=['predefinedRoles/admin']保持不变,需确保父资源路径格式正确(账号为accounts/{account_id},媒体资源为properties/{property_id})

    核心代码调整示例:

    # 改用v1版本的类型导入
    from google.analytics.admin_v1.types import (
        CreateAccountUserLinkRequest,
        UserLink,
        BatchCreateAccountUserLinksRequest
    )
    
    # 替换批量创建用户链接的逻辑
    client.batch_create_account_user_links(
        BatchCreateAccountUserLinksRequest(
            parent=account.account,
            requests=[
                CreateAccountUserLinkRequest(
                    user_link=UserLink(
                        email_address="example@email.com",
                        direct_roles=['predefinedRoles/admin']
                    )
                )
            ],
            notify_new_users=True
        )
    )
    
  3. 更新客户端库
    确保安装支持v1版本的最新客户端库,执行命令:

    pip install --upgrade google-analytics-admin
    

内容的提问来源于stack exchange,提问作者maxpelic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 13:20:18