pythonjsonflask

Ensure the POST data is valid JSON


I am developping a JSON API with Python Flask.
What I want is to always return JSON, with a error message indicating any error that occured.

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.

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

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

I've read about adding decorator to request to do that, but no comprehensive example.


Solution

  • You have three options:

    Personally, I'd probably go with the second option:

    from werkzeug.exceptions import BadRequest
    from flask import json, Request, current_app
    
    
    class JSONBadRequest(BadRequest):
        def get_body(self, environ=None):
            """Get the JSON body."""
            return json.dumps({
                'code':         self.code,
                'name':         self.name,
                'description':  self.description,
            })
    
        def get_headers(self, environ=None):
            """Get a list of headers."""
            return [('Content-Type', 'application/json')]
    
    
    def on_json_loading_failed(self, e: ValueError | None):
        if e is None:
            # wrong mime-type, defer to the default implementation to raise
            # UnsupportedMediaType().
            super().on_json_loading_failed(e)
        if current_app and current_app.debug:
            raise JSONBadRequest(f"Failed to decode JSON object: {e}")
        raise JSONBadRequest()
    
    
    Request.on_json_loading_failed = on_json_loading_failed
    

    Now, every time request.get_json() fails, it'll call your custom on_json_loading_failed method and raise an exception with a JSON payload rather than a HTML payload.