Routers in Django REST Framework (DRF) provide an easy way to automatically generate URL routing for API views. They significantly reduce boilerplate code when working with ViewSets and standard CRUD APIs.
Routers map HTTP verbs (GET, POST, PUT, DELETE) to ViewSet methods without manually defining routes in urls.py.
// ViewSet with automatic CRUD routes
from rest_framework import viewsets
from rest_framework.routers import DefaultRouter
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = router.urls
// Simple CRUD routing without extras
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register(r'books', BookViewSet)
urlpatterns = router.urls
// Custom endpoint using @action
from rest_framework.decorators import action
from rest_framework.response import Response
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
@action(detail=True, methods=['post'])
def mark_as_read(self, request, pk=None):
book = self.get_object()
book.read = True
book.save()
return Response({'status': 'book marked as read'})
/books/ → list & create/books/{id}/ → retrieve, update, delete/books/{id}/mark_as_read/ → custom actionTest how the DefaultRouter maps URLs and HTTP Methods to ViewSet actions.