31

I setup a very simple post route in flask like this:

from flask import Flask, request app = Flask(__name__) @app.route('/post', methods=['POST']) def post_route(): if request.method == 'POST': data = request.get_json() print('Data Received: "{data}"'.format(data=data)) return "Request Processed.\n" app.run() 

This is the curl request I am trying to send from the command-line:

curl localhost:5000/post -d '{"foo": "bar"}' 

But still, it prints out 'Data Received: "None"'. So, it doesn't recognize the JSON I passed it.

Is it necessary to specify the json format in this case?

0

1 Answer 1

31

According to the get_json docs:

[..] function will return None if the mimetype is not application/json but this can be overridden by the force parameter.

So, either specify the mimetype of the incoming request to be application/json:

curl localhost:5000/post -d '{"foo": "bar"}' -H 'Content-Type: application/json' 

or force JSON decoding with force=True:

data = request.get_json(force=True) 

If running this on Windows (cmd.exe, not PowerShell), you'll also need to change the quoting of your JSON data, from single quotes to double quotes:

curl localhost:5000/post -d "{\"foo\": \"bar\"}" -H 'Content-Type: application/json' 
Sign up to request clarification or add additional context in comments.

13 Comments

Still not working, unfortunately.
Have you seen the edit of question? I thought you had a typo, but maybe that was also an error in your code. Check your print line uses format: print('Data Received: "{data}"'.format(data=data)).
What version of flask/curl do you use? On what platform?
I fixed it. I guess it's a Windows specific problem with the double quotes. curl localhost:5000/post -d "{\"foo\": \"bar\"}" -H "Content-Type: application/json" works just fine.
@user305883, request.form contains form values. When you use JSON body encoding, that's not form. See an intro to forms here.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.