Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Routers and URLs

Routers: Automatic URL Configuration

Generate URLs for viewsets automatically with DRF's SimpleRouter and DefaultRouter. Learn register(), basename, route names, the API root view and trailing slashes.

A viewset is a class of actions, not a URL. Something must say that GET /tasks/ calls list, GET /tasks/7/ calls retrieve, and so on. You saw the manual version with as_view({"get": "list"}). A router writes that mapping for you: register a viewset once, and the router produces every URL pattern, with names ready for reverse().

This lesson covers the two main routers, how register() and basename work, what routes you get, and how to include the result in urls.py.

Registering a viewset

Python A router builds the URL patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

router.register(prefix, viewset) takes the URL prefix and the viewset. The router printed two patterns: tasks/ (list and create) and tasks/<pk>/ (retrieve, update, partial update, destroy), named task-list and task-detail. The include(router.urls) line plugs them into the project, under api/.

Which verbs a pattern allows follows the actions the viewset has. A ReadOnlyModelViewSet registered on the same router would only allow GET on both patterns.

basename and route names

Route names are <basename>-list, <basename>-detail and <basename>-<action> for extra actions. DRF finds the basename from the viewset's queryset (Task becomes task). You must pass basename yourself when:

  • the viewset has no queryset attribute because it overrides get_queryset();
  • you register two viewsets for the same model, and the names would clash.
Python
router.register("my-tasks", MyTaskViewSet, basename="my-task")
Python basename and reverse()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Names matter beyond tidiness: HyperlinkedModelSerializer and HyperlinkedRelatedField look up <basename>-detail to build URLs, as shown in Relational Fields.

SimpleRouter and DefaultRouter

DRF has two commonly used routers:

Router Extra behavior
SimpleRouter Only the viewset routes
DefaultRouter Everything SimpleRouter does, plus an API root view at / listing all list endpoints, and optional .json-style format suffixes (/tasks.json)

DefaultRouter is the usual choice because the root page doubles as a table of contents in the browsable API.

Python DefaultRouter adds an API root

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The root lists each registered prefix with its absolute URL. The helper make_viewset just builds serializer and viewset classes programmatically to keep the example short; in your project you would write ordinary classes.

The standard route table

For a prefix tasks a router creates these routes:

URL Verbs and actions Name
tasks/ GET list, POST create task-list
tasks/{pk}/ GET retrieve, PUT update, PATCH partial_update, DELETE destroy task-detail
tasks/{pk}/{action}/ extra @action(detail=True) task-{action}
tasks/{action}/ extra @action(detail=False) task-{action}

Extra routes come from custom actions. A route is only created when the viewset has a matching method.

Router options

  • Trailing slash. Routes end with / by default. Use SimpleRouter(trailing_slash=False) for slash-less URLs (and make sure your clients and APPEND_SLASH settings agree).
  • Lookup field. The segment can become something else with lookup_field = "slug" on the viewset. If the value might contain dots, set lookup_value_regex = "[^/]+".
  • Several routers. Large projects create one router per app and include each under its own prefix, or call router.registry.extend(other.registry) to merge.
  • Custom routers. Subclass SimpleRouter and set routes to change the table, which is rarely needed.
Python
# catalog/urls.py
router = DefaultRouter()
router.register("products", ProductViewSet)
router.register("categories", CategoryViewSet)

urlpatterns = [path("", include(router.urls))]
Python
# project/urls.py
urlpatterns = [
    path("api/catalog/", include("catalog.urls")),
    path("api/orders/", include("orders.urls")),
]

Common mistakes

  • Registering a viewset without a queryset and without basename.
  • Registering the same prefix twice, so one viewset silently shadows the other.
  • Putting a literal URL such as tasks/export/ before the router's tasks/<pk>/ pattern when pk could match "export". Make export a @action(detail=False) instead, or place your own pattern first.
  • Forgetting the trailing slash in tests or clients. POST /api/tasks redirects to /api/tasks/ and a redirect drops the body, which looks like a mysterious 301 or 500.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does router.register('tasks', TaskViewSet) do?

    The router maps URLs and HTTP verbs to the viewset's actions and exposes them through router.urls.
  2. 2. When must you pass basename to register()?

    Without a queryset DRF cannot derive a name, and duplicate names would clash.
  3. 3. What does DefaultRouter add on top of SimpleRouter?

    DefaultRouter adds the root listing page and optional .json style suffixes.
  4. 4. What is the route name of the detail URL for basename 'task'?

    Names follow the <basename>-detail pattern, which reverse() and hyperlinked fields use.

Summary

  • A router turns a viewset into URL patterns; register it with router.register(prefix, viewset).
  • SimpleRouter gives the routes; DefaultRouter adds an API root and format suffixes.
  • Route names are <basename>-list, <basename>-detail and <basename>-<action>.
  • Provide basename when there is no queryset attribute or names would clash.
  • Include router.urls in your project's URL configuration; mind trailing slashes and pattern order.

Next: URL Patterns, Format Suffixes and Namespaces