简体   繁体   中英

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?

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

I went through this problem also by imputing null to some model property. If you do not want to create an error handler just add the tag x-nullable: true in the property that the validation is occurring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM