目录api的gsuite服务帐户返回http 400错误:错误的请求/无效的输入



我已经开始开发一些api来在我的G套件目录中创建用户。我遵循了服务帐户教程以及python的目录教程。我的代码非常简单,只是为了测试它将如何工作。

from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']
SERVICE_ACCOUNT_FILE = 'file'
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('admin', 'directory_v1', credentials=creds)
results = service.users().list(customer='i am not sure what customer is', maxResults=10, orderBy='email').execute() 
#this line produces the error.
#Vscode also states the service has no member users. But I did install all #the libraries
users = results.get('users', [])
print(users)

对我来说,文件对大多数事情都不清楚。当我运行这个时,我得到

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/admin/directory/v1/users?customer=students&maxResults=10&orderBy=email&alt=json returned "Bad Request">

当我将客户从my_customer更改为其他内容时,我得到Invalid Input。有什么建议可以导致这个错误,最好是如何通过服务帐户使用这个api?现在,我确实启用了directory api并创建了服务帐户,还下载了服务帐户文件。我是不是少了一步?我也更希望有人能提供我找不到的更好的文档。

最后我通过设置另一个参数"主题";当呼叫";service_account.Credentials.from_service_account_file"。

确保服务帐户启用了域范围的委派并具有正确的作用域。

是的,如果你想制作一个小助手脚本,那么如何做一件基本的事情还很不清楚。服务帐户的JSON是在Google Cloud中生成新密钥后得到的>IAM;管理员>服务帐户>钥匙。以下是完整的最终变体:

import json
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
SUBJECT = 'admin.email@your.domain.org'
CUSTOMER_ID = 'C91FjKp'
def main():
credentials = service_account.Credentials.from_service_account_file(
'/path/to/service-account-key.json', scopes=SCOPES
)
credentials = credentials.with_subject(SUBJECT)
admin = build('admin', 'directory_v1', credentials=credentials)
results = admin.users().list(
customer=CUSTOMER_ID,
query='isSuspended=False',
maxResults=100,
orderBy='email',
viewType='admin_view',
projection='basic',
showDeleted=False,
).execute()
print(json.dumps(results, indent=4))
if __name__ == '__main__':
main()

最新更新