Ensure the POST data is valid JSON
<p>I am developping a JSON API with Python Flask.<br>
What I want is to always return JSON, with a error message indicating any error that occured.</p>

<p>That API also only accept JSON data in the POST body, but Flask by default return a HTML error 400 if it can't read the data as JSON.</p>

<p>Preferably, I d also like to not force the user to send the <code>Content-Type</code> header, and if <code>raw</code> or <code>text</code> content-type, try to parse the body as JSON nonetheless.</p>

<p>In short, I need a way to validate that the POST body's is JSON, and handle the error myself.</p>

<p>I've read about adding decorator to <code>request</code> to do that, but no comprehensive example.</p>

<p>Combining the options <code>force=True</code> and <code>silent=True</code> make the result of <code>request.get_json</code> be <code>None</code> if the data is not parsable, then a simple <code>if</code> allow you to check the parsing.</p>

<pre><code>from flask import Flask
from flask import request

@app.route('/foo', methods=['POST'])
def function(function = None):
    print "Data: ", request.get_json(force = True, silent = True);
    if request.get_json() is not None:
        return "Is JSON";
    else:
        return "Nope";

if __name__ == "__main__":
    app.run()
</code></pre>

<p>Credits to lapinkoira and Martijn Pieters.</p>

python json flask