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

Python调用Google MyBusiness API遇UnknownApiNameOrVersion错误求助

解决方案

核心问题:API名称错误

你用的mybusiness这个API名称已经被Google替换,现在Google Business Profile API(原My Business API)对应的正确API标识是mybusinessbusinessinformation(用于位置信息查询)或mybusinessaccountmanagement(用于账户管理操作),而非旧的mybusiness。

具体修正步骤

  1. 修正API客户端构建代码
    把原来的:
service = build("mybusiness", "v1", credentials=creds)

替换为:

service = build("mybusinessbusinessinformation", "v1", credentials=creds)
  1. 修复parent参数的格式错误
    你代码里的parent='accounts/112827745/locations'.format(account_id='myaccount')既没有正确格式化变量,也用错了参数格式——查询位置列表的parent应该是账户ID(格式为accounts/{account_id}),而非accounts/xxx/locations。修正为:
parent = 'accounts/{account_id}'.format(account_id='112827745')
locations = service.accounts().locations().list(parent=parent).execute()
  1. 调整凭证校验逻辑顺序
    原来的代码会先调用API再校验凭证有效性,可能导致过期凭证直接报错。调整为优先处理凭证有效性,再执行API调用。

修正后的完整代码

from google.cloud import bigquery
from pathlib import Path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from libs.gcp import gcp
import google.auth
from googleapiclient.discovery import build

def run():
    SCOPES = ["https://www.googleapis.com/auth/business.manage"]
    creds = None

    # 加载本地保存的凭证
    if Path("token.json").exists():
        creds = Credentials.from_authorized_user_file("token.json", SCOPES)
    
    # 校验并更新凭证
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
            creds = flow.run_local_server(port=0)
        # 保存更新后的凭证
        with open("token.json", "w") as token:
            token.write(creds.to_json())
    
    # 构建API客户端并查询位置
    service = build("mybusinessbusinessinformation", "v1", credentials=creds)
    parent = 'accounts/{account_id}'.format(account_id='112827745')
    locations = service.accounts().locations().list(parent=parent).execute()

    # 打印位置名称
    for location in locations.get('locations', []):
        print(location.get('name'))

为什么Postman能正常调用?

Postman里你应该是直接使用了正确的API端点(比如https://mybusinessbusinessinformation.googleapis.com/v1/accounts/{account_id}/locations),而Python的build方法依赖Google的API discovery文档,旧的mybusiness名称已从文档中移除,因此报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:04:56