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

183 views Asked by At

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.

1

There are 1 answers

13
Arpit Solanki On

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