Package: drf-rfc7807-exceptions
Django Rest Framework RFC7807 ExceptionsWhat is this?A library forDjango Rest Frameworkreturning consistent and easy-to-parse error messages.This library was built withRFC7807guidelines in mind, but with a small twist: it defines a "problem detail" as alistbut it still serves as a way to include errors in a predictable and easy-to-parse format for any API consumer.This library was designed to be used by anyone, therefore all of the advanced RFC7807 "problem detail" components are optional.
Errors, on the other hand, are always formatted with RFC7807 keywords and DRF exception data.N.B.This is still in the works, and the ability to raise RFC7870-like errors will be added in the near future.Table of ContentsInstallationUsageException HandlerExample JSON Error ResponsesSettingsCAMELIZEEXTRA_HANDLERSFIELDS_SEPARATORTestingSupportContributingInstallationInstall using the command line:pip install drf-rfc7807-exceptionsUsageException HandlerAddEXCEPTION_HANDLERin yourREST_FRAMEWORKsettings of your Django project settings file:REST_FRAMEWORK={# ..."EXCEPTION_HANDLER":"drf_rfc7807_exceptions.exception_handler",}Example JSON Error ResponsesField validation errors{"title":"Error message.","invalid_params":[{"name":"field_name","reason":["error",...]},...]}Non-fields validation errors{"title":"Error message.","detail":["error",...]}Other bad requests with no detail{"title":"Error message."}RFC7807 errorsComing soon...SettingsDefault available settings:DRF_RFC7807_EXCEPTIONS={"CAMELIZE":False,"EXTRA_HANDLERS":[],"FIELDS_SEPARATOR":".",}CAMELIZECamel case support for Django Rest Framework exceptions JSON error responses.IfCAMELIZEis set toTrue:{"title":"Error message.","invalidParams":[{"name":"fieldName","reason":["error",...]}...]}EXTRA_HANDLERSSupport for exceptions that differ from the standard structure of the Django Rest Framework.For instance, you may want to specify you own exception:classAuthenticationFailed(exceptions.AuthenticationFailed):def__init__(self,detail=None,code=None):"""Builds a detail dictionary for the error to give more informationto API users."""detail_dict={"detail":self.default_detail,"code":self.default_code}ifisinstance(detail,dict):detail_dict.update(detail)elifdetailisnotNone:detail_dict["detail"]=detailifcodeisnotNone:detail_dict["code"]=codesuper().__init__(detail_dict)Use exception in code:defmy_func():raiseAuthenticationFailed({"detail":_("Error message."),"messages":[{"metadata":"metadata_data","type":"type_name","message":"error message",}],})This will result in:AuthenticationFailed({"detail":"Error message.","messages":[{"metadata":"metadata_data","type":"type_name","message":"error message",}],})You can handle this by creating ahandlers.pyfile and specifying an handler for your use case:defhandle_exc_custom_authentication_failed(exc):frompath.to.my.exceptionsimportAuthenticationFailedifisinstance(exc,AuthenticationFailed):try:exc.detail=exc.detail["messages"][0]["message"]except(KeyError,IndexError):exc.detail=exc.detail["detail"]returnexcThen add it to theEXTRA_HANDLERSlist in this package settings:DRF_RFC7807_EXCEPTIONS={"EXTRA_HANDLERS":["path.to.my.handlers.handle_exc_custom_authentication_failed",# ...]}FIELDS_SEPARATORSupport for nested dicts containing multiple fields to be flattened.IfFIELDS_SEPARATORis set to.:{"field1":{"field2":"value"}}Will result in:{"field1.field2":"value"}TestingUsing tox (recommended)toxUsing poetryInstall dependencies:make installorpoetry install -vRun tests:make testorpoetry run pytest test_projectSupportPleaseopen an issue.ContributingPlease use theGithub Flow. In a nutshell, create a branch, commit your code, and open a pull request.