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>You can try to decode JSON object using python json library. 
The main idea is to take plain request body and try to convert to JSON.E.g:</p>

<pre><code>import json
...
# somewhere in view
def view():
    try:
        json.loads(request.get_data())
    except ValueError:
        # not a JSON! return error
        return {'error': '...'}
    # do plain stuff
</code></pre>

python json flask