Python + Flask: Correct way to validate that json POST request is non-empty
Just check if request.data
is present, if(request.data): ...continue
Herr Derb
Updated on July 06, 2022Comments
-
Herr Derb almost 2 years
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
-
Dolf Andringa about 9 yearsthis could fail if request.data = 0 for instance, which also evaluates as false. Maybe better would be if hasattr(request,'data'):
-
Herr Derb about 9 yearsI just gave it a try with "0". It accually gives a true. In the end, it gets caught with the scheme comparisson.
-
raj.andy1 over 3 yearsThis did not work for me :( I still get the same behavior. Not sure if there is a better way