Holly Johnson Holly Johnson - 1 year ago 161
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

as raw data in
( an json posting tool) to api and I get the vladation help message error"No Name provided":but when i try
it works fine. I thought it was not suppose to work like that, How do i get it to work with

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()
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__':

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download