0

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!

6
  • I have also tried request.data() and request.json() to little success. Dec 26, 2019 at 21:41
  • To confirm, have you tried printing request.json?
    – turnip
    Dec 26, 2019 at 21:54
  • Did you try with request.data.decode() ?
    – SunPaz
    Dec 26, 2019 at 21:55
  • @user1579970 I have just tried running your example and I see get no issues. Where are you seeing "Invalid character in attribute name"?
    – turnip
    Dec 26, 2019 at 21:59
  • request.json gives "null". request.data.decode() gives ""{\n \"test\":\"Hello World\"\n}"", which indicates it's received the JSON object into data. I guess I could hardcode a way to extract the data from .decode(), but not ideal. Now quite interested in why data alone or get_json() do not work. Dec 26, 2019 at 21:59

2 Answers 2

1

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...

0

I suspect you are not sending the payload as JSON from Postman.

It should look like this:

enter image description here

Then when you do request.json in your Flask app you should see the JSON. Note that it is not request.json()

1
  • Thanks, turnip, the odd thing is that I am. I made absolutely sure of this before posting. Will keep fiddling and report back if I find something.... Dec 26, 2019 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.