URL Routing
DRF DefaultRouter and SimpleRouter Configuration
Django REST Framework routers eliminate manual URL routing boilerplate by automatically mapping standard ViewSet actions to predictable RESTful URLs. Understanding the differences between SimpleRouter and DefaultRouter, customizing trailing slashes, and managing format suffixes ensures seamless API routing.
1. Comparing SimpleRouter vs DefaultRouter
| Feature | SimpleRouter | DefaultRouter |
|---|---|---|
| Generates CRUD routes | Yes (list, create, retrieve, update, destroy) | Yes |
API Root Endpoint (/) | No (returns 404 at root) | Yes (Generates hyperlinked index of all endpoints) |
| Format Suffix Patterns | Optional manual configuration | Automatic (supports .json, .api suffixes) |
| Sweet Spot | Sub-routers or internal micro-APIs | Public API roots and browsable enterprise portals |
2. Advanced Router Configuration
3. The Trailing Slash Debate (trailing_slash=False)
By default, Django and DRF enforce trailing slashes (/api/v1/products/). If a client requests /api/v1/products, Django sends a 301 Moved Permanently redirect to the slashed URL.
In REST APIs consumed by frontend frameworks, unexpected 301 redirects on POST requests can drop the request body. If your client architecture strictly avoids trailing slashes:
4. Inspecting Registered Router URLs
To view every URL pattern generated by your router, inspect router.urls:
Output:
Practice Quiz
Token Authentication
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Endpoints for Models | Token Authentication |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.