Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Testing and Deployment

Testing DRF APIs with APIClient and APITestCase

Write reliable tests for Django REST Framework APIs: APITestCase, APIClient, force_authenticate, APIRequestFactory, status and payload assertions, query counts and a testing checklist.

An API is a contract with clients you cannot see. Tests are how you promise that the contract still holds after tomorrow's refactor. API tests are also satisfying to write: you send an HTTP request, you assert on the status code and the JSON, and you never need a browser.

DRF builds on Django's test tools and adds rest_framework.test: APIClient (a test HTTP client that understands format="json" and authentication shortcuts), APITestCase (a Django TestCase with an APIClient ready as self.client) and APIRequestFactory (builds request objects without going through URLs, middleware or a database round trip).

The test pyramid for APIs

What to test where

Unit tests Serializers, validators, filters
API tests Request in, status and JSON out
Flow tests Login, create, update, delete

Most value comes from API tests: they exercise URLs, permissions, serializers and queries together

1 / 2

A first test class

In a real project you put tests in tests.py or a tests/ package and run python manage.py test (or pytest with pytest-django). Django creates a separate empty test database, wraps every test in a transaction, and rolls it back afterwards, so tests never see each other's data.

The lesson's runner has no project folder, so the example below builds a tiny Task API and runs a normal unittest suite in memory. The test code itself is exactly what you would write in tests.py.

Python APITestCase: create, list, permissions, validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
ok    test_anonymous_is_refused
ok    test_blank_title_is_a_400
ok    test_create_sets_the_owner
ok    test_delete_returns_204
ok    test_list_shows_only_my_tasks
ok    test_other_users_task_is_hidden
ok    test_patch_marks_done
ran 7 tests | failures: 0 | errors: 0

Notes on this style:

  • force_authenticate(user) skips real credential checking: the request is treated as coming from that user. It is the fastest way to test everything that happens after authentication. To test login itself (/api/token/, session login), post real credentials; see token authentication.
  • format="json" encodes the body as JSON and sets the Content-Type. Without it, APIClient sends multipart form data by default (or whatever TEST_REQUEST_DEFAULT_FORMAT says). A common bug is posting a nested dict without format="json".
  • self.client.credentials(HTTP_AUTHORIZATION="Token ...") sets a header for all later requests; self.client.force_authenticate(user=None) logs out.
  • setUpTestData runs once per class, which is faster than creating the rows in setUp() for every test, and Django resets class-level data between tests.
  • Use response.json() (or response.data for the already-parsed Python structure before rendering).

Testing a view without URLs: APIRequestFactory

APIRequestFactory builds a request object you can hand directly to a view function. It skips URL routing and middleware, so it is great for unit-testing a view's logic or a permission class. It returns an un-rendered response, so call render() if you need content. Authenticate with the helper force_authenticate(request, user=...).

CaptureQueriesContext and assertNumQueries let you pin the number of SQL queries, which is how you catch N+1 problems (see query optimization).

Python APIRequestFactory, permission checks and query counts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
member POST -> 403
anonymous GET -> 200
rows: 6 | queries: 1

With select_related("author") the whole list costs one query, no matter how many posts there are. Delete that call and the same test would report one query per post plus one: a regression you can lock in with self.assertNumQueries(1).

Good habits

  • Name tests after behaviour: test_other_users_task_is_hidden tells a future reader what broke.
  • One logical assertion per test, but several assert lines are fine when they describe the same result.
  • Test refusals, not just success. For every endpoint add the anonymous case, the wrong-user case, and an invalid-payload case. Most security bugs are a missing "who is refused" test.
  • Assert on the contract. Compare keys and values clients depend on. Avoid asserting on whole serialized objects that contain timestamps or generated IDs.
  • Freeze nondeterminism. Use freezegun or unittest.mock.patch for time, random values and outside services (payment gateways, email, HTTP calls). Never call a real third-party API from a test.
  • Use factories. Libraries such as factory_boy or model_bakery create valid objects with one line, keeping the setup short.
  • Keep the suite fast. Use MD5PasswordHasher in test settings, prefer force_authenticate, and use setUpTestData. Fast tests get run.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does format="json" do in client.post(url, data, format="json")?

    It controls how the request body is encoded. Without it APIClient uses the default test format, usually multipart.
  2. 2. What is force_authenticate for?

    It bypasses authentication so tests can focus on what happens after login.
  3. 3. Why does Django roll back the database after each APITestCase test?

    Every test runs inside a transaction that is rolled back, which isolates tests.
  4. 4. How can a test catch an N+1 query regression?

    Pinning the number of queries makes an accidental per-row query fail the test.
  5. 5. Which request is easiest to test with APIRequestFactory?

    The factory creates a request you pass straight to the view, skipping URL routing and most middleware.

Summary

  • Use APITestCase and APIClient for most tests; APIRequestFactory for isolated views and permissions.
  • Authenticate with force_authenticate() or credentials(); send JSON with format="json".
  • Test the happy path, every refusal (401, 403, 404), bad input (400) and side effects.
  • Pin query counts with assertNumQueries and mock anything that talks to the outside world.
  • Keep tests named by behaviour, independent and fast.

Next: Testing Authentication and Permissions