GMail API 使用 Python Google API 客户端:错误 400,前提条件失败

GMail API using Python Google API Client: error 400, failed precondition

我正在尝试使用 Google API Python Client 和服务帐户身份验证来访问我们的 GSuite GMail API。根据文档,我的 MCVE 代码如下:

import os
import sys
from google.auth.transport.requests import Request
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build

email = sys.argv[1]

cred = Credentials.from_service_account_file(os.getenv('SERVICE_ACCOUNT'))
cred = cred.with_scopes(['https://www.googleapis.com/auth/gmail.labels'])
cred.refresh(Request())

gmail = build('gmail', 'v1', credentials=cred)
try:
    print(gmail.users().labels().list(userId=email).execute())
except Exception as ex:
    print('Error:', ex.content.decode('ascii'))

输出为:

Error: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "failedPrecondition",
    "message": "Bad Request"
   }
  ],
  "code": 400,
  "message": "Bad Request"
 }
}

通常的嫌疑人:

另一个观察:当我访问 API 时,服务帐户的使用计数器增加,但相应的 OAuth2 客户端的使用计数器仍然为 0。

我还能缺少什么?

缺少的是documentation. In addition to setting the scopes, I need to impersonate a user account by calling with_subject中提到的一小部分:

cred = cred.with_subject(email)

之后它按预期工作,希望对某人有所帮助。