Flask RESTful POST JSON fails

2019-03-20 19:31发布

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)

3条回答
Root(大扎)
2楼-- · 2019-03-20 20:12

To add-on to the previous two answers, you do not need to escape the quotes across all OS's, following this syntax will work just fine on Mac/Linux:

-d '{"Hello":"Karl"}'
查看更多
Juvenile、少年°
3楼-- · 2019-03-20 20:15

I just want to point out that you need to escape regardless of OS - and regardless if you have double quotes around the request data - I saw this post and didn't think it was the answer to my issue because I had double quotes around the request data and single quotes inside:

This won't work:

-d "{'Hello': 'Karl'}"

This will:

-d "{\"Hello\":\"Karl\"}"

Again, you need to escape the quotes regardless of OS (I'm on Mac) and regardless of whether you have single or double quotes

And thanks Sabuj Hassan for your answer!

查看更多
来,给爷笑一个
4楼-- · 2019-03-20 20:16

-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\"}"
查看更多
登录 后发表回答