DRF: Customising Exception Messages from the API - django

I'm starting to dive into DRF a little deeper of late, and I was wondering I would like to start customising the error messaging that gets return via the API for incorrect permissions, I'd like to wrap a little extra detail.
For example, if authentication credentials were not provided for an endpoint that is permission restricted, the API returns:
{
"detail": "Authentication credentials were not provided."
}
Which comes from line 171 from the rest_framework.exceptions: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py. Really, I'd like this to be consistent with the
{
"success": false,
"message": "Authentication credentials were not provided.",
"data": null
}
So, I assume I now need to begin customising my own exceptions.
How best should I go about doing this?
Perhaps it has some tie in with default_error_messages = {} inside the serializer ...

You can override DRF's default exception handler and JSON parser on your settings.py:
REST_FRAMEWORK = {
...
'EXCEPTION_HANDLER': 'helpers.exceptions.custom_exception_handler',
'DEFAULT_RENDERER_CLASSES': [
'helpers.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
]
}
And then it's just a matter of customizing how to handle your exceptions and how to render the responses:
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Customize your exception handling here
return response
And you can use the custom JSON renderer in case you need to do any extra formatting on the response, in my case I had to add a "status_code" to the payload:
class JSONRenderer(BaseJsonRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Render `data` into JSON, returning a bytestring.
"""
<Base code from the original class...>
response = renderer_context.get('response')
if response and 200 <= response.status_code <= 299 and 'status_code' not in response.data:
response.data = Errors.success(response.data)
<Base code from the original class...>
My Errors.success(response.data) was just a simpler way to merge the success status code to the data.

There is a decorator solution that creates custom Response on each type of your exceptions:
# project/api/exceptions.py
from functools import wraps
from rest_framework import status
def handle_exceptions(func):
#wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except AuthCredentialsError as exc:
return Response(
{"message": exc.message},
status=status.HTTP_405_METHOD_NOT_ALLOWED,
)
return wrapper
# project/api/your_code.py
from project.api.exceptions import handle_exceptions
class SomeViewSet():
#handle_exceptions
def create(self, request, *args, **kwargs):
raise AuthCredentialsError("Authentication credentials were not provided")

Related

Handling exceptions in permission classes

I am using Django REST Framework with simple JWT, and I don't like how permission classes generate a response without giving me the final say on what gets sent to the client. With other class-based views not restricting permissions (login, registration, etc.), I have control over how I handle exceptions, and I can choose how the response data is structured.
However, anytime I introduce permission classes, undesired behavior occurs. My desired structure is best represented in my LoginView (see try/except block):
NON_FIELD_ERRORS_KEY = settings.REST_FRAMEWORK['NON_FIELD_ERRORS_KEY']
class LoginView(GenericAPIView):
"""
View for taking in an existing user's credentials and authorizing them if valid or denying access if invalid.
"""
serializer_class = LoginSerializer
def post(self, request):
"""
POST method for taking a token from a query string, checking if it is valid, and logging in the user if valid, or returning an error response if invalid.
"""
serializer = self.serializer_class(data=request.data)
try:
serializer.is_valid(raise_exception=True)
except AuthenticationFailed as e:
return Response({NON_FIELD_ERRORS_KEY: [e.detail]}, status=e.status_code)
return Response(serializer.data, status=status.HTTP_200_OK)
However, what happens when I try to define a view using a permission class?
class LogoutView(GenericAPIView):
"""
View for taking in a user's access token and logging them out.
"""
serializer_class = LogoutSerializer
permission_classes = [IsAuthenticated]
def post(self, request):
"""
POST method for taking a token from a request body, checking if it is valid, and logging out the user if valid, or returning an error response if invalid.
"""
access = request.META.get('HTTP_AUTHORIZATION', '')
serializer = self.serializer_class(data={'access': access})
try:
serializer.is_valid(raise_exception=True)
except AuthenticationFailed as e:
return Response({NON_FIELD_ERRORS_KEY: [e.detail]}, status=e.status_code)
return Response(serializer.save(), status=status.HTTP_205_RESET_CONTENT)
When I go to test this, requests with an invalid Authorization header are handled outside the scope of post(), so execution never reaches the method at all. Instead, I am forced to deal with a response that is inconsistent with the rest of my project. Here's an example:
# Desired output
{
'errors': [
ErrorDetail(string='Given token not valid for any token type', code='token_not_valid')
]
}
# Actual output
{
'detail': ErrorDetail(string='Given token not valid for any token type', code='token_not_valid'),
'code': ErrorDetail(string='token_not_valid', code='token_not_valid'),
'messages': [
{
'token_class': ErrorDetail(string='AccessToken', code='token_not_valid'),
'token_type': ErrorDetail(string='access', code='token_not_valid'),
'message': ErrorDetail(string='Token is invalid or expired', code='token_not_valid')
}
]
}
Is there a simple way to change how these responses are formatted?
After stepping through the code, I found that the exceptions with which I was concerned were being raised in the last commented section of APIView.initial.
# rest_framework/views.py (lines 399-416)
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs)
# Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
# Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
# Ensure that the incoming request is permitted
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)
To generate a custom response, either create a custom implementation of APIView with an overloaded initial() method, or override the method in specific instances of APIView (or descendants such as GenericAPIView).
# my_app/views.py
def initial(self, request, *args, **kwargs):
"""
This method overrides the default APIView method so exceptions can be handled.
"""
try:
super().initial(request, *args, **kwargs)
except (AuthenticationFailed, InvalidToken) as exc:
raise AuthenticationFailed(
{NON_FIELD_ERRORS_KEY: [_('The provided token is invalid.')]},
'invalid')
except NotAuthenticated as exc:
raise NotAuthenticated(
{
NON_FIELD_ERRORS_KEY:
[_('Authentication credentials were not provided.')]
}, 'not_authenticated')

Django rest_framework custom error message

I have a API endpoint where it will do input validation using rest_framework's serializer.is_valid() where it will return custom error message and response.
serializer = FormSerializer(data=data)
if not serializer.is_valid(raise_exception=False):
return Response({"Failure": "Error"}, status=status.HTTP_400_BAD_REQUEST)
Is it possible to populate validation errors without using the generic response provided by raise_exception=True? I am trying to avoid using the generic response as it will display all the validation errors if there are more than one error.
The response will be something like
return Response(
{
"Failure": "Error",
"Error_list": {"field1": "This field is required"}
},
status=status.HTTP_400_BAD_REQUEST
)
Create a Custom Exception class as,
from rest_framework.exceptions import PermissionDenied
from rest_framework import status
class MyCustomExcpetion(PermissionDenied):
status_code = status.HTTP_400_BAD_REQUEST
default_detail = "Custom Exception Message"
default_code = 'invalid'
def __init__(self, detail, status_code=None):
self.detail = detail
if status_code is not None:
self.status_code = status_code
Why I'm inherrited from PermissionDenied exception class ??
see this SO post -- Why DRF ValidationError always returns 400
Then in your serializer, raise exceptions as,
class SampleSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = SampleModel
def validate_age(self, age): # field level validation
if age > 10:
raise MyCustomExcpetion(detail={"Failure": "error"}, status_code=status.HTTP_400_BAD_REQUEST)
return age
def validate(self, attrs): # object level validation
if some_condition:
raise MyCustomExcpetion(detail={"your": "exception", "some_other": "key"}, status_code=status.HTTP_410_GONE)
return attrs
age and name are two fields of SampleModel class
Response will be like this
By using this method,
1. You can customize the JSON Response
2. You can return any status codes
3. You don't need to pass True in serializer.is_valid() method (This is not reccomended)
A simple way is to use one of the exception messages, eg NotFound. See docs
# views.py
from rest_framework.exceptions import NotFound
class myview(viewsets.ModelViewSet):
def perform_create(self, serializer):
raise NotFound("My text here")
That will return a 404 and change the response to your text
HTTP 404 Not Found
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"detail": "my text here"
}
You can write custom error handler:
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
response = exception_handler(exc, context)
if response is not None:
response.data['Failure'] = 'Error'
return response

How to send customized response if the unauthroized credentials were provided in django rest

How to send customised response if the unauthorised credentials were provided in django rest.
class StockList(APIView):
permission_classes = [IsAuthenticated]
def get(self,request):
stocks = Stock.objects.all()
serializer = StockSerializer(stocks,many=True)
return Response({'user': serializer.data,'post': serializer.data})
def post(self):
pass
Here when I Hit url by invalid credentials i get 401 error on development server.
But i want to send customised response on client using json.
any suggestions are welcomed.
Thank you.
You can use a custom exception handler to customized response of api exception.
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status_code'] = response.status_code
if response.status_code == 401:
response.data['some_message'] = "Some custom message"
return response
Then in setting.py you have to add your custom error handler
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.path.to.custom_exception_handler'
}
Refs: docs

Django REST Exceptions

I currently have some code for a view based on the Django REST Framework.
Ive been using a customer exception class, but ideally I want to use the inbuilt Django REST exceptions.
From the code below I feel this probably not the best or cleanest way to utilize the REST Framework exceptions to its maximum.
Has anyone got any good examples where they are catching issues and returning them cleanly with the REST built in exceptions ?
class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
def queryInput(request):
try:
auth_token = session_id = getAuthHeader(request)
if not auth_token:
return JSONResponse({'detail' : "fail", "error" : "No X-Auth-Token Found", "data" : None}, status=500)
if request.method:
data = JSONParser().parse(request)
serializer = queryInputSerializer(data=data)
if request.method == 'POST':
if serializer.is_valid():
input= serializer.data["input"]
fetchData = MainRunner(input=input,auth_token=auth_token)
main_data = fetchData.main()
if main_data:
return JSONResponse({'detail' : "success", "error" : None, "data" : main_data}, status=201)
return JSONResponse({'detail' : "Unknown Error","error" : True, "data" : None}, status=500)
except Exception as e:
return JSONResponse({'error' : str(e)},status=500)
The Django REST framework provides several built in exceptions, which are mostly subclasses of DRF's APIException.
You can raise exceptions in your view like you normally would in Python:
from rest_framework.exceptions import APIException
def my_view(request):
raise APIException("There was a problem!")
You could also create your own custom exception by inheriting from APIException and setting status_code and default_detail. Some of the built in ones are: ParseError, AuthenticationFailed, NotAuthenticated, PermissionDenied, NotFound, NotAcceptable, ValidationError, etc.
These will then get converted to a Response by the REST Framework's exception handler. Each exception is associated with a status code that is added to the Response. By default the exception handler is set to the built in handler:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}
But you can set it to your own custom exception handler if you want to convert the exceptions yourself by changing this in your settings.py file:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
And then create the custom handler in that location:
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status_code'] = response.status_code
return response
You can use the build in DRF exception, just import and raise
from rest_framework.exceptions import ParseError
...
raise ParseError('I already have a status code!')

Tastypie-django custom error handling

I would like to return some JSON responses back instead of just returning a header with an error code. Is there a way in tastypie to handle errors like that?
Figured it out eventually. Here's a good resource to look at, if anyone else needs it. http://gist.github.com/1116962
class YourResource(ModelResource):
def wrap_view(self, view):
"""
Wraps views to return custom error codes instead of generic 500's
"""
#csrf_exempt
def wrapper(request, *args, **kwargs):
try:
callback = getattr(self, view)
response = callback(request, *args, **kwargs)
if request.is_ajax():
patch_cache_control(response, no_cache=True)
# response is a HttpResponse object, so follow Django's instructions
# to change it to your needs before you return it.
# https://docs.djangoproject.com/en/dev/ref/request-response/
return response
except (BadRequest, ApiFieldError), e:
return HttpBadRequest({'code': 666, 'message':e.args[0]})
except ValidationError, e:
# Or do some JSON wrapping around the standard 500
return HttpBadRequest({'code': 777, 'message':', '.join(e.messages)})
except Exception, e:
# Rather than re-raising, we're going to things similar to
# what Django does. The difference is returning a serialized
# error message.
return self._handle_500(request, e)
return wrapper
You could overwrite tastypie's Resource method _handle_500(). The fact that it starts with an underscore indeed indicates that this is a "private" method and shouldn't be overwritten, but I find it a cleaner way than having to overwrite wrap_view() and replicate a lot of logic.
This is the way I use it:
from tastypie import http
from tastypie.resources import ModelResource
from tastypie.exceptions import TastypieError
class MyResource(ModelResource):
class Meta:
queryset = MyModel.objects.all()
fields = ('my', 'fields')
def _handle_500(self, request, exception):
if isinstance(exception, TastypieError):
data = {
'error_message': getattr(
settings,
'TASTYPIE_CANNED_ERROR',
'Sorry, this request could not be processed.'
),
}
return self.error_response(
request,
data,
response_class=http.HttpApplicationError
)
else:
return super(MyResource, self)._handle_500(request, exception)
In this case I catch all Tastypie errors by checking if exception is an instance of TastypieError and return a JSON reponse with the message "Sorry, this request could not be processed.". If it's a different exception, I call the parent _handle_500 using super(), which will create a django error page in development mode or send_admins() in production mode.
If you want to have a specific JSON response for a specific exception, just do the isinstance() check on a specific exception. Here are all the Tastypie exceptions:
https://github.com/toastdriven/django-tastypie/blob/master/tastypie/exceptions.py
Actually I think there should be a better/cleaner way to do this in Tastypie, so I opened a ticket on their github.