← Back to Django, page 4

django-0062 · Easy fresher

What is the difference between a plain Django view and a DRF @api_view or APIView, and what does Response give you?

DRF wraps Django views with request parsing (request.data for JSON, forms and files), content negotiation, a Response class that renders to JSON or other formats, authentication, permissions, throttling and consistent error handling. Use @api_view for small function endpoints and APIView for class-based ones, and move to generic views or viewsets for CRUD.

Full answer

A plain Django view receives an HttpRequest and must parse JSON, validate, serialise and set status codes by hand. DRF adds:

  • Request: request.data (parsed body for JSON, form data or multipart, always one place), request.query_params, request.user, request.auth.
  • Response(data, status=...): holds Python data and renders it later according to the client's Accept header (JSON by default, browsable API for browsers).
  • Policy classes: authentication_classes, permission_classes, throttle_classes, and parsers and renderers, configured globally in REST_FRAMEWORK or per view.
  • Exceptions: ValidationError, NotFound, PermissionDenied are turned into 400, 404 and 403 responses with a JSON body.

Function style:

python
@api_view(["GET", "POST"])
def hello(request):
    ...

Class style: class StudentList(APIView): def get(self, request): .... The method name selects the handler; unsupported methods return 405 automatically.

Normally the view uses a serializer to validate request.data and to build the response data. The levels of abstraction, from low to high: APIView, generic views (ListCreateAPIView), then ModelViewSet with a router.

Return Response(serializer.data, status=status.HTTP_201_CREATED) for created resources and let serializer.is_valid(raise_exception=True) produce the 400 response.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from rest_framework import serializers, status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.test import APIRequestFactory
from rest_framework.views import APIView

STUDENTS = [{"id": 1, "name": "Asha"}]


class StudentIn(serializers.Serializer):
    name = serializers.CharField(max_length=20)


class StudentList(APIView):
    def get(self, request):
        return Response(STUDENTS)

    def post(self, request):
        s = StudentIn(data=request.data)
        s.is_valid(raise_exception=True)            # becomes a 400 response with JSON errors
        STUDENTS.append({"id": len(STUDENTS) + 1, **s.validated_data})
        return Response(STUDENTS[-1], status=status.HTTP_201_CREATED)


@api_view(["GET"])
def ping(request):
    return Response({"pong": True, "params": dict(request.query_params)})


rf = APIRequestFactory()
view = StudentList.as_view()
r = view(rf.get("/students/"))
print(r.status_code, r.data)
r = view(rf.post("/students/", {"name": "Ravi"}, format="json"))
print(r.status_code, r.data)
r = view(rf.post("/students/", {"name": ""}, format="json"))
print(r.status_code, r.data)
print(view(rf.delete("/students/")).status_code)
print(ping(rf.get("/ping/?x=1")).data)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Requires `pip install djangorestframework`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 [{'id': 1, 'name': 'Asha'}] 201 {'id': 2, 'name': 'Ravi'} 400 {'name': [ErrorDetail(string='This field may not be blank.', code='blank')]} 405 {'pong': True, 'params': {'x': ['1']}}

Key points

  • request.data parses JSON, form and multipart in one place
  • Response renders to the format the client asks for
  • @api_view or APIView add auth, permissions, throttling and errors
  • Unsupported methods return 405 automatically
  • Generic views and viewsets sit above APIView

Common mistakes

  • Parsing request.body by hand inside DRF views
  • Returning raw dictionaries with HttpResponse instead of Response
  • Skipping serializer validation and trusting request.data
  • Forgetting that the project-wide default permission is AllowAny

Follow-ups

  • What are the default authentication and permission classes?
  • When should you use a ViewSet instead of APIView?
  • How does content negotiation pick the renderer?

Tips

  • Mention request.data and Response
  • List what DRF adds automatically
  • Show the abstraction ladder