← Back to Chapters

Using Routers in Django REST Framework

? Using Routers in Django REST Framework

? Quick Overview

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.

? Key Concepts

  • Automatic URL generation
  • ViewSet-based routing
  • Standard CRUD mappings
  • Custom actions via decorators

? Syntax & Theory

Routers map HTTP verbs (GET, POST, PUT, DELETE) to ViewSet methods without manually defining routes in urls.py.

? Using DefaultRouter

? View Code Example
// 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

? Using SimpleRouter

? View Code Example
// Simple CRUD routing without extras
from rest_framework.routers import SimpleRouter

router = SimpleRouter()
router.register(r'books', BookViewSet)

urlpatterns = router.urls

⚙️ Custom Router Actions

? View Code Example
// 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'})

? Live Output / Explanation

  • /books/ → list & create
  • /books/{id}/ → retrieve, update, delete
  • /books/{id}/mark_as_read/ → custom action

? Router Logic Simulator

Test how the DefaultRouter maps URLs and HTTP Methods to ViewSet actions.

// Click 'Resolve Route' to see the mapped action

? Use Cases

  • REST APIs with minimal URL configuration
  • Rapid backend prototyping
  • Consistent CRUD endpoints

✅ Tips & Best Practices

  • Prefer DefaultRouter for full-featured APIs
  • Use SimpleRouter for strict control
  • Keep custom actions RESTful

? Try It Yourself

  • Add a custom list-level action
  • Switch between routers and observe URLs
  • Secure custom routes with permissions