How to Test API in Django: Simple Guide with Examples
To test an API in Django, use
APIClient from rest_framework.test to simulate HTTP requests and check responses. Write test cases in Django's TestCase class to verify your API endpoints behave as expected.Syntax
Use APIClient to send HTTP requests like get, post, put, and delete to your API endpoints. Write tests inside a subclass of django.test.TestCase or rest_framework.test.APITestCase. Use assertions to check response status codes and data.
APIClient(): creates a test client for API requestsclient.get(url): sends a GET requestclient.post(url, data, format='json'): sends a POST request with JSON dataself.assertEqual(): checks expected vs actual results
python
from rest_framework.test import APIClient from django.test import TestCase class MyApiTest(TestCase): def setUp(self): self.client = APIClient() def test_example(self): response = self.client.get('/api/example/') self.assertEqual(response.status_code, 200) self.assertIn('key', response.data)
Example
This example shows how to test a simple API endpoint that returns a list of items. It sends a GET request and checks the response status and content.
python
from rest_framework.test import APIClient from django.test import TestCase from django.urls import reverse class ItemApiTest(TestCase): def setUp(self): self.client = APIClient() def test_get_items(self): url = reverse('item-list') # URL name from your urls.py response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertIsInstance(response.data, list) # Example: check if response contains expected keys if response.data: self.assertIn('id', response.data[0]) self.assertIn('name', response.data[0])
Output
Ran 1 test in 0.005s
OK
Common Pitfalls
- Not using
APIClientand instead using Django's defaultClient, which may not handle JSON properly. - Forgetting to set
format='json'in POST/PUT requests, causing data to be sent as form data instead of JSON. - Not reversing URLs with
reverse(), which can break tests if URLs change. - Not checking response status codes before accessing
response.data, which can cause errors if the response is an error.
python
from rest_framework.test import APIClient from django.test import TestCase from django.urls import reverse class WrongApiTest(TestCase): def setUp(self): self.client = APIClient() def test_post_without_format(self): url = reverse('item-list') data = {'name': 'Test Item'} # Wrong: missing format='json', sends form data response = self.client.post(url, data) self.assertNotEqual(response.status_code, 201) # May fail def test_post_with_format(self): url = reverse('item-list') data = {'name': 'Test Item'} # Right: sends JSON data response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, 201)
Quick Reference
Remember these key points when testing Django APIs:
- Use
APIClientfromrest_framework.test. - Use
reverse()to get URLs by name. - Set
format='json'for JSON requests. - Check
response.status_codebefore accessing data. - Write tests inside
TestCasesubclasses.
Key Takeaways
Use Django REST Framework's APIClient to simulate API requests in tests.
Always set format='json' when sending JSON data in POST or PUT requests.
Use reverse() to get URLs by name to keep tests maintainable.
Check response status codes before accessing response data to avoid errors.
Write your API tests inside Django TestCase subclasses for automatic test discovery.