Routers In Django Rest Framework¶
Routers are used with ViewSets in django rest framework to auto config the urls. Routers provides a simple, quick and consistent way of wiring ViewSet logic to a set of URLs. Router automatically maps the incoming request to proper viewset action based on the request method type(i.e GET, POST, etc). Let's start using routers.
Working with DRF Routers¶
Lets's see a simple example how to configure viewset urls
urls.py
from rest_framework import routers
from .views import UserViewSet
router = routers.SimpleRouter()
router.register('users', UserViewSet)
urlpatterns = router.urls
Above example will generate urls configuration like below
- URL pattern: ^users/$ Name: 'user-list'
- URL pattern: ^users/{pk}/$ Name: 'user-detail'
- URL pattern: ^accounts/$ Name: 'account-list'
- URL pattern: ^accounts/{pk}/$ Name: 'account-detail'
We have two types of routers in Django REST
SimpleRouter¶
- It includes actions for all actions (i.e list, create, retrieve, update, partial_update and destroy).
- Let's see how it configures the urls
URL Style | HTTP Method | Action | URL Name |
---|---|---|---|
{prefix}/ | GET | list | {basename}-list |
POST | create | ||
{prefix}/{url_path}/ | GET, or as specified by `methods` argument | `@action(detail=False)` decorated method | {basename}-{url_name} |
{prefix}/{lookup}/ | GET | retrieve | {basename}-detail |
PUT | update | ||
PATCH | partial_update | ||
DELETE | destroy | ||
{prefix}/{lookup}/{url_path}/ | GET, or as specified by `methods` argument | `@action(detail=True)` decorated method | {basename}-{url_name} |
DefaultRouter¶
- It also includes all actions just like SimpleRouter and it additionally provides a default root view which returns a response containing hyperlinks to all the list views.
- Let's see how it configures the urls
URL Style | HTTP Method | Action | URL Name |
---|---|---|---|
[.format] | GET | automatically generated root view | api-root |
{prefix}/[.format] | GET | list | {basename}-list |
POST | create | ||
{prefix}/{url_path}/[.format] | GET, or as specified by `methods` argument | `@action(detail=False)` decorated method | {basename}-{url_name} |
{prefix}/{lookup}/[.format] | GET | retrieve | {basename}-detail |
PUT | update | ||
PATCH | partial_update | ||
DELETE | destroy | ||
{prefix}/{lookup}/{url_path}/[.format] | GET, or as specified by `methods` argument | `@action(detail=True)` decorated method | {basename}-{url_name} |
To avoid trailing slash we have to provide trailing_slash=False
while initiating the router like below.
router = SimpleRouter(trailing_slash=False)
# or
# router = DefaultRouter(trailing_slash=False)
Reference: https://www.django-rest-framework.org/api-guide/routers
SourceCode: https://github.com/encode/django-rest-framework/blob/master/rest_framework/routers.py