Flask-RESTful POST/PUT请求报错:未加载JSON数据问题排查
问题解决指南
1. 先修正curl命令的格式错误
你遇到的curl: (6) Could not resolve host: application是因为请求头的格式写错了。Shell会把Content-Type: application/json里的空格当成参数分隔符,误将application识别为要访问的主机名。正确的curl命令需要把整个请求头用引号包裹:
# 发送JSON格式请求的正确命令 curl -X POST http://localhost:5000/your-api-endpoint \ -H "Content-Type: application/json" \ -d '{"username": "test", "password": "123456"}'
如果要发送application/x-www-form-urlencoded格式的数据,命令应为:
curl -X POST http://localhost:5000/your-api-endpoint \ -d "username=test&password=123456"
2. 让Flask-RESTful支持表单或JSON数据
Flask-RESTful默认只从JSON请求体中解析参数,这就是你发送表单数据返回400错误的原因。解决这个问题需要在参数解析时明确指定参数来源:
情况1:只处理表单数据(application/x-www-form-urlencoded)
在资源类中,给reqparse.add_argument添加location='form'参数:
from flask import Flask from flask_restful import Api, Resource, reqparse app = Flask(__name__) api = Api(app) class YourResource(Resource): def post(self): parser = reqparse.RequestParser() # 明确指定从表单中获取参数 parser.add_argument('username', required=True, location='form') parser.add_argument('password', required=True, location='form') args = parser.parse_args() # 后续业务逻辑 return {"message": f"Hello {args['username']}"}, 201 api.add_resource(YourResource, '/your-api-endpoint') if __name__ == '__main__': app.run(debug=True)
情况2:同时支持JSON和表单数据
如果想让接口兼容两种格式,把location设为列表['json', 'form'],解析器会优先从JSON中取参数,找不到再从表单中获取:
parser.add_argument('username', required=True, location=['json', 'form']) parser.add_argument('password', required=True, location=['json', 'form'])
3. 额外注意事项
- 你的Flask-RESTful版本0.3.9中,
reqparse模块是稳定可用的,无需修改核心API写法。 - 开启Flask的
DEBUG模式时,注意避免自动重载导致的缓存问题。 - 发送JSON数据时,务必保证格式合法(如字符串用双引号、逗号分隔正确),否则也会返回400错误。
内容的提问来源于stack exchange,提问作者Chuck
相关产品推荐
相关产品推荐

