Understanding Status Codes and Response in Django REST Framework

Last updated 1 month, 2 weeks ago | 142 views 75     5

Tags:- Python Django DRF

In a RESTful API, how you respond to a client is just as important as what you respond with. In Django REST Framework (DRF), the Response class and HTTP status codes are essential tools for clearly communicating the outcome of an API request.

This guide will help you understand:

  • What the Response class is

  • Why status codes matter

  • Common status codes used in APIs

  • How to use them effectively in DRF

  • Best practices and common mistakes


What is Response in DRF?

In DRF, the Response class is a subclass of Django's HttpResponse, but it's designed for APIs. It:

  • Automatically renders content into the right format (e.g. JSON)

  • Supports content negotiation

  • Works seamlessly with DRF’s request/response flow

✅ Basic Example

from rest_framework.response import Response

def example_view(request):
    return Response({"message": "Hello, API!"})

Behind the scenes, DRF converts this into a JSON response:

{
  "message": "Hello, API!"
}

Why Are Status Codes Important?

HTTP status codes tell the client what happened. They are standardized and widely understood by frontends, mobile apps, and even humans.

Code Meaning Example Use
200 OK Success GET a list of books
201 Created Successfully created POST a new resource
204 No Content Successfully deleted DELETE a record
400 Bad Request Validation failed Missing required field
401 Unauthorized Not authenticated User not logged in
403 Forbidden Authenticated but not allowed No permission
404 Not Found Resource doesn't exist Invalid ID
500 Internal Server Error Server crashed Unexpected issue

How to Use Status Codes in DRF

DRF provides a handy module: rest_framework.status

✅ Example with Status Codes

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

class ExampleView(APIView):
    def get(self, request):
        return Response({"message": "All good"}, status=status.HTTP_200_OK)

    def post(self, request):
        if "name" not in request.data:
            return Response({"error": "Name is required"}, status=status.HTTP_400_BAD_REQUEST)
        return Response({"message": "Created"}, status=status.HTTP_201_CREATED)

Real Example: Handling All Statuses

class BookDetailView(APIView):
    def get(self, request, pk):
        try:
            book = Book.objects.get(pk=pk)
        except Book.DoesNotExist:
            return Response({"error": "Not found"}, status=status.HTTP_404_NOT_FOUND)
        serializer = BookSerializer(book)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def delete(self, request, pk):
        try:
            book = Book.objects.get(pk=pk)
            book.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except Book.DoesNotExist:
            return Response({"error": "Not found"}, status=status.HTTP_404_NOT_FOUND)

When to Use Which Status Code

Situation Status Code Response
Resource retrieved 200 OK Data in body
New resource created 201 Created Created object in body
Delete succeeded 204 No Content Empty body
Invalid input 400 Bad Request Errors in body
User not logged in 401 Unauthorized Auth required
Not enough permissions 403 Forbidden Not allowed
Resource missing 404 Not Found Error message
Server crashed 500 Internal Server Error Debug only in development

⚠️ Common Mistakes

Mistake Fix
Not specifying a status Use status=... in Response()
Returning HttpResponse Use rest_framework.response.Response for APIs
Incorrect status code Follow HTTP spec: use 201 for creation, not 200
Returning raw dicts Always return through Response()

Best Practices

  • ✅ Always return appropriate status codes — it improves client-side logic and debugging.

  • ✅ Use DRF’s status module instead of hardcoding numbers (more readable).

  • ✅ Return useful error messages with 400, 404, 403, etc.

  • ✅ Avoid 500 errors by handling exceptions with try/except.


Summary

Component Purpose
Response() Send formatted response (usually JSON)
status module Use readable status codes like status.HTTP_404_NOT_FOUND
Proper HTTP codes Help clients understand what happened and why

A well-designed API not only sends back data, but also sends back the right message using HTTP status codes.