Python + Flask: Correct way to validate that json POST request is non-empty
Asked Answered
A

2

11

First off all, I'm very new to python. For a little project I have to implement a websevice, that can recieve a json as content. I did implement this with the flask library and it works fine so far. The only problem I have now, is the error handeling. I do check for the right content-type and I compare the recieved json with a scheme. If the request fails those checks, I'm sending a custom 400 response (raise FailedRequest). The problem I have now is, that I couldn't figure out, how to check if the request.json is empty. Right now, when I send a request with the correct content-type but empty content I'll get a system generated "bad request" as response instead of my custom one. How can I check if the request.json object is empty? request.json is None didn't work....

Or am I doing the whole validation the wrong way?

    #invoked method on a POST request
@app.route('/',methods = ['POST'])
def add():
    """
    This function is mapped to the POST request of the REST interface
    """
    print ("incoming POST")
    #check if a JSON object is declared in the header

    if request.headers['Content-Type'] == 'application/json; charset=UTF-8':
        print ("passed contentType check")
        print ("Json not none")
        print (request.get_json())
        data = json.dumps(request.json)
        #check if recieved JSON object is valid according to the scheme
        if (validateJSON(data)):
            saveToMongo(data)
            return "JSON Message saved in MongoDB"

    raise FailedRequest
Attlee answered 30/3, 2015 at 12:22 Comment(2)
can this request.get_json() == {} ?Grishilde
if(request.data): ... should workShanaeshanahan
S
19

Just check if request.data is present, if(request.data): ...continue

Shanaeshanahan answered 30/3, 2015 at 12:30 Comment(3)
this could fail if request.data = 0 for instance, which also evaluates as false. Maybe better would be if hasattr(request,'data'):Dollfuss
I just gave it a try with "0". It accually gives a true. In the end, it gets caught with the scheme comparisson.Attlee
This did not work for me :( I still get the same behavior. Not sure if there is a better wayGynarchy
A
0

If you want to check whether the incoming payload (that is request.data in terms of Flask API) is empty, then you could try checking if the request.content_length is 0. This maps to the Content-Length header, which denotes the size of the payload, something like this:

if request.content_length > 0:
  # do something
else:
  # return error

Here is the official Flask API link to know more about the request.content_length property.

Aleut answered 6/3 at 10:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.