Skip to content

Routers

When using ViewSets, you don't need to design your URLs yourself. DRF routers automatically wire up your view logic to a set of URLs, making URL routing incredibly quick and consistent.

Using DefaultRouter

The DefaultRouter creates a standard set of RESTful routes.

python
# urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views

# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'users', views.UserViewSet, basename='user')
router.register(r'articles', views.ArticleViewSet, basename='article')

# The API URLs are now determined automatically by the router.
urlpatterns = [
    path('', include(router.urls)),
]

Generated Routes

Registering router.register(r'users', UserViewSet) automatically generates the following URLs:

URLHTTP MethodAction
/users/GETlist()
/users/POSTcreate()
/users/{pk}/GETretrieve()
/users/{pk}/PUTupdate()
/users/{pk}/PATCHpartial_update()
/users/{pk}/DELETEdestroy()

This significantly cuts down the boilerplate needed in your urls.py file!