通过服务帐户访问Google My Business API时出错403

时间:2017-09-07 18:20:36

标签: python google-oauth google-my-business-api

我正在开展一个项目,我们希望通过GMB API收集有关GMB性能的数据。这需要捕获许多reportInsights结果。我们不会为此帐户创建或更新任何记录。然而,我尝试了Oauth2方法,这要求我提供权限,因为我们没有访问或更新任何用户数据,我想避免Oauth。

从文档和本用例中,我认为服务帐户是最好的方法,我在Google API控制台中创建了该凭据。

我可以创建凭据,但是,当我运行该进程时,我收到以下错误:

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://mybusiness.googleapis.com/$discovery/rest?version=v3 returned "The request is missing a valid API key.">

这看起来很奇怪,因为我有一套有效的服务帐户凭据。我确实包含了来自Google API控制台的有效API密钥,但我收到了同样的错误。

这是我的Python代码:

import os
import httplib2
import json
import argparse
import apiclient.discovery

from oauth2client.service_account import ServiceAccountCredentials

from apiclient.discovery import build

api_name = 'mybusiness'
api_version = 'v3'
api_key = '<my valid api key from google api console that has permission for this GMB project>'

discovery_uri = 'https://mybusiness.googleapis.com/$discovery/rest?version={}'.format(api_version)

flow_scope='https://www.googleapis.com/auth/plus.business.manage'

credentials_file = '/Google_My_Business-service_account.json' # the service account credentials from the Google API console that have permission for this GMB project 

credentials = ServiceAccountCredentials.from_json_keyfile_name(credentials_file, scopes=flow_scope)

print("credentials: ", credentials)

http = credentials.authorize(httplib2.Http())
print("http: ", http)

# Build the service object
service = build(api_name, api_version, http=http, developerKey=api_key, discoveryServiceUrl=discovery_uri)

从最后一行抛出错误。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

尝试将您的代码更改为以下

from oauth2client.client import AccessTokenCredentials
credentials = AccessTokenCredentials('<an access token>', 'my-user-agent/1.0')
http = httplib2.Http() 
http = credentials.authorize(http)

然后,如果可行,请尝试以下方法从JSON文件

获取凭据
from oauth2client.client import AccessTokenCredentials
credentials = AccessTokenCredentials.from_json(credentials_file)
http = httplib2.Http()
http = credentials.authorize(http)

答案 1 :(得分:1)

问题在于发现服务网址。似乎私人api无法通过发现api服务访问(即使你使用apikeys)。因此,解决方案是将发现服务URL更改为显示mybusiness服务的有效json文件。

discovery_uri = "https://developers.google.com/my-business/samples/mybusiness_google_rest_v3p3.json"