Performance: Testing API endpoints
Testing API endpoints affects development speed and server response validation but does not directly impact page load or rendering performance.
Jump into concepts and practice - no test required
from unittest.mock import patch def test_api_endpoint(self): with patch('app.views.get_external_data') as mock_data: mock_data.return_value = {'key': 'value'} response = self.client.get('/api/data') self.assertEqual(response.status_code, 200) self.assertIn('key', response.json())
def test_api_endpoint(self): response = self.client.get('/api/data') self.assertEqual(response.status_code, 200) self.assertIn('data', response.content.decode()) # No mocking, hitting real database and external services
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Real API calls in tests | 0 (no DOM) | 0 | 0 | [X] Bad |
| Mocked API calls in tests | 0 (no DOM) | 0 | 0 | [OK] Good |
APIClient in testing?APIClient for testing in Django REST Framework?from rest_framework.test import APIClient.client = APIClient()
response = client.get('/api/items/')
print(response.status_code)client = APIClient()
response = client.post('/api/items/', data={'name': 'Book'})
self.assertEqual(response.status_code, 201)format='json' is specified.format='json' causes the server to reject or misinterpret data, failing the test.APIClient?client.force_authenticate(user=user) or set credentials before making requests.client.get() to access the protected endpoint successfully.