Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 6 of 10 · Django Testing & Debugging
Interview question

How do you test Django REST Framework APIs (APIClient, status codes, serializer validation)? Django REST Framework API को कैसे टेस्ट करें (APIClient, स्टेटस कोड, सीरियलाइज़र वैलिडेशन)?

Answer

DRF provides rest_framework.test.APIClient, a subclass of Django's test client tailored for APIs — it handles JSON request/response bodies naturally, supports authentication helpers like force_authenticate() to bypass real login for a test, and returns a response whose .data attribute gives the parsed response content directly.

A thorough DRF test suite checks status codes for each scenario (200/201 for success, 400 for validation errors, 401/403 for auth failures, 404 for missing resources), verifies the exact shape of the returned JSON, and separately unit-tests serializers by instantiating them directly with sample data to confirm validation rules work in isolation from any view or HTTP layer.

from rest_framework.test import APITestCase
from rest_framework import status

class ProductAPITest(APITestCase):
    def test_create_product_invalid_price(self):
        response = self.client.post('/api/products/', {'name': 'Book', 'price': -10})
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertIn('price', response.data)

DRF rest_framework.test.APIClient प्रदान करता है, जो Django के टेस्ट क्लाइंट का एक सबक्लास है जो APIs के लिए अनुकूलित है — यह JSON रिक्वेस्ट/रिस्पॉन्स बॉडीज़ को स्वाभाविक रूप से हैंडल करता है, टेस्ट के लिए वास्तविक लॉगिन को बायपास करने के लिए force_authenticate() जैसे ऑथेंटिकेशन हेल्पर्स सपोर्ट करता है।

एक संपूर्ण DRF टेस्ट सूट हर परिदृश्य के लिए स्टेटस कोड जाँचता है, लौटाए गए JSON के सटीक स्वरूप को सत्यापित करता है, और सीरियलाइज़र्स को अलग से यूनिट-टेस्ट करता है।

from rest_framework.test import APITestCase
from rest_framework import status

class ProductAPITest(APITestCase):
    def test_create_product_invalid_price(self):
        response = self.client.post('/api/products/', {'name': 'Book', 'price': -10})
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

Was this answer clear?