Building Production-Ready APIs with Django REST Framework
## Project Setup
```bash
pip install djangorestframework djangorestframework-simplejwt
```
```python
INSTALLED_APPS = [..., 'rest_framework']
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20,
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day',
},
}
```
## ViewSet Example
```python
from rest_framework import viewsets, permissions
from .models import Project
from .serializers import ProjectSerializer
class ProjectViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Project.objects.filter(status='completed')
serializer_class = ProjectSerializer
permission_classes = [permissions.AllowAny]
filterset_fields = ['category', 'status']
```
## API Versioning
```python
# urls.py
urlpatterns = [
path('api/v1/', include('api.v1.urls')),
path('api/v2/', include('api.v2.urls')),
]
```
## select_related & prefetch_related
Always optimise ORM queries in serializers:
```python
queryset = Project.objects.select_related('client').prefetch_related('members', 'metrics')
```
Avoids N+1 queries — the most common DRF performance pitfall.