Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask RESTful POST JSON fails

I have a problem posting JSON via curl from cmd (Windows7) to Flask RESTful. This is what I post:

curl.exe -i -H "Content-Type: application/json" \
 -H "Accept: application/json" -X POST \
 -d '{"Hello":"Karl"}' http://example.net:5000/

It results in a bad request, also I don't know how to debug this, normally I would print out information to console, but this doesn't work. How do you debug wsgi apps? Seems like a hopeless task...

This is my simple test app as seen on the net:

from flask import Flask, request
from flask.ext.restful import Resource, Api

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

class Test(Resource):
    def post(self):
        #printing request.data works
        json_data = request.get_json(force=True) # this issues Bad request
        # request.json also does not work
        return {}

api.add_resource(Test, '/')

if __name__ == '__main__':
    app.run(debug=True)
like image 703
neonbarbarian Avatar asked Mar 08 '14 18:03

neonbarbarian


People also ask

How to get json data from POST request in Flask?

You need to set the request content type to application/json for the . json property and . get_json() method (with no arguments) to work as either will produce None otherwise.

Is Flask RESTful deprecated?

The whole request parser part of Flask-RESTful is slated for removal and will be replaced by documentation on how to integrate with other packages that do the input/output stuff better (such as marshmallow). This means that it will be maintained until 2.0 but consider it deprecated.

Does Flask return JSON?

jsonify() is a helper method provided by Flask to properly return JSON data.


1 Answers

-d '{"Hello":"Karl"}' doesn't work from windows as its surrounded by single quotes. Use double quotes around and it will work for you.

-d "{\"Hello\":\"Karl\"}"
like image 176
Sabuj Hassan Avatar answered Oct 06 '22 17:10

Sabuj Hassan