A
A
AlmazKayum2020-11-22 19:46:49
Flask
AlmazKayum, 2020-11-22 19:46:49

Why does request.json return null in flask?

good time.
I am making a POST request. Actually the code.

from flask import Flask
from flask import jsonify, request
app = Flask(__name__)

@app.route('/api/func/<int:id>/', methods=['POST'])
def func(id):
    data = request.json
    return jsonify(data)

app.run(...)

The Flask web server is working properly. Get requests are OK.
When sending a POST request with data = {'data': 'some_data'} returns
data = None
I make a CURL request
curl -i -X POST -d "{'data': 'some_data'}"  http://IP:PORT/api/func/<id>/

produces such a response
5fba95811011d473045941.png
where null is just the returned data.
It should return {'data': 'some_data'}
What am I doing wrong?

UPD. with a PUT request the same story, request.json is empty.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2020-11-22
@AlmazKayum

Everything is ok, the problem is in the cURL request itself
Set the content-type to JSON
-H "Content-Type: application/json"
Plus, as it seems to me, not a curl expert, but it would be better to wrap JSON in a single quote, and wrap all the data inside in a double quote, since a single quote is not correct in JSON .
In theory, this is how it should work on Linux.

curl -i -X POST -d '{"data": "some_data"}' -H "Content-Type: application/json" http://127.0.0.1:5000/api/func/1/

Windows will swear at such a decision because of the quotes, they will need to be escaped
If the curl is not fundamental, you can use Postman, IMHO, it will be more convenient
Looks like this in postman
5fba9849174aa265291377.jpeg

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question