Flask-restful API不接受JSON。

4
我正在尝试学习如何编写API。我按照书上的内容一字不漏地复制了所有的代码,但是我却无法将数据提交到API。我试着在一个名为Postman的JSON提交工具中,将{'name':'holy'}作为原始数据提交到API,但是我得到了验证错误消息“未提供名称”。但是当我尝试 name=holy 时它却可以正常工作。我以为它不应该这样工作,请问怎样才能让它与{'name':'holy'}一同工作?
from flask import Flask, request,render_template, jsonify
from flask_restful import Resource, Api,marshal_with, fields, reqparse

app = Flask(__name__)
api = Api(app)


class UserApi(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument(
            'name',
            required=True,
            help='No name provided',
            location=['form', 'json']
        )

    def get(self):
        return jsonify ({"first_name":"Holy","last_name": "Johnson"})

    def post(self):
        args = self.reqparse.parse_args()
        return jsonify ({"first_name":"Holy","last_name": "Johnson"})



api.add_resource(UserApi, '/users')

if __name__ == '__main__':
    app.run(debug=True)
1个回答

5
你的代码应该是可行的 - 你必须指定请求头Content-Type:application/json。原因是flask-restfulreqparse模块试图从它从flask.request.json接受的数据中解析数据,只有在设置了Content-Type:application/json时才会设置该数据。
如果你可以访问curl(或wget),则可以执行以下操作进行测试:
$shell> curl -X POST -H "Content-Type: application/json" -d '{"name": "holly"}' http://localhost:5000/users
{
  "first_name": "Holy",
  "last_name": "Johnson"
}

在Postman中,你可以设置一个头部(header),就像下面的截图所示。 enter image description here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接