无法调用Moodle API的core_user_create_users接口创建用户求助
解决Moodle API core_user_create_users接口"Missing required key in single structure: users"错误
可能的原因及解决方案
1. 未正确设置请求头Content-Type
Moodle的JSON格式REST API要求请求头必须包含Content-Type: application/json。如果没有设置这个头,服务器无法识别请求体的JSON格式,会导致无法解析users字段。
- 操作:在请求中添加该请求头,确保值为
application/json。
2. 请求体传递方式错误
Moodle REST API对POST请求的参数传递有两种兼容方式,若传递方式不匹配会导致参数识别失败:
- 方式一(推荐):使用raw JSON请求体。确保请求方式为POST,Content-Type已正确设置,请求体为你提供的完整JSON结构。
- 方式二:使用表单参数传递。将
users作为表单字段名,字段值为用户数组的JSON字符串,示例:
这种方式无需设置users: [{"username":"zezaoteste123","password":"Segura5678!","firstname":"zezao","lastname":"teste","email":"zezao.teste@dominio.com","auth":"manual"}]application/json头,使用默认的application/x-www-form-urlencoded即可。
3. 确认API权限与配置
- 检查webservice token是否拥有
core_user_create_users接口的调用权限,可在Moodle后台「站点管理」→「插件」→「Web服务」→「已授权的用户」中查看权限分配。 - 确认Moodle站点已启用REST协议,在「Web服务」→「协议」中检查REST是否处于启用状态。
测试示例(curl命令)
raw JSON方式:
curl -X POST \ http://url/webservice/rest/server.php?wstoken=token&wsfunction=core_user_create_users&moodlewsrestformat=json \ -H 'Content-Type: application/json' \ -d '{ "users": [ { "username": "zezaoteste123", "password": "Segura5678!", "firstname": "zezao", "lastname": "teste", "email": "zezao.teste@dominio.com", "auth": "manual" } ] }'
表单参数方式:
curl -X POST \ http://url/webservice/rest/server.php?wstoken=token&wsfunction=core_user_create_users&moodlewsrestformat=json \ -d 'users=[{"username":"zezaoteste123","password":"Segura5678!","firstname":"zezao","lastname":"teste","email":"zezao.teste@dominio.com","auth":"manual"}]'
内容的提问来源于stack exchange,提问作者José Pontes
相关产品推荐
相关产品推荐

