From the jsonapi documentation:
Error objects provide additional information about problems encountered while performing an operation. Error objects MUST be returned as an array keyed by errors in the top level of a JSON API document.
To return jsonapi compatible error objects in flask-rest-jsonapi, one must raise an exception and an appropriate error message will be shown depending on the type of exception specified.
Following is an example of how to raise a jsonapi compatible error
But the above method of raising an exception fails when working with decorators in flask-rest-jsonapi. Taking inspiration from the JsonApiException class of flask-rest-jsonapi itself, we’ll be building a custom class which can formulate jsonapi compatible error message and we can just simply return them by using make_response from flask.
In our basic class definition, we’ll define a default title and status code in case none of them is provided by the user. The default status code will be 500. Following is the code for the same:
We will be accepting the following four parameters for the initialization of an object of the said class:
- source: the source of the error in the request document
- detail: Any details about the error
- title: Title for the error
- Status: HTTP status for the error
Following is the initialisation function for the same:
We’ll be using the jsonapi_errors module to format all of these parameters into jsonapi error objects:
- Jsonapi error objects: http://jsonapi.org/format/#error-objects
- HTTP status code 500: httpstatuses.com/500
- Flask make response: http://flask.pocoo.org/docs/0.12/api/#flask.make_response