diff --git a/docs/patterns/errorpages.rst b/docs/patterns/errorpages.rst index 1df9c061..7e43674c 100644 --- a/docs/patterns/errorpages.rst +++ b/docs/patterns/errorpages.rst @@ -97,3 +97,29 @@ An example template might be this:

What you were looking for is just not there.

go somewhere nice {% endblock %} + + +Returning API errors as JSON +---------------------------- + +When using Flask for web APIs, you can use the same techniques as above +to return JSON responses to API errors. :func:`~flask.abort` is called +with a ``description`` parameter. The :meth:`~flask.errorhandler` will +use that as the JSON error message, and set the status code to 404. + +.. code-block:: python + + from flask import abort, jsonify + + @app.errorhandler(404) + def resource_not_found(e): + return jsonify(error=str(e)), 404 + + @app.route("/cheese") + def get_one_cheese(): + resource = get_resource() + + if resource is None: + abort(404, description="Resource not found") + + return jsonify(resource)