Reputation: 379
I have tried to find similar questions (or documentation) with little success, so I would be very grateful if somebody could point me in the direction of where I have gone wrong here.
In Python 3, I have used Flask to receive HTTP requests for JSON and return them.
from flask import Flask, request
app=Flask(__name__, template_folder='')
@app.route('/json', methods=['POST'])
def json():
return format(request)
I am using Postman to POST the following to 127.0.0.1/json (to confirm: 127.0.0.1/json works perfectly well if I just ask it to return "Hello World"):
{
"test":"Hello World"
}
Then Postman responds with:
<Request 'http://127.0.0.1:5000/json' [POST]>
So far, so good. But it reports there is an "Invalid character in attribute name".
Furthermore, when I change the Python script to:
from flask import Flask, request
app=Flask(__name__, template_folder='')
@app.route('/json', methods=['POST'])
def json():
return format(request.get_json())
The script returns "None" to Postman, despite a JSON object being POST'ed' to it.
Thanks very much to anyone who can clarify this for me. I usually try to debug myself, but this has had me really stumped for a few hours. I am sure I am doing something really stupid! Thanks a lot!
Upvotes: 0
Views: 995
Reputation: 379
OK, for whatever reason the JSON object was not being parsed as 'application/json', I fixed this problem:
return format(request.get_json(force=True))
the argument force=True will process the JSON anyhow.
Thank you very much everybody for your help! Hope this helps somebody else who's a bit confused...
Upvotes: 1
Reputation: 2346
I suspect you are not sending the payload as JSON from Postman.
It should look like this:
Then when you do request.json
in your Flask app you should see the JSON. Note that it is not request.json()
Upvotes: 0