Validating a JSON post request coming into a python flask app

Viewed 716

I have a simple flask app

@app.route("/endpoint/", methods=['POST'])
def mypostmethod():

    if 'Content-Type' in request.headers and request.headers['Content-Type'] == 'application/json':

        post_data = request.json

        req_data = request.get_json()

        content = req_data['content']

        return content

and I curl as follows:

curl -X POST "localhost:8080/endpoint/" -H "Content-Type: application/json" -d '{'content': 'Blah'}'

I get the following error:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Failed to decode JSON object: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)</p>

It is because, json body in cURL is using single quotes, when I use double quotes it works.

I was wondering, how can I add some code in my flask app to check this error and return a custom response code and some response message? Where do I add the try block? Can you please use my code as example.

3 Answers

I'm not very experienced with JSONs, but I would try something like this:

Data you got are (I guess) in request.json.

As this is error you got - Failed to decode JSON object: Expecting property name enclosed in double quotes, I would maybe do

include json

try:
 json.dumps(request.json)
except JSONDecodeError as e:
 return("wrong request data")

JSONDecodeError is mentioned in json library documentation here

Use double quotes in your json:

curl -X POST "localhost:8080/endpoint/" -H "Content-Type: application/json" -d '{"content": "Blah"}'

This is simply not a valid argument for the -d option in cURL. You need to replace the single quotes with the double quotes in the argument and enclose it with single quotes.

wrong: '{'content': 'Blah'}'
ok:    '{"content": "Blah"}'
Related