apierrors.rst
This file
Path
docs/patterns/apierrors.rst
63 lines · 2.1 KiB
Last changed by
Merge pull request #890 from seancron/documentation-fixDaniel Neuhäuserbefore adoption4212e67
History of this fileTake it
Added documentation on API error handlersArmin Ronacherbefore adoptionf9f8180
lines 1–21why, one step back1Implementing API Exceptions2===========================34It's very common to implement RESTful APIs on top of Flask. One of the5first thing that developers run into is the realization that the builtin6exceptions are not expressive enough for APIs and that the content type of7``text/html`` they are emitting is not very useful for API consumers.89The better solution than using ``abort`` to signal errors for invalid API10usage is to implement your own exception type and install an error handler11for it that produces the errors in the format the user is expecting.1213Simple Exception Class14----------------------1516The basic idea is to introduce a new exception that can take a proper17human readable message, a status code for the error and some optional18payload to give more context for the error.1920This is a simple example::21Fixed a typoArmin Ronacherbefore adoption335cbe0
line 22why, one step back22 from flask import jsonifyAdded documentation on API error handlersArmin Ronacherbefore adoptionf9f8180
lines 23–49why, one step back2324 class InvalidUsage(Exception):25 status_code = 4002627 def __init__(self, message, status_code=None, payload=None):28 Exception.__init__(self)29 self.message = message30 if status_code is not None:31 self.status_code = status_code32 self.payload = payload3334 def to_dict(self):35 rv = dict(self.payload or ())36 rv['message'] = self.message37 return rv3839A view can now raise that exception with an error message. Additionally40some extra payload can be provided as a dictionary through the `payload`41parameter.4243Registering an Error Handler44----------------------------4546At that point views can raise that error, but it would immediately result47in an internal server error. The reason for this is that there is no48handler registered for this error class. That however is easy to add::49Merge pull request #890 from seancron/documentation-fixDaniel Neuhäuserbefore adoption4212e67
line 50why, one step back50 @app.errorhandler(InvalidUsage)Added documentation on API error handlersArmin Ronacherbefore adoptionf9f8180
lines 51–63why, one step back51 def handle_invalid_usage(error):52 response = jsonify(error.to_dict())53 response.status_code = error.status_code54 return response5556Usage in Views57--------------5859Here is how a view can use that functionality::6061 @app.route('/foo')62 def get_foo():63 raise InvalidUsage('This view is gone', status_code=410)