Search code examples
pythonflaskconnexion

Python Connexion — Control "Type" Key in 400 Response Errors


I'm using connexion, a python library for REST API's, with a swagger definition. It's working properly for the actual requests, but when there is an error condition, such as validation fails, it returns a response like:

{
  "type": "about:blank",
  "title": "Bad Request",
  "status": 400,
  "detail": "None is not of type 'string'"
} 

The title, status and detail all are good and make sense, but is there a way for me to control the type key's value so that I can provide more helpful information rather than simply having about:blank in there?

Under the hood, it appears that connexion uses requests and flask, so maybe there is something I can leverage from them?


Solution

  • I have never worked with the underlying framework, but with a quick scan, the module exposes the Flask application constructor. With that, you can define a new app with your swagger file as

    app = connexion.App(__name__, specification_dir='swagger/')
    

    and then add custom error handlers. For example for the 400 error you can do

    from flask import jsonify
    
    @app.errorhandler(400)
    def page_not_found(e):
        custom_data = {
            'type': 'Advanced type'
            # etc
        }
        return jsonify(custom_data)
    

    Read more about Flask Error handlers here