Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Routers and URLs

URL Patterns, Format Suffixes and Namespaces

Write DRF URL patterns by hand, add format suffixes like .json, use reverse() and namespaces for stable links, and mix routers with ordinary paths in one project.

Routers cover the common cases, but you will still write URL patterns by hand for plain APIViews, for custom endpoints and for mixing everything into one project. This lesson covers the tools around those patterns: format suffixes, reverse(), namespaces, the hyperlinked API root and the order rules that decide which pattern wins.

Hand-written patterns

A DRF view is an ordinary Django view once you call as_view(), so the usual path() and re_path() work:

Python
from django.urls import path
from .views import NoteList, NoteDetail, health

urlpatterns = [
    path("notes/", NoteList.as_view(), name="note-list"),
    path("notes/<int:pk>/", NoteDetail.as_view(), name="note-detail"),
    path("health/", health, name="health"),          # a function view with @api_view
]

Always give patterns a name. Names let reverse(), hyperlinked serializers and tests find URLs without hard-coding strings, so you can restructure URLs later without breaking code.

Format suffixes

A client can ask for a representation in the URL as well as in the Accept header: /notes/1.json instead of /notes/1/ with Accept: application/json. DRF's format_suffix_patterns() takes your URL list and adds a suffix variant of each pattern. Your view receives the suffix as a format argument (it must accept format=None).

Python Format suffix 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.

/notes/1.json selected the JSON renderer without any Accept header, and .api selected the browsable HTML renderer. .xml returned 404 because no renderer has the format xml, as we did not install one. Why bother? Some clients cannot set headers easily (a browser address bar, a simple <a href> link, a spreadsheet import), and suffixes make URLs bookmarkable and cacheable per format.

Notice the trailing slashes: format_suffix_patterns works best with slash-less patterns such as notes/<int:pk>, because notes/1/.json looks odd. With DefaultRouter the suffix patterns are already added for you (include_format_suffixes=True), as seen in the previous lesson. You only need format_suffix_patterns for hand-written URLs.

Mind that every extra route also needs your format parameter on the view or you get a TypeError.

reverse() and DRF's reverse

Django's reverse() builds a path. DRF's rest_framework.reverse.reverse builds a full URL when given a request, and automatically respects versioning (a later chapter):

Python Building URLs with 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.

The first two values include the scheme and host (http://api.example.com/...), taken from the request, so a client can follow them without knowing how the server is deployed. The last one, without request, is only a path. Returning absolute links from a root view is the hypermedia habit that DefaultRouter's API root also follows.

Namespaces

When a project has several apps, two of them may both define item-list. Namespaces prevent clashes: give each included URLconf an app_name, and refer to names as namespace:name.

Python
# catalog/urls.py
app_name = "catalog"
urlpatterns = [path("items/", ItemList.as_view(), name="item-list")]

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

# anywhere
reverse("catalog:item-list")

There is one important catch with hyperlinked serializers: they build links using view_name. With namespaces, set view_name="catalog:item-detail" on each hyperlinked field (via extra_kwargs = {"url": {"view_name": "catalog:item-detail"}}), or the lookup will fail with an ImproperlyConfigured error. This is the most common source of confusion with namespaced routers.

With a router and a namespace, you pass the router's URLs through include:

Python
router = DefaultRouter()
router.register("items", ItemViewSet, basename="item")

app_name = "catalog"
urlpatterns = [path("", include(router.urls))]

Pattern order and conflicts

Django tries patterns in order and uses the first match, so order is a design tool:

Python Order decides which pattern wins

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.

Put specific literal patterns before parameterized ones. With routers, avoid the problem by making export a @action(detail=False); DRF registers list-level actions before the detail pattern.

Putting it together: a project urls.py

Python
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("api/v1/", include("catalog.urls")),          # router-based
    path("api/v1/auth/", include("accounts.urls")),    # hand-written APIViews
    path("api-auth/", include("rest_framework.urls")), # browsable API login
]

Prefix your API (/api/) so it does not collide with HTML pages, and consider a version segment (/api/v1/) from day one. Versioning strategies are the subject of a later chapter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does format_suffix_patterns() add?

    Each pattern gets a twin like notes/1.json, and the suffix reaches the view as the format argument.
  2. 2. Why use rest_framework.reverse.reverse(name, request=request)?

    Passing the request lets DRF include scheme and host and apply the versioning scheme.
  3. 3. Two URL patterns both match a request. Which one handles it?

    Django uses the first match, so list specific patterns before parameterized ones.
  4. 4. A namespaced router fails to build links in a HyperlinkedModelSerializer. What is the usual cause?

    Hyperlinked fields call reverse() with a view name; with namespaces it must be written namespace:name.

Summary

  • Hand-written patterns work with as_view(); always give them names.
  • format_suffix_patterns adds .json-style variants, and views must accept format=None.
  • DRF's reverse(..., request=request) returns absolute, version-aware URLs.
  • Use app_name namespaces to avoid name clashes, and set view_name on hyperlinked fields accordingly.
  • The first matching pattern wins, so put literal patterns before parameterized ones.

Next: Nested and Related Routes