Search⌘ K
AI Features

Adding a Router

Explore how to add routers to Django viewsets to automate API endpoint creation. Learn to send HTTP requests using Insomnia and implement permissions to protect user data from unauthorized modifications.

Routers allow us to quickly declare all of the common routes for a given controller. The next code snippet shows a viewset to which we will be adding a router.

At the root of the apps project (core), create a file named routers.py.

And let’s add the code:

Python 3.8
from rest_framework import routers
from core.user.viewsets import UserViewSet
router = routers.SimpleRouter()
# ##################################################################### #
# ################### USER ###################### #
# ##################################################################### #
router.register(r'user', UserViewSet, basename='user')
urlpatterns = [
*router.urls,
]

To register a route for a viewset, the register() method needs two arguments:

  • The prefix: Essentially represents the name of the ...