I have written a Flask
application that provides an API. I am using the RESTplus
library.
I use a model to format the data. If a request is successful, the values are inserted into the model and the model is returned.
However, if the request is unsuccessful, the model is returned and all values are null
. My goal is to return a user-defined error message with multiple key-value pairs. The error message should have a different structure than as Model.
Here is a minimal example:
from flask import Flask
from flask_restplus import Resource, fields, Api
app = Flask(__name__)
api = Api()
api.init_app(app)
books = {'1': {"id": 1, "title": "Learning JavaScript Design Patterns", 'author': "Addy Osmani"},
'2': {"id": 2, "title": "Speaking JavaScript", "author": "Axel Rauschmayer"}}
book_model = api.model('Book', {
'id': fields.String(),
'title': fields.String(),
'author': fields.String(),
})
@api.route('/books/<id>')
class ApiBook(Resource):
@api.marshal_with(book_model)
def get(self, id):
try:
return books[id]
except KeyError as e:
return {'message': 'Id does not exist'}
if __name__ == '__main__':
app.run()
Successful output
curl -X GET "http://127.0.0.1:5000/books/1" -H "accept: application/json"
{
"id": "1",
"title": "Learning JavaScript Design Patterns",
"author": "Addy Osmani"
}
Erroneous output
curl -X GET "http://127.0.0.1:5000/books/3" -H "accept: application/json"
{
"id": null,
"title": null,
"author": null
}
Is it possible to have a user-defined error message next to a model? Is there an alternative?