Google Directory API(Python)如何通过JSON批量添加多个用户
谷歌Admin SDK Directory API批量添加用户解决方案
报错原因
service.users().insert()是单用户插入接口,仅接受单个用户的配置对象作为请求体参数,你传入了多用户组成的列表,接口无法解析到预期的primaryEmail字段,因此抛出400参数错误。
实现批量添加的方案
方案1:使用官方批量请求接口(推荐,适合大量用户)
谷歌API客户端原生支持批量请求,单次最多可处理100个插入任务,比循环单条插入性能更高,同时支持自定义回调处理每个请求的结果,示例代码如下:
import json from googleapiclient.http import BatchHttpRequest # 从JSON文件加载用户配置列表 with open("users.json", "r", encoding="utf-8") as f: user_list = json.load(f) # 批量请求回调函数,用于处理每个用户的插入结果 def insert_callback(request_id, response, exception): if exception: print(f"第{request_id}个用户插入失败:{exception}") else: print(f"第{request_id}个用户插入成功,邮箱:{response['primaryEmail']}") # 初始化批量请求对象 batch = BatchHttpRequest(callback=insert_callback) # 遍历所有用户,将插入请求添加到批量任务中 for idx, user_config in enumerate(user_list): req = service.users().insert(body=user_config) batch.add(req, request_id=str(idx)) # 执行所有批量任务 batch.execute()
方案2:循环调用单用户插入接口(适合少量用户)
如果需要添加的用户数量较少,可以直接遍历用户列表调用单插入接口,逻辑更简单易维护:
import json # 从JSON文件加载用户配置列表 with open("users.json", "r", encoding="utf-8") as f: user_list = json.load(f) for user_config in user_list: try: resp = service.users().insert(body=user_config).execute() print(f"用户 {resp['primaryEmail']} 插入成功") except Exception as e: print(f"用户 {user_config['primaryEmail']} 插入失败:{str(e)}")
注意事项
- 所有用户的
primaryEmail后缀必须属于你当前谷歌工作区账号管理的域名,否则也会触发Invalid Input: primary_user_email报错 - 批量请求单次最多支持100个操作,用户量超过100时需要拆分多批处理
- 调用时需留意官方接口的频率限制,避免触发限流规则
内容的提问来源于stack exchange,提问作者Roman Shytskou
相关产品推荐
相关产品推荐

