HttpError 400 错误请求 - Google 管理目录 API (Python)

HttpError 400 Bad Request - Google Admin Directory API (Python)

我在创建 Google 项目即服务帐户时遇到困难。我在 Python 中使用 Admin SDK,特别是目录 API。我相信我的身份验证是正确的,但是在调用 users.list 时出现以下错误:

Traceback (most recent call last):
  File "googleproject.py", line 17, in <module>
userlist = service.users().list().execute(http = http_auth)
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 135, in positional_wrapper
return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 723, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/admin/directory/v1/users?alt=json returned "Bad Request">

我的代码如下:

from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http
from apiclient.discovery import build

#----AUTHORISATION----#

client_email = '*****@developer.gserviceaccount.com'
with open('*****.p12') as f:
  private_key = f.read()

credentials = SignedJwtAssertionCredentials(client_email, private_key, 'https://www.googleapis.com/auth/admin.directory.user')
http_auth = credentials.authorize(Http())

#--------------------#

service = build('admin', 'directory_v1', http = http_auth)
userlist = service.users().list().execute(http = http_auth)

我试过将 http = http_auth 作为 execute() 的参数传递和不传递。我基本上遵循了此处给出的示例:https://code.google.com/p/google-api-python-client/source/browse/samples/service_account/tasks.py

我在开发者控制台中启用了 Admin SDK,并在 Google 应用程序控制面板中添加了客户端 ID 和范围。

我设法修复了它!问题是我没有在列表参数中设置域。所以新代码如下:

from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http
from apiclient.discovery import build

#----AUTHORISATION----#

client_email = '*****@developer.gserviceaccount.com'
with open('*****') as f:
  private_key = f.read()

credentials = SignedJwtAssertionCredentials(client_email, private_key, 'https://www.googleapis.com/auth/admin.directory.user', sub = 'super-admin@domain.com')
http_auth = credentials.authorize(Http())

#--------------------#

service = build('admin', 'directory_v1', http = http_auth)
user = service.users().list(showDeleted = False, domain = 'domain.com').execute()