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

10,707

Solution 1

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.

Solution 2

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')]
Share:
10,707

Related videos on Youtube

Akshay Pratap Singh
Author by

Akshay Pratap Singh

Software Engineer & Data Science Enthusiast Programming Languages Python, JavaScript & NodeJs (Proficient) C, C++, Java, C#, PHP, HTML, CSS Scripting Language Bash and Powershell Frameworks and Libraries Django & DRF, Express (Proficient) ReactJs, Flask, Angular Cloud Services Experience Azure, AWS "Be Curious, Be Sceptical and Be Learner."

Updated on September 26, 2022

Comments

  • Akshay Pratap Singh
    Akshay Pratap Singh over 1 year

    I am learning Django Rest Framework, and also new to django. I want to return a custom 404 error in json when a client will access a resource which was not found.

    My urls.py looks liks this:

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

    In which i have only one resource, which can be accessed through URI, http://localhost:8000/mailer/

    Now, when a client access any other URI like http://localhost:8000/, API should return a 404-Not Found error like this:

    {
        "status_code" : 404
        "error" : "The resource was not found"
    }
    

    Please suggest some answer with proper code snippets, if suitable.

  • Akshay Pratap Singh
    Akshay Pratap Singh almost 9 years
    this solution doesn't work, i did as you described.I also set DEBUG=False.But, it return html page, Not Found The requested URL / was not found on this server.
  • Akshay Pratap Singh
    Akshay Pratap Singh almost 9 years
    what should i do to make Error404 class view, such that it return my customized JsonResponse in call of each HTTP methods.
  • Akshay Pratap Singh
    Akshay Pratap Singh almost 9 years
    Is there any way to write one single method in Class View, which handle all HTTP methods, rather write for separate method for each HTTP method.
  • Ernest
    Ernest almost 9 years
    @AkshayPratapSingh Seems like I misunderstood you. Edited my answer and it should work now.
  • Akshay Pratap Singh
    Akshay Pratap Singh almost 9 years
    i am using this method to catch rest_framwork view's errors, but it does not catch url route non-matched error, which return 404 error.
  • Akshay Pratap Singh
    Akshay Pratap Singh almost 9 years
    your solution also works but i used function @api_view not class based view , so that api return same JsonResponse on calling each HTTP method.
  • Heretron
    Heretron about 7 years
    You should also include status code 404: JsonResponse({'detail': "The resource was not found", 'status_code': 404}, status=404)