Debian Codegraph @

docs/api-guide/routers.md

raw
1 ---
2 source:
3 - routers.py
4 ---
5
6 # Routers
7
8 > 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.
9 >
10 > — [Ruby on Rails Documentation][cite]
11
12 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.
13
14 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.
15
16 ## Usage
17
18 Here's an example of a simple URL conf, that uses `SimpleRouter`.
19
20 from rest_framework import routers
21
22 router = routers.SimpleRouter()
23 router.register(r'users', UserViewSet)
24 router.register(r'accounts', AccountViewSet)
25 urlpatterns = router.urls
26
27 There are two mandatory arguments to the `register()` method:
28
29 * `prefix` - The URL prefix to use for this set of routes.
30 * `viewset` - The viewset class.
31
32 Optionally, you may also specify an additional argument:
33
34 * `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.
35
36 The example above would generate the following URL patterns:
37
38 * URL pattern: `^users/$` Name: `'user-list'`
39 * URL pattern: `^users/{pk}/$` Name: `'user-detail'`
40 * URL pattern: `^accounts/$` Name: `'account-list'`
41 * URL pattern: `^accounts/{pk}/$` Name: `'account-detail'`
42
43 !!! note
44 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.
45
46 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:
47
48 'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
49
50 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.
51
52 ### Using `include` with routers
53
54 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.
55
56 For example, you can append `router.urls` to a list of existing views...
57
58 router = routers.SimpleRouter()
59 router.register(r'users', UserViewSet)
60 router.register(r'accounts', AccountViewSet)
61
62 urlpatterns = [
63 path('forgot-password/', ForgotPasswordFormView.as_view()),
64 ]
65
66 urlpatterns += router.urls
67
68 Alternatively you can use Django's `include` function, like so...
69
70 urlpatterns = [
71 path('forgot-password', ForgotPasswordFormView.as_view()),
72 path('', include(router.urls)),
73 ]
74
75 You may use `include` with an application namespace:
76
77 urlpatterns = [
78 path('forgot-password/', ForgotPasswordFormView.as_view()),
79 path('api/', include((router.urls, 'app_name'))),
80 ]
81
82 Or both an application and instance namespace:
83
84 urlpatterns = [
85 path('forgot-password/', ForgotPasswordFormView.as_view()),
86 path('api/', include((router.urls, 'app_name'), namespace='instance_name')),
87 ]
88
89 See Django's [URL namespaces docs][url-namespace-docs] and the [`include` API reference][include-api-reference] for more details.
90
91 !!! note
92 If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters
93 on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as
94 `view_name='app_name:user-detail'` for serializer fields hyperlinked to the user detail view.
95
96 The automatic `view_name` generation uses a pattern like `%(model_name)-detail`. Unless your models names actually clash
97 you may be better off **not** namespacing your Django REST Framework views when using hyperlinked serializers.
98
99 ### Routing for extra actions
100
101 A viewset may [mark extra actions for routing][route-decorators] 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:
102
103 from myapp.permissions import IsAdminOrIsSelf
104 from rest_framework.decorators import action
105
106 class UserViewSet(ModelViewSet):
107 ...
108
109 @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
110 def set_password(self, request, pk=None):
111 ...
112
113 The following route would be generated:
114
115 * URL pattern: `^users/{pk}/set_password/$`
116 * URL name: `'user-set-password'`
117
118 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.
119 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.
120
121 For example, if you want to change the URL for our custom action to `^users/{pk}/change-password/$`, you could write:
122
123 from myapp.permissions import IsAdminOrIsSelf
124 from rest_framework.decorators import action
125
126 class UserViewSet(ModelViewSet):
127 ...
128
129 @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],
130 url_path='change-password', url_name='change_password')
131 def set_password(self, request, pk=None):
132 ...
133
134 The above example would now generate the following URL pattern:
135
136 * URL path: `^users/{pk}/change-password/$`
137 * URL name: `'user-change_password'`
138
139 ### Using Django `path()` with routers
140
141 By default, the URLs created by routers use regular expressions. This behavior can be modified by setting the `use_regex_path` argument to `False` when instantiating the router, in this case [path converters][path-converters-topic-reference] are used. For example:
142
143 router = SimpleRouter(use_regex_path=False)
144
145 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 or `lookup_value_converter` if using path converters. For example, you can limit the lookup to valid UUIDs:
146
147 class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
148 lookup_field = 'my_model_id'
149 lookup_value_regex = '[0-9a-f]{32}'
150
151 class MyPathModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
152 lookup_field = 'my_model_uuid'
153 lookup_value_converter = 'uuid'
154
155 Note that path converters will be used on all URLs registered in the router, including viewset actions.
156
157 ## API Guide
158
159 ### SimpleRouter
160
161 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.
162
163 <table border=1>
164 <tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
165 <tr><td rowspan=2>{prefix}/</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
166 <tr><td>POST</td><td>create</td></tr>
167 <tr><td>{prefix}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=False)` decorated method</td><td>{basename}-{url_name}</td></tr>
168 <tr><td rowspan=4>{prefix}/{lookup}/</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
169 <tr><td>PUT</td><td>update</td></tr>
170 <tr><td>PATCH</td><td>partial_update</td></tr>
171 <tr><td>DELETE</td><td>destroy</td></tr>
172 <tr><td>{prefix}/{lookup}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
173 </table>
174
175 By default, the URLs created by `SimpleRouter` are appended with a trailing slash.
176 This behavior can be modified by setting the `trailing_slash` argument to `False` when instantiating the router. For example:
177
178 router = SimpleRouter(trailing_slash=False)
179
180 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.
181
182 ### DefaultRouter
183
184 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.
185
186 <table border=1>
187 <tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
188 <tr><td>[.format]</td><td>GET</td><td>automatically generated root view</td><td>api-root</td></tr></tr>
189 <tr><td rowspan=2>{prefix}/[.format]</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
190 <tr><td>POST</td><td>create</td></tr>
191 <tr><td>{prefix}/{url_path}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=False)` decorated method</td><td>{basename}-{url_name}</td></tr>
192 <tr><td rowspan=4>{prefix}/{lookup}/[.format]</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
193 <tr><td>PUT</td><td>update</td></tr>
194 <tr><td>PATCH</td><td>partial_update</td></tr>
195 <tr><td>DELETE</td><td>destroy</td></tr>
196 <tr><td>{prefix}/{lookup}/{url_path}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
197 </table>
198
199 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.
200
201 router = DefaultRouter(trailing_slash=False)
202
203 ## Custom Routers
204
205 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.
206
207 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.
208
209 The arguments to the `Route` named tuple are:
210
211 **url**: A string representing the URL to be routed. May include the following format strings:
212
213 * `{prefix}` - The URL prefix to use for this set of routes.
214 * `{lookup}` - The lookup field used to match against a single instance.
215 * `{trailing_slash}` - Either a '/' or an empty string, depending on the `trailing_slash` argument.
216
217 **mapping**: A mapping of HTTP method names to the view methods
218
219 **name**: The name of the URL as used in `reverse` calls. May include the following format string:
220
221 * `{basename}` - The base to use for the URL names that are created.
222
223 **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.
224
225 ### Customizing dynamic routes
226
227 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:
228
229 **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.
230
231 **name**: The name of the URL as used in `reverse` calls. May include the following format strings:
232
233 * `{basename}` - The base to use for the URL names that are created.
234 * `{url_name}` - The `url_name` provided to the `@action`.
235
236 **initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view.
237
238 ### Example
239
240 The following example will only route to the `list` and `retrieve` actions, and does not use the trailing slash convention.
241
242 from rest_framework.routers import Route, DynamicRoute, SimpleRouter
243
244 class CustomReadOnlyRouter(SimpleRouter):
245 """
246 A router for read-only APIs, which doesn't use trailing slashes.
247 """
248 routes = [
249 Route(
250 url=r'^{prefix}$',
251 mapping={'get': 'list'},
252 name='{basename}-list',
253 detail=False,
254 initkwargs={'suffix': 'List'}
255 ),
256 Route(
257 url=r'^{prefix}/{lookup}$',
258 mapping={'get': 'retrieve'},
259 name='{basename}-detail',
260 detail=True,
261 initkwargs={'suffix': 'Detail'}
262 ),
263 DynamicRoute(
264 url=r'^{prefix}/{lookup}/{url_path}$',
265 name='{basename}-{url_name}',
266 detail=True,
267 initkwargs={}
268 )
269 ]
270
271 Let's take a look at the routes our `CustomReadOnlyRouter` would generate for a simple viewset.
272
273 `views.py`:
274
275 class UserViewSet(viewsets.ReadOnlyModelViewSet):
276 """
277 A viewset that provides the standard actions
278 """
279 queryset = User.objects.all()
280 serializer_class = UserSerializer
281 lookup_field = 'username'
282
283 @action(detail=True)
284 def group_names(self, request, pk=None):
285 """
286 Returns a list of all the group names that the given
287 user belongs to.
288 """
289 user = self.get_object()
290 groups = user.groups.all()
291 return Response([group.name for group in groups])
292
293 `urls.py`:
294
295 router = CustomReadOnlyRouter()
296 router.register('users', UserViewSet)
297 urlpatterns = router.urls
298
299 The following mappings would be generated...
300
301 <table border=1>
302 <tr><th>URL</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
303 <tr><td>/users</td><td>GET</td><td>list</td><td>user-list</td></tr>
304 <tr><td>/users/{username}</td><td>GET</td><td>retrieve</td><td>user-detail</td></tr>
305 <tr><td>/users/{username}/group_names</td><td>GET</td><td>group_names</td><td>user-group-names</td></tr>
306 </table>
307
308 For another example of setting the `.routes` attribute, see the source code for the `SimpleRouter` class.
309
310 ### Advanced custom routers
311
312 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.
313
314 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.
315
316 ## Third Party Packages
317
318 The following third party packages are also available.
319
320 ### DRF Nested Routers
321
322 The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources.
323
324 ### ModelRouter (wq.db.rest)
325
326 The [wq.db package][wq.db] provides an advanced [ModelRouter][wq.db-router] 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.
327
328 from wq.db import rest
329 from myapp.models import MyModel
330
331 rest.router.register_model(MyModel)
332
333 ### DRF-extensions
334
335 The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions-routers] for creating [nested viewsets][drf-extensions-nested-viewsets], [collection level controllers][drf-extensions-collection-level-controllers] with [customizable endpoint names][drf-extensions-customizable-endpoint-names].
336
337 [cite]: https://guides.rubyonrails.org/routing.html
338 [route-decorators]: viewsets.md#marking-extra-actions-for-routing
339 [drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
340 [wq.db]: https://wq.io/wq.db
341 [wq.db-router]: https://wq.io/docs/router
342 [drf-extensions]: https://chibisov.github.io/drf-extensions/docs/
343 [drf-extensions-routers]: https://chibisov.github.io/drf-extensions/docs/#routers
344 [drf-extensions-nested-viewsets]: https://chibisov.github.io/drf-extensions/docs/#nested-routes
345 [drf-extensions-collection-level-controllers]: https://chibisov.github.io/drf-extensions/docs/#collection-level-controllers
346 [drf-extensions-customizable-endpoint-names]: https://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name
347 [url-namespace-docs]: https://docs.djangoproject.com/en/stable/topics/http/urls/#url-namespaces
348 [include-api-reference]: https://docs.djangoproject.com/en/stable/ref/urls/#include
349 [path-converters-topic-reference]: https://docs.djangoproject.com/en/stable/topics/http/urls/#path-converters