olive
olive

Reputation: 1204

How do I customise the default 404 response for a URL not found error using Django Rest Framework?

I want to know how to display an error page like this when there is a 404 error for a not-found resource on my Django Rest Framework API:

{
    'detail': 'The resource was not found'
}

I can't find out how to do this, because most of the tutorial is just assuming that you are setting up a specific URL.

Upvotes: 3

Views: 1076

Answers (1)

Justin Hamade
Justin Hamade

Reputation: 833

Django Rest Framework overrides Django Http404 in exception_handler so you need to write your own exception. Example:

class NotFound(APIException):
    status_code = status.HTTP_404_NOT_FOUND
    default_detail = 'The resource was not found.'

    def __init__(self, detail=None):
        self.detail = detail or self.default_detail

Upvotes: 1

Related Questions