如何解决连接到Gmail API的400错误

时间:2019-09-05 02:01:49

标签: python google-api gmail-api google-api-python-client service-accounts

我正在尝试建立服务应用程序连接以检索组织成员的邮件元数据。我收到一个非常无助的400错误,没有提示为什么存在问题。

SCOPES = ['https://www.googleapis.com/auth/gmail.metadata']
credentials = ServiceAccountCredentials.from_json_keyfile_name("scripts/test-235821-48a6ee6cab95.json", SCOPES)
http_auth = credentials.authorize(Http())
service = build('gmail', 'v1', http=http_auth, cache_discovery=False)
response = service.users().getProfile(userId="a_user@mydomain.com").execute()

要说明我如何进行设置:

  1. 我在Google Cloud Platform控制台中创建了一个项目。
  2. 我在该项目中创建了一个服务帐户,并已为其授予域范围的授权
  3. 在G Suite管理控制台中,我授权该服务帐户访问用户数据而不必单独给出同意或他们的密码,并授予其https://www.googleapis.com/auth/gmail.metadata的范围

我得到的错误是:

[2019-09-04 18:29:10,199] INFO in {app::52} DEPLOYMENT local
[2019-09-04 18:29:11,974] INFO in {discovery::272} URL being requested: GET https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest
[2019-09-04 18:29:11,974] INFO in {transport::157} Attempting refresh to obtain initial access_token
[2019-09-04 18:29:11,976] INFO in {client::777} Refreshing access_token
[2019-09-04 18:29:12,143] INFO in {discovery::873} URL being requested: GET https://www.googleapis.com/gmail/v1/users/a_user%40mydomain.com/profile?alt=json
Traceback (most recent call last):
  File "manage.py", line 64, in <module>
manager.run()
  File "/Users/*/Repositories/myco/venv/lib/python3.7/site-packages/flask_script/__init__.py", line 417, in run
result = self.handle(argv[0], argv[1:])
  File "/Users/*/Repositories/myco/venv/lib/python3.7/site-packages/flask_script/__init__.py", line 386, in handle
res = handle(*args, **config)
  File "/Users/*/Repositories/myco/venv/lib/python3.7/site-packages/flask_script/commands.py", line 216, in __call__
return self.run(*args, **kwargs)
  File "manage.py", line 59, in crm_get_messages
Gmail.get_messages()
  File "/Users/*/Repositories/myco/scripts/gmail.py", line 23, in get_messages
response = service.users().getProfile(userId="a_user@mydomain.com").execute()
  File "/Users/*/Repositories/myco/venv/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
  File "/Users/*/Repositories/myco/venv/lib/python3.7/site-packages/googleapiclient/http.py", line 851, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/a_user%40domain.com/profile?alt=json returned "Bad Request">

0 个答案:

没有答案