How do you return 404 when resource is not found in Django REST Framework

Simply way to do it, you can use raise Http404, here is your

from django.http import Http404

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from yourapp.models import Snippet
from yourapp.serializer import SnippetSerializer

class SnippetDetailView(APIView):

    def get_object(self, pk):
            return Snippet.objects.get(pk=pk)
        except Snippet.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet)
        return Response(, status=status.HTTP_200_OK)

You also can handle it with Response(status=status.HTTP_404_NOT_FOUND), this answer is how to do with it:

But previously, inside your

from rest_framework import serializers

from yourapp.models import Snippet

class SnippetSerializer(serializers.ModelSerializer):
    user = serializers.CharField(
    photo = serializers.ImageField(

    class Meta:
        model = Snippet
        fields = ('user', 'title', 'photo', 'description')

    def create(self, validated_data):
        return Snippet.objects.create(**validated_data)

To test it, an example using curl command;

$ curl -X GET http://localhost:8000/snippets/<pk>/

# example;

$ curl -X GET http://localhost:8000/snippets/99999/

Hope it can help..


If you want to handle for all error 404 urls with DRF, DRF also provide about it with APIException, this answer may help you;

I’ll give an example how do with it;


from rest_framework.exceptions import NotFound

def error404(request):
    raise NotFound(detail="Error 404, page not found", code=404)


from django.conf.urls import (
  handler400, handler403, handler404, handler500)

from yourapp.views import error404

handler404 = error404

Makesure your DEBUG = False

Leave a Comment