← Back to Django, page 5

django-0082 · Medium mid

How do you test Django REST Framework endpoints with APIClient and APITestCase, including authentication, permissions and error cases?

APITestCase gives self.client, an APIClient that sends JSON by default with format='json' and supports force_authenticate(user) to skip real login. Tests should check status codes, the response body shape, permission boundaries (anonymous, normal user, owner, staff), validation errors and database side effects, using setUpTestData for shared fixtures and assertNumQueries for performance guards.

Full answer

rest_framework.test provides APIRequestFactory (build requests, call views directly), APIClient (full stack through URLs and middleware) and APITestCase (a Django TestCase with self.client = APIClient()).

Pattern:

python
class StudentApiTests(APITestCase):
    @classmethod
    def setUpTestData(cls):
        cls.teacher = User.objects.create_user("t", password="x", is_staff=True)
        cls.pupil = User.objects.create_user("p", password="x")

    def test_anonymous_gets_401(self):
        self.assertEqual(self.client.get("/api/students/").status_code, 401)

    def test_staff_can_create(self):
        self.client.force_authenticate(self.teacher)
        r = self.client.post("/api/students/", {"name": "Asha"}, format="json")
        self.assertEqual(r.status_code, 201)

Guidelines:

  • force_authenticate(user=..., token=...) bypasses authentication classes, which is fine for permission logic. Add a few tests with real credentials (client.credentials(HTTP_AUTHORIZATION="Bearer ...")) to prove the auth setup works.
  • Always send format="json" or set TEST_REQUEST_DEFAULT_FORMAT in settings; otherwise bodies are multipart.
  • Test the matrix: unauthenticated (401 or 403), forbidden user (403), owner (200), other user's object (404 or 403), invalid payload (400 with field errors).
  • Assert response JSON structure, not only status codes, and database state (Student.objects.count()).
  • assertNumQueries protects list endpoints against N+1 regressions.
  • self.client.logout() and force_authenticate(None) reset identity.
  • Test throttling by overriding DEFAULT_THROTTLE_RATES with override_settings and clearing the cache between tests.
  • Run tests in parallel with manage.py test --parallel and avoid shared global state.
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
    ROOT_URLCONF=__name__,
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "rest_framework.authtoken", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import unittest

from django.contrib.auth import get_user_model
from django.db import models, connection
from django.test.utils import setup_test_environment
from django.urls import include, path
from rest_framework import serializers, viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.routers import DefaultRouter
from rest_framework.test import APITestCase


class Note(models.Model):
    owner = models.ForeignKey("auth.User", on_delete=models.CASCADE)
    text = models.CharField(max_length=100)

    class Meta:
        app_label = "school"


class NoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Note
        fields = ["id", "text"]


class NoteViewSet(viewsets.ModelViewSet):
    serializer_class = NoteSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Note.objects.filter(owner=self.request.user).order_by("id")

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


router = DefaultRouter()
router.register("notes", NoteViewSet, basename="note")
urlpatterns = [path("api/", include(router.urls))]

User = get_user_model()
with connection.schema_editor() as editor:
    for m in (User, Note):
        editor.create_model(m)


class NoteApiTests(APITestCase):
    @classmethod
    def setUpTestData(cls):
        cls.asha = User.objects.create_user("asha", password="x")
        cls.ravi = User.objects.create_user("ravi", password="x")
        cls.note = Note.objects.create(owner=cls.asha, text="private")

    def test_anonymous_is_rejected(self):
        self.assertEqual(self.client.get("/api/notes/").status_code, 403)

    def test_owner_sees_own_note(self):
        self.client.force_authenticate(self.asha)
        r = self.client.get("/api/notes/")
        self.assertEqual([n["text"] for n in r.json()], ["private"])

    def test_other_user_gets_404(self):
        self.client.force_authenticate(self.ravi)
        self.assertEqual(self.client.get(f"/api/notes/{self.note.pk}/").status_code, 404)

    def test_create_sets_owner_and_validates(self):
        self.client.force_authenticate(self.ravi)
        r = self.client.post("/api/notes/", {"text": "mine"}, format="json")
        self.assertEqual((r.status_code, Note.objects.get(pk=r.json()["id"]).owner), (201, self.ravi))
        bad = self.client.post("/api/notes/", {"text": ""}, format="json")
        self.assertEqual((bad.status_code, list(bad.json())), (400, ["text"]))

    def test_list_uses_one_query(self):
        self.client.force_authenticate(self.asha)
        with self.assertNumQueries(1):
            self.client.get("/api/notes/")


setup_test_environment()
suite = unittest.defaultTestLoader.loadTestsFromTestCase(NoteApiTests)
result = unittest.TextTestRunner(verbosity=0, stream=open("/dev/null", "w")).run(suite)
print("ran:", result.testsRun, "failures:", len(result.failures), "errors:", len(result.errors))
for case, tb in result.failures + result.errors:
    print(case, tb[-300:])

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): ran: 5 failures: 0 errors: 0

Key points

  • APIClient sends JSON with format='json'
  • force_authenticate skips login to test permissions
  • Test the full matrix: anonymous, forbidden, owner, other user, invalid
  • Assert body and database state, not only status
  • assertNumQueries guards against N+1

Common mistakes

  • Sending multipart bodies by forgetting format='json'
  • Testing only the happy path and status 200
  • Relying only on force_authenticate and never testing real credentials
  • Not checking that users cannot read or change other users' objects

Follow-ups

  • How do you test token or JWT authentication end to end?
  • How would you test throttling reliably?
  • What is the difference between APIRequestFactory and APIClient?

Tips

  • List the permission test matrix
  • Mention force_authenticate and credentials
  • Mention assertNumQueries