routers.py

Routers

Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index… a resourceful route declares them in a single line of code.

Ruby on Rails Documentation

Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.

REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.

Usage

Here's an example of a simple URL conf, that uses SimpleRouter.

  1. from rest_framework import routers
  2. router = routers.SimpleRouter()
  3. router.register(r'users', UserViewSet)
  4. router.register(r'accounts', AccountViewSet)
  5. urlpatterns = router.urls

There are two mandatory arguments to the register() method:

  • prefix - The URL prefix to use for this set of routes.
  • viewset - The viewset class.

Optionally, you may also specify an additional argument:

  • basename - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set basename when registering the viewset.

The example above would generate the following URL patterns:

  • 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'

Note: The basename argument is used to specify the initial part of the view name pattern. In the example above, that's the user or account part.

Typically you won't need to specify the basename argument, but if you have a viewset where you've defined a custom get_queryset method, then the viewset may not have a .queryset attribute set. If you try to register that viewset you'll see an error like this:

  1. 'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.

This means you'll need to explicitly set the basename argument when registering the viewset, as it could not be automatically determined from the model name.


Using include with routers

The .urls attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.

For example, you can append router.urls to a list of existing views…

  1. router = routers.SimpleRouter()
  2. router.register(r'users', UserViewSet)
  3. router.register(r'accounts', AccountViewSet)
  4. urlpatterns = [
  5. url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
  6. ]
  7. urlpatterns += router.urls

Alternatively you can use Django's include function, like so…

  1. urlpatterns = [
  2. url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
  3. url(r'^', include(router.urls)),
  4. ]

You may use include with an application namespace:

  1. urlpatterns = [
  2. url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
  3. url(r'^api/', include((router.urls, 'app_name'))),
  4. ]

Or both an application and instance namespace:

  1. urlpatterns = [
  2. url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
  3. url(r'^api/', include((router.urls, 'app_name'), namespace='instance_name')),
  4. ]

See Django's URL namespaces docs and the include API reference for more details.


Note: If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameterson the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such asview_name='app_name:user-detail' for serializer fields hyperlinked to the user detail view.

The automatic view_name generation uses a pattern like %(model_name)-detail. Unless your models names actually clashyou may be better off not namespacing your Django REST Framework views when using hyperlinked serializers.


Routing for extra actions

A viewset may mark extra actions for routing by decorating a method with the @action decorator. These extra actions will be included in the generated routes. For example, given the set_password method on the UserViewSet class:

  1. from myapp.permissions import IsAdminOrIsSelf
  2. from rest_framework.decorators import action
  3. class UserViewSet(ModelViewSet):
  4. ...
  5. @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
  6. def set_password(self, request, pk=None):
  7. ...

The following route would be generated:

  • URL pattern: ^users/{pk}/set_password/$
  • URL name: 'user-set-password'

By default, the URL pattern is based on the method name, and the URL name is the combination of the ViewSet.basename and the hyphenated method name.If you don't want to use the defaults for either of these values, you can instead provide the url_path and url_name arguments to the @action decorator.

For example, if you want to change the URL for our custom action to ^users/{pk}/change-password/$, you could write:

  1. from myapp.permissions import IsAdminOrIsSelf
  2. from rest_framework.decorators import action
  3. class UserViewSet(ModelViewSet):
  4. ...
  5. @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],
  6. url_path='change-password', url_name='change_password')
  7. def set_password(self, request, pk=None):
  8. ...

The above example would now generate the following URL pattern:

  • URL path: ^users/{pk}/change-password/$
  • URL name: 'user-change_password'

API Guide

SimpleRouter

This router includes routes for the standard set of list, create, retrieve, update, partial_update and destroy actions. The viewset can also mark additional methods to be routed, using the @action decorator.

URL StyleHTTP MethodActionURL Name
{prefix}/GETlist{basename}-list
POSTcreate
{prefix}/{url_path}/GET, or as specified by methods argument@action(detail=False) decorated method{basename}-{url_name}
{prefix}/{lookup}/GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{url_path}/GET, or as specified by methods argument@action(detail=True) decorated method{basename}-{url_name}

By default the URLs created by SimpleRouter are appended with a trailing slash.This behavior can be modified by setting the trailing_slash argument to False when instantiating the router. For example:

  1. router = SimpleRouter(trailing_slash=False)

Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.

The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the lookup_value_regex attribute on the viewset. For example, you can limit the lookup to valid UUIDs:

  1. class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
  2. lookup_field = 'my_model_id'
  3. lookup_value_regex = '[0-9a-f]{32}'

DefaultRouter

This router is similar to SimpleRouter as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional .json style format suffixes.

URL StyleHTTP MethodActionURL Name
[.format]GETautomatically generated root viewapi-root
{prefix}/[.format]GETlist{basename}-list
POSTcreate
{prefix}/{url_path}/[.format]GET, or as specified by methods argument@action(detail=False) decorated method{basename}-{url_name}
{prefix}/{lookup}/[.format]GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{url_path}/[.format]GET, or as specified by methods argument@action(detail=True) decorated method{basename}-{url_name}

As with SimpleRouter the trailing slashes on the URL routes can be removed by setting the trailing_slash argument to False when instantiating the router.

  1. router = DefaultRouter(trailing_slash=False)

Custom Routers

Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.

The simplest way to implement a custom router is to subclass one of the existing router classes. The .routes attribute is used to template the URL patterns that will be mapped to each viewset. The .routes attribute is a list of Route named tuples.

The arguments to the Route named tuple are:

url: A string representing the URL to be routed. May include the following format strings:

  • {prefix} - The URL prefix to use for this set of routes.
  • {lookup} - The lookup field used to match against a single instance.
  • {trailing_slash} - Either a '/' or an empty string, depending on the trailing_slash argument.

mapping: A mapping of HTTP method names to the view methods

name: The name of the URL as used in reverse calls. May include the following format string:

  • {basename} - The base to use for the URL names that are created.

initkwargs: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the detail, basename, and suffix arguments are reserved for viewset introspection and are also used by the browsable API to generate the view name and breadcrumb links.

Customizing dynamic routes

You can also customize how the @action decorator is routed. Include the DynamicRoute named tuple in the .routes list, setting the detail argument as appropriate for the list-based and detail-based routes. In addition to detail, the arguments to DynamicRoute are:

url: A string representing the URL to be routed. May include the same format strings as Route, and additionally accepts the {url_path} format string.

name: The name of the URL as used in reverse calls. May include the following format strings:

  • {basename} - The base to use for the URL names that are created.
  • {url_name} - The url_name provided to the @action.

initkwargs: A dictionary of any additional arguments that should be passed when instantiating the view.

Example

The following example will only route to the list and retrieve actions, and does not use the trailing slash convention.

  1. from rest_framework.routers import Route, DynamicRoute, SimpleRouter
  2. class CustomReadOnlyRouter(SimpleRouter):
  3. """
  4. A router for read-only APIs, which doesn't use trailing slashes.
  5. """
  6. routes = [
  7. Route(
  8. url=r'^{prefix}$',
  9. mapping={'get': 'list'},
  10. name='{basename}-list',
  11. detail=False,
  12. initkwargs={'suffix': 'List'}
  13. ),
  14. Route(
  15. url=r'^{prefix}/{lookup}$',
  16. mapping={'get': 'retrieve'},
  17. name='{basename}-detail',
  18. detail=True,
  19. initkwargs={'suffix': 'Detail'}
  20. ),
  21. DynamicRoute(
  22. url=r'^{prefix}/{lookup}/{url_path}$',
  23. name='{basename}-{url_name}',
  24. detail=True,
  25. initkwargs={}
  26. )
  27. ]

Let's take a look at the routes our CustomReadOnlyRouter would generate for a simple viewset.

views.py:

  1. class UserViewSet(viewsets.ReadOnlyModelViewSet):
  2. """
  3. A viewset that provides the standard actions
  4. """
  5. queryset = User.objects.all()
  6. serializer_class = UserSerializer
  7. lookup_field = 'username'
  8. @action(detail=True)
  9. def group_names(self, request, pk=None):
  10. """
  11. Returns a list of all the group names that the given
  12. user belongs to.
  13. """
  14. user = self.get_object()
  15. groups = user.groups.all()
  16. return Response([group.name for group in groups])

urls.py:

  1. router = CustomReadOnlyRouter()
  2. router.register('users', UserViewSet)
  3. urlpatterns = router.urls

The following mappings would be generated…

URLHTTP MethodActionURL Name
/usersGETlistuser-list
/users/{username}GETretrieveuser-detail
/users/{username}/group_namesGETgroup_namesuser-group-names

For another example of setting the .routes attribute, see the source code for the SimpleRouter class.

Advanced custom routers

If you want to provide totally custom behavior, you can override BaseRouter and override the get_urls(self) method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the self.registry attribute.

You may also want to override the get_default_basename(self, viewset) method, or else always explicitly set the basename argument when registering your viewsets with the router.

Third Party Packages

The following third party packages are also available.

DRF Nested Routers

The drf-nested-routers package provides routers and relationship fields for working with nested resources.

ModelRouter (wq.db.rest)

The wq.db package provides an advanced ModelRouter class (and singleton instance) that extends DefaultRouter with a register_model() API. Much like Django's admin.site.register, the only required argument to rest.router.register_model is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration.

  1. from wq.db import rest
  2. from myapp.models import MyModel
  3. rest.router.register_model(MyModel)

DRF-extensions

The DRF-extensions package provides routers for creating nested viewsets, collection level controllers with customizable endpoint names.