GMail API使用Python Google API客户端:错误400,失败
我正在尝试使用服务帐户身份验证访问我们的GSuite GMail API。根据文件,我的MCVE代码如下:GMail API使用Python Google API客户端:错误400,失败,python,gmail-api,google-api-python-client,Python,Gmail Api,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
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客户端访问”中配置
我还能错过什么呢?我错过的,是书中提到的一小段。除了设置作用域外,我还需要通过调用以下命令模拟用户帐户: 之后,它的工作如预期,希望能帮助别人
cred = cred.with_subject(email)