Herr Derb
Herr Derb

Reputation: 5387

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

Upvotes: 11

Views: 22089

Answers (2)

Anindya Dey
Anindya Dey

Reputation: 1101

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.

Upvotes: 0

akshay
akshay

Reputation: 502

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

Upvotes: 20

Related Questions