Flask-RESTPlus is an extension for Flask that adds support for quickly building REST APIs. It is no longer maintained and has been superseded by Flask-RESTX.
APIFlask and Flask-RESTPlus/Flask-RESTx share similar goals and features, but the implementation is different. This guide will help you migrate from Flask-RESTPlus/Flask-RESTX to APIFlask.
APIFlask uses marshmallow to define data schema and uses api.input for request parsing.
fromapiflaskimportSchemafromapiflask.fieldsimportInteger,StringclassUser(Schema):name=String(required=True)age=Integer(required=True)@app.get('/')@app.input(User,location='json')defcreate_user(json_data):# the arg name defaults to the `<location_name>_data`pass
You can also import the Schema, Integer, and String from marshmallow directly.
{"message":"The browser (or proxy) sent a request that this server could not understand.","custom":"value"}
To document the error response, you can use the :raises annotation in the docstring.
@api.route('/test/')classTestResource(Resource):defget(self):''' Do something :raises CustomException: In case of something '''pass
APIFlask also automatically handles errors and returns a JSON response with the error message.
{"message":"The browser (or proxy) sent a request that this server could not understand.","detail":{}}
To add custom fields, define a custom exception class that inherits from HTTPException:
fromapiflaskimportHTTPErrorclassPetNotFound(HTTPError):status_code=404message='This pet is missing.'extra_data={'error_code':'2323','error_docs':'https://example.com/docs/missing'}
or use apiflask.abort with extra_data argument:
abort(400,message='Something is wrong...',extra_data={'docs':'http://example.com','error_code':1234})
output:
{"message":"Something is wrong...","detail":{},"docs":"http://example.com","error_code":1234}
To document the error response, you can use the app.doc decorator: