使用Google Workspace API创建用户遇400错误,求正确调用方式
Google Workspace Admin SDK创建用户400错误修复方案
你的代码出现400错误的核心原因是调用users().create()时仅传入了customer参数,缺少创建用户所需的必填核心字段。Google Workspace创建用户必须提供用户邮箱、姓名、初始密码等关键信息,否则接口会返回参数无效的400错误。
正确调用方式及代码修正
以下是修正后的完整代码,重点修改用户创建的部分:
from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/admin.directory.user'] def main(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) with open('token.json', 'w') as token: token.write(creds.to_json()) try: service = build('admin', 'directory_v1', credentials=creds) # 构造用户创建的核心参数(必填字段) user_payload = { "primaryEmail": "new.user@your-domain.com", # 替换为你的域下的邮箱 "name": { "givenName": "John", # 用户名字 "familyName": "Doe" # 用户姓氏 }, "password": "YourStrongPassword123!", # 需符合Google Workspace域的密码策略 "changePasswordAtNextLogin": True # 可选:强制用户下次登录修改密码 } # 调用创建用户接口,customer用my_customer代表当前管理员所在域 created_user = service.users().create(body=user_payload, customer='my_customer').execute() print(f"用户创建成功:{created_user['primaryEmail']}") except HttpError as e: print(f"请求错误:{e.content.decode('utf-8')}") if __name__ == '__main__': main()
关键注意事项
- 必填字段说明:必须包含
primaryEmail(域内唯一邮箱)、name.givenName、name.familyName、password,缺少任何一个都会触发400错误。 - 权限要求:必须使用Google Workspace域管理员账号完成授权,普通域用户没有创建用户的权限。
- customer参数:使用
my_customer即可代表当前管理员所属的域,无需手动填写具体的客户ID。 - 密码规则:密码需符合你的Google Workspace域设置的密码策略(比如长度、复杂度、特殊字符要求等),否则会返回400错误。
- 错误排查:添加
HttpError捕获,可以打印出详细的错误信息,帮助精准定位问题(比如邮箱已存在、密码不符合规则等)。
内容的提问来源于stack exchange,提问作者Ankur Roy
相关产品推荐
相关产品推荐

