Using Routers for Automatic URL Routing in Django REST Framework
Last updated 6 months, 1 week ago | 471 views 75 5
Manually defining URL patterns for every view in your API can get repetitive and error-prone. That’s why Django REST Framework offers routers—a powerful way to automatically generate URL patterns for your ViewSets.
In this article, you'll learn:
-
What routers are in DRF
-
How they work with ViewSets
-
Types of routers
-
Step-by-step setup with examples
-
Tips and common pitfalls
What Are Routers?
In DRF, routers automatically generate URL patterns for ViewSets, mapping HTTP methods to actions like .list(), .retrieve(), .create(), etc.
Instead of writing this:
urlpatterns = [
path('books/', BookListView.as_view()),
path('books/<int:pk>/', BookDetailView.as_view()),
]
You can do this:
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = [
path('', include(router.urls)),
]
✅ It’s cleaner
✅ Less boilerplate
✅ Automatically handles RESTful conventions
Prerequisites
You should already have:
-
A Django model (e.g.,
Book) -
A serializer (e.g.,
BookSerializer) -
A ViewSet (e.g.,
BookViewSetusingModelViewSet)
Step-by-Step Example
1. Create the Model
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
2. Create the Serializer
# serializers.py
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
3. Create the ViewSet
# views.py
from rest_framework.viewsets import ModelViewSet
from .models import Book
from .serializers import BookSerializer
class BookViewSet(ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
4. Register with a Router
# urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = [
path('', include(router.urls)),
]
✅ Now you get all these routes:
| HTTP Method | URL | Action |
|---|---|---|
| GET | /books/ |
List all |
| POST | /books/ |
Create |
| GET | /books/<pk>/ |
Retrieve one |
| PUT | /books/<pk>/ |
Update |
| PATCH | /books/<pk>/ |
Partial update |
| DELETE | /books/<pk>/ |
Delete |
Types of Routers in DRF
1. DefaultRouter
-
Adds a default API root view (e.g.,
"/") -
Automatically handles all ViewSet actions
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
2. SimpleRouter
-
Same as
DefaultRouter, but no root view -
Use this when you don't want an API root (
/)
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
3. Custom Routers
-
You can create your own router by subclassing
BaseRouterorSimpleRouter.
⚠️ Common Pitfalls
| Problem | Fix |
|---|---|
Page not found |
Ensure you’re using include(router.urls) in urlpatterns |
| API root page missing | Use DefaultRouter instead of SimpleRouter |
| Duplicate routes | Don’t register the same ViewSet twice |
| ViewSet missing actions | Use ModelViewSet or include the right mixins |
Tips and Best Practices
-
✅ Use routers + ViewSets for fast CRUD development.
-
✅ Use explicit URL patterns if you need fine-grained control.
-
✅ Prefer
DefaultRouterduring development—it gives you an API root. -
✅ Name your ViewSets clearly to avoid confusion (e.g.,
BookViewSet).
Summary
| Concept | Purpose |
|---|---|
router.register() |
Maps a ViewSet to a URL prefix |
DefaultRouter |
Auto-generates routes + API root |
SimpleRouter |
Auto-generates routes only |
| ViewSet + Router | Easy CRUD API generation |
Routers save time, reduce duplication, and enforce RESTful patterns. If you're building APIs with Django REST Framework, routers are your best friend.
What’s Next?
You might want to explore:
-
Adding extra actions to ViewSets using
@action -
Building nested routes with
drf-nested-routers