Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 968
Herr Derb Avatar asked Mar 30 '15 12:03

Herr Derb


1 Answers

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

like image 135
akshay Avatar answered Sep 23 '22 22:09

akshay