Return Custom 404 Error when resource not found in Django Rest Framework

according to django documentation : Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL. ref: https://docs.djangoproject.com/en/1.8/topics/http/urls/

so you can just add another url in urlpatterns after the one you created and it should match all url patterns and send them to a view that return the 404 code.

i.e :

urlpatterns = [
url(r'^mailer/$', views.Mailer.as_view(), name='send-email-to-admin'),
url(r'^.*/$',views.Error404.as_view(),name='error404')]

You are looking for handler404.

Here is my suggestion:

  1. Create a view that should be called if none of the URL patterns match.
  2. Add handler404 = path.to.your.view to your root URLconf.

Here is how it's done:

  1. project.views

    from django.http import JsonResponse
    
    
    def custom404(request, exception=None):
        return JsonResponse({
            'status_code': 404,
            'error': 'The resource was not found'
        })
    
  2. project.urls

    from project.views import custom404
    
    
    handler404 = custom404
    

Read error handling for more details.

Django REST framework exceptions may be useful as well.