API Reference¶
This part of the documentation covers the interfaces, classes, functions, etc. of Pyll JSON Errors. Any parts where Pyll JSON Errors depends on one of it’s optional dependencies it will be noted.
Data Models¶
Python representations of various JSON API errors objects.
See the JSON API Error Format for more information.
-
class
pyll_json_errors.models.
BaseJson
¶ Abstract class which all concrete JSON API object classes inherit.
-
abstract
as_dict
()¶ Converts the object into a dictionary containing only Python primitives. Must be implemented by concrete subclasses.
- Returns
Dictionary representation of objects containing only Python primitives.
- Return type
dict
-
serialized
()¶ Get object as stringified JSON.
- Returns
The object as stringified JSON.
- Return type
str
-
abstract
-
class
pyll_json_errors.models.
JsonError
(*, id=None, status=None, code=None, title=None, detail=None, source=None, meta=None)¶ Represents a single JSON error object.
- Parameters
id (str, optional) – A unique identifier for this particular occurrence of the problem.
status (str, optional) – The HTTP status code applicable to this problem, expressed as a string value.
code (str, optional) – An application-specific error code, expressed as a string value.
title (str, optional) – A short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem.
detail (str, optional) – A human-readable explanation specific to this occurrence of the problem.
source (JsonErrorSourceParameter or JsonErrorSourcePointer, optional) – An object containing references to the source of the error.
meta (BaseJson or dict, optional) – Non-standard meta-information about the error.
- Raises
TypeError – Raised if
source
ormeta
are not the expected types.
-
as_dict
()¶ Converts the object into a dictionary containing only Python primitives. Resulting dictionary will only contain keys with values, there will not be any keys with a value of
None
.- Returns
Dictionary representation of objects containing only Python primitives.
- Return type
dict
-
class
pyll_json_errors.models.
JsonErrorArray
(errors=[])¶ Representation of multiple
JsonError
objects.Manages various attributes of the top level “errors” JSON API object.
- Parameters
errors (list) – A list of
JsonError
objects.fallback_status (int) – The fallback HTTP status code to use for HTTP responses if one cannot be derived from provided errors. Defaults to 400.
override_status (int, optional) – If set, this value will always be returned as the status.
-
as_dict
()¶ Converts the object into a dictionary containing only Python primitives. Must be implemented by concrete subclasses.
- Returns
Dictionary representation of objects containing only Python primitives.
- Return type
dict
-
property
status
¶ Get the HTTP status code that represents the collection of
JsonErrors
as a whole.If
override_status
is set, that is returned. Else, try to derive the status fromerrors
. If there is only one error, return that error’s status, else return the highest status of all errors, rounded down to the nearest 100th. If that does not result in a value,fallback_status
is returned.- Returns
The HTTP status code.
- Return type
int
-
class
pyll_json_errors.models.
JsonErrorSourceParameter
(*, parameter)¶ Represents a parameter type JSON API error
source
object.- Parameters
parameter (str) – The name of the query parameter causing the issue.
-
as_dict
()¶ Converts the object into a dictionary containing only Python primitives. Must be implemented by concrete subclasses.
- Returns
Dictionary representation of objects containing only Python primitives.
- Return type
dict
-
class
pyll_json_errors.models.
JsonErrorSourcePointer
(*, keys)¶ Represents a pointer type JSON API error
source
object.Notes
See documentation for
pyll_json_errors.utils.flatten_dict
for more information and example keys.- Parameters
keys (tuple) – An tuple of strings which represents the path of the error in some object.
Example
{ "one": { "two": ["some error"] } "list": [ { "error": "hello world" }, { "error": "foobar" } ] } # "some error"'s keys would be ("one", "two") # "hello world"'s keys would be ("list", "0", "error") # "foobar"'s keys would be ("list", "1", "error")
-
as_dict
()¶ Converts the object into a dictionary containing only Python primitives. Must be implemented by concrete subclasses.
- Returns
Dictionary representation of objects containing only Python primitives.
- Return type
dict
-
property
pointer
¶ Get the final JSON pointer representation of the keys.
- Returns
The final stringified pointer.
- Return type
str
Example
JsonErrorSourcePointer(keys=("one", "two", "three")).pointer # "/one/two/three"
Exceptions¶
Pyll JSON Errors exception classes.
This module holds all of the custom exceptions raise by the package.
-
exception
pyll_json_errors.exceptions.
ConcreteJsonError
(message, json_errors)¶ An exception containing JSON error objects.
Convenient for raising an exception and using attached errors for some further processing.
- Parameters
message (str) – Exception message.
json_errors (JsonErrorArray or list) – Either a
JsonErrorArray
or a list ofJsonError
errors to attach to the exception.
- Raises
TypeError – Raised if passed
json_errors
are not the expected type.
-
exception
pyll_json_errors.exceptions.
JsonErrorException
¶ Base class for all library exceptions.
Transforms¶
Transform classes are the primary interface for converting error of any type into Pyll JSON Errors.
-
class
pyll_json_errors.transform.
BaseTransform
¶ Base abstract class which all transform classes must inherit.
When adding a new type of transform (say for a new module in
pyll_json_errors.contrib
), they should inherit from this class and implementmake_json_errors()
.-
abstract
make_json_errors
(sources)¶ Convert some source objects into a list of JsonErrors.
This method is implemented by concrete subclasses of
BaseTransform
. This method should be considered semi-private. Use it for concrete class implementation, but useto_list()
orto_array()
when performing actual transformations.- Parameters
sources (list) – A list of source error objects to convert.
- Returns
- A list of
JsonError
objects. Does not return a
- A list of
- Return type
list
-
to_array
(*, sources)¶ Transform source data into a single
JsonErrorArray
object.- Parameters
sources (list) – A list of source error objects to convert.
- Returns
A single
JsonErrorArray
object.- Return type
-
abstract
Generic Errors¶
Contains convenient functions for creating JsonErrorArray
objects
for commonly used errors.
-
pyll_json_errors.generics.
error400
(*, title='Bad Request', detail=None)¶ Create a generic JSON error with status code 400.
- Parameters
title (str, optional) – The title to associate with the error.
detail (str, optional) – The detail to associate with the error.
- Returns
A JsonErrorArray containing one error.
- Return type
-
pyll_json_errors.generics.
error403
(*, title='Forbidden', detail=None)¶ Create a generic JSON error with status code 403.
- Parameters
title (str, optional) – The title to associate with the error.
detail (str, optional) – The detail to associate with the error.
- Returns
A JsonErrorArray containing one error.
- Return type
-
pyll_json_errors.generics.
error404
(*, title='Not found', detail=None)¶ Create a generic JSON error with status code 404.
- Parameters
title (str, optional) – The title to associate with the error.
detail (str, optional) – The detail to associate with the error.
- Returns
A JsonErrorArray containing one error.
- Return type
Constants¶
Various library constants.
These values should not be changed.
-
pyll_json_errors.constants.
HEADER_CONTENT_TYPE_NAME
= 'Content-Type'¶ Name of the content type header.
- Type
str
-
pyll_json_errors.constants.
HEADER_CONTENT_TYPE_VALUE
= 'application/json'¶ Value of the content type header.
- Type
str
-
pyll_json_errors.constants.
JSON_POINTER_SEPARATOR
= '/'¶ JSON Pointer separator as described be JSON API spec.
- Type
str
Utilities¶
Helpful utility functions.
-
pyll_json_errors.utils.
flatten_dict
(*, data)¶ Flatten a nested dictionary into a tuple of tuples containing the key and value for each member of original dict.
Useful for generating JSON pointers from dictionaries. Output contains flattened keys and flattens any iterable values.
- Parameters
data (dict) – A dictionary to flatten.
- Returns
A tuple of tuples containing a tuple of str and a value.
- Return type
tuple
Example
inp = { "simpleError": "red", "simpleErrorList": ["orange", 1], "objectError": { "a": "yellow", "b": 2, "c": ["green", 3] }, 1: "blue", 2: ["purple", 4], "listedObjects": [ { "1": "lime", 2: ["maroon", 5] }, { 3: "pink", "d": ["jade", 6] } ] } outp = flatten_dict(data=inp) # outp # ( # (("simpleError",), "red"), # (("simpleErrorList",), "orange"), # (("simpleErrorList",), 1), # (("objectError", "a"), "yellow"), # (("objectError", "b"), 2), # (("objectError", "c"), "green"), # (("objectError", "c"), 3), # (("1",), "blue"), # (("2",), "purple"), # (("2",), "4"), # (("listedObjects", "0", "1"), "lime"), # (("listedObjects", "0", "2"), "maroon"), # (("listedObjects", "0", "2"), 5), # (("listedObjects", "1", "3"), "pink"), # (("listedObjects", "1", "d"), "jade"), # (("listedObjects", "1", "d"), 6), # )
Contrib Modules¶
Contains integrations for various 3rd party Python libraries.
Flask¶
Integrate Pyll JSON API errors into Flask applications.
In order to use this module, the flask
optional dependency must be installed. See Installation.
See the driver Flask app
for examples on integrating pyll_json_errors
into Flask.
-
class
pyll_json_errors.contrib.flask.
HttpExceptionTransform
¶ Transform
werkzeug.exceptions.HTTPException
objects.-
make_json_errors
(sources)¶ Transform
werkzeug.exceptions.HTTPException
objects intoJsonError
objects.- Parameters
sources (list) – A list of
werkzeug.exceptions.HTTPException
objects to transform.- Returns
A list of
JsonError
objects representing eachwerkzeug.exceptions.HTTPException
object. Returned list will be same length assources
.- Return type
list
-
-
pyll_json_errors.contrib.flask.
make_response
(*, json_errors, mimetype='application/json')¶ Create a Flask
Response
object from aJsonErrorArray
object.- Parameters
json_errors (JsonErrorArray) – The errors array to generate an HTTP response from.
mimetype (str) – The mimetype the Flask
Response
will return with.
- Returns
A Flask
Response
object which can be returned from a Flask view controller function.- Return type
-
pyll_json_errors.contrib.flask.
wrap_app
(app)¶ Wraps a
flask.Flask
application, adding various error handlers automatically.Wrapping an application provides automatic JSON API errors responses for 403 and 404 responses. It also provides automatic JSON API error responses for view controllers which raise
ConcreteJsonError
errors.- Parameters
app (flask.Flask) – The Flask object to wrap.
- Returns
None
Marshamllow¶
Integrate Pyll JSON API errors with Marshmallow validation and schemas.
In order to use this module, the marshmallow
optional dependency must be installed. See Installation.
See the driver Marshmallow app
for examples on integrating pyll_json_errors
with Marshmallow.
-
class
pyll_json_errors.contrib.marshmallow.
ValidationErrorTransform
¶ Transform
marshmallow.exceptions.ValidationError
objects.-
make_json_errors
(sources)¶ Transform
marshmallow.exceptions.ValidationError
objects.- Parameters
sources (list) – A list of Marshmallow
ValidationError
objects.- Returns
A list of
JsonError
objects representing the provided MarshmallowValidationError
. Returned list will be greater than or equal to the length ofsource
.- Return type
list
-
validation_error_status
= 400¶ HTTP status code for validation failure responses.
- Type
int
-
Django REST Framework¶
Integrate Pyll JSON API errors with Django REST Framwork applications.
In order to use this module, the rest_framework
optional dependency must be installed. See Installation.
See the driver DRF app
for examples on integrating pyll_json_errors
with DRF.
-
class
pyll_json_errors.contrib.rest_framework.
DRFTransform
¶ Transform DRF exception response data.
This transform handles any and all exceptions raised by DRF, regardless of exception type and content.
-
get_code
(status_code, pointer, error)¶ Get the code associated with this error detail.
- Parameters
status_code (int) – The status code of the error.
pointer (list) – A list of str (pointer segments) to the field which raised the initial errors.
error (rest_framework.exceptions.ErrorDetail) – The DRF-provided detail of the error.
- Returns
The code associated with this error detail.
- Return type
str
-
get_detail
(status_code, pointer, error)¶ Get the error detail.
- Parameters
status_code (int) – The status code of the error.
pointer (list) – A list of str (pointer segments) to the field which raised the initial errors.
error (rest_framework.exceptions.ErrorDetail) – The DRF-provided detail of the error.
- Returns
The detail message associated with this error.
- Return type
str
-
get_source
(status_code, pointer, error)¶ Get the pointer to the field which raised this error.
- Parameters
status_code (int) – The status code of the error.
pointer (list) – A list of str (pointer segments) to the field which raised the initial errors.
error (rest_framework.exceptions.ErrorDetail) – The DRF-provided detail of the error.
- Returns
An object which contains the pointer to the field responsible for the error.
- Return type
-
get_status_code
(status_code, pointer, error)¶ Get the status code of the error message.
- Parameters
status_code (int) – The status code of the error.
pointer (list) – A list of str (pointer segments) to the field which raised the initial errors.
error (rest_framework.exceptions.ErrorDetail) – The DRF-provided detail of the error.
- Returns
The status code to be associated with this error detail.
- Return type
int
-
get_title
(status_code, pointer, error)¶ Get the title of the error to be returned to the user.
- Parameters
status_code (int) – The status code of the error.
pointer (list) – A list of str (pointer segments) to the field which raised the initial errors.
error (rest_framework.exceptions.ErrorDetail) – The DRF-provided detail of the error.
- Returns
The title of the message.
- Return type
str
-
make_error_dict
(status_code, pointer, error)¶ Get the entire error detail in a JSON API compatible object.
- Parameters
status_code (int) – The status code of the error.
pointer (list) – A list of str (pointer segments) to the field which raised the initial errors.
error (rest_framework.exceptions.ErrorDetail) – The DRF-provided detail string of the error.
- Returns
Dictionary as a
JsonError
.- Return type
-
make_json_errors
(sources)¶ Transform Django REST Framework errors into models.JsonError objects.
- Parameters
sources (list) – A list of DRF APIException objects.
- Returns
A list of
JsonError
objects representing errors raised by DRF.- Return type
list
-
-
pyll_json_errors.contrib.rest_framework.
make_response
(error_array)¶ Format a list of errors into a DRF response object.
- Parameters
error_array (JsonErrorArray) – The array of errors to be formatted into the response.
- Returns
A DRF response containing the formatted errors which can be returned to the user.
- Return type
-
pyll_json_errors.contrib.rest_framework.
reformat_response
(exc, context)¶ Reformat the error response data provided by base Django.
This method should be called from within a custom error handler implemented by the user. See Custom Exception Handling for more information. This method can also be called directly as a custom exception handler.
- Parameters
exc (rest_framwork.exceptions.APIException) – The exception that caused this errors response to be returned.
context (dict) – A dictonary of additional details passed from the rest framework.
- Returns
A DRF response formatted in the JSON api spec.
- Return type