Holly Johnson Holly Johnson - 1 month ago 24
Python Question

Flask-restful API not accepting json

I am trying to learn how to do apis. I copied everything from the book exactly but i am unable to post to the api. I tried posting

{'name':'holy'}
as raw data in
postman
( an json posting tool) to api and I get the vladation help message error"No Name provided":but when i try
name=holy
it works fine. I thought it was not suppose to work like that, How do i get it to work with
{'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)

Answer

Your code should work - you have to specify the request header Content-Type: application/json. The reason why is because flask-restful's reqparse module tries to parse its data from flask.request.json, which is only set if Content-Type: application/json is set.

If you have access to curl (or wget), you can do the following to test:

$shell> curl -X POST -H "Content-Type: application/json" -d '{"name": "holly"}' http://localhost:5000/users
{
  "first_name": "Holy",
  "last_name": "Johnson"
}

In Postman, you can set a header, like shown in the screenshot below. enter image description here