Routing APIs with DRF
Routing APIs with DRF
When working with Django REST Framework ViewSets, manually writing individual path() entries for every CRUD endpoint (list, create, retrieve, update, destroy) is tedious and error-prone. DRF Routers automatically generate standardized, consistent RESTful URL routing schemes, including trailing slash management and the browsable API root.
1. How DRF Routers Work
A DRF router inspects a ViewSet and automatically generates the complete set of standard REST URL patterns:
2. Configuring DefaultRouter vs SimpleRouter
DRF provides two main router classes:
SimpleRouter: Generates only the basic CRUD URL patterns.DefaultRouter: ExtendsSimpleRouterby adding a default API Root endpoint displaying hyperlinks to all registered resources, as well as optional.json/ format suffix patterns.
Visiting http://127.0.0.1:8000/api/v1/ renders DRF's interactive Browsable API Root with clickable links to /articles/ and /categories/!
3. When is basename Required?
If a ViewSet has a queryset attribute, DRF automatically derives the basename from the model name:
However, if your ViewSet overrides get_queryset() and omits the static queryset attribute, you must specify basename:
4. Nested Routers with drf-nested-routers
For hierarchical REST APIs (e.g. /articles/{article_id}/comments/{comment_id}/), use the drf-nested-routers package:
Practice Quiz
Custom Middleware
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| APIView & ViewSet | Custom Middleware |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.