Skip to content
Myr

Added documentation on API error handlers

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent fc2225b · Browse files · 2 files+64 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+64 added−0 removed

  • other:+64 added−0 removed

2 files+64 added−0 removed

added:docs/patterns/apierrors.rst+63 added
1Implementing 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::2122 from flask import jsonfiy2324 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::4950 @app.errorhandler(InvalidAPIUsage)51 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)
modified:docs/patterns/index.rst+1 added
17 unmodified lines
1819 packages20 appfactories21 appdispatch22 apierrors23 urlprocessors24 distribute25 fabric26 sqlite3
17 unmodified lines