Adding custom response Headers to APIException

django, django-rest-framework, python

Solution

Try overriding `finalize_response` in your rest framework view:

def finalize_response(self, request, *args, **kwargs):
    response = super(SomeAPIView, self).finalize_response(request, *args, **kwargs)
    response['WWW-Authenticate'] = 'Token'
    return response

Edit:

After seeing your update, I think your override of `handle_exception` should work, I would only add an else statement to call the parent method to cover other exceptions. One thing I noticed in overriding dispatch, which may not be an issue here, is that setting a new key/value for self.headers resulted in a server error that I didn't take the time to track down. Anyways, it seems you are on the right track.

Problem

I have created a custom exception referring to http://django-rest-framework.org/api-guide/exceptions.html. Please know that I have my own authentication backend. Hence I am not using rest_framework's authentication module. For authentication errors, I want to add 'WWW-Authenticate: Token' header to the response that is sent from the exception. Any ideas will be very helpful. Update: Thanks @Pathétique, This is what I ended up doing. -Have a base view class named BaseView. -override the handle_exception method to set appropriate headers, in my case 'WWW-Authenticate'. Here is the code: ``` class BaseView(APIView): def handle_exception(self, exc): if isinstance(exc, MYEXCEPTION): self.headers['WWW-Authenticate'] = "Token" return Response({'detail': exc.detail, status=exc.status_code, exception=True) ``` Your thoughts?

Original source