aboutsummaryrefslogtreecommitdiffstats
path: root/api-guide/routers/index.html
blob: 892e9df46fbdd17a2b280da41c95f6547d0bd278 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
<!DOCTYPE html>
<html lang="en">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <title>Routers - Django REST framework</title>
  <link href="../../img/favicon.ico" rel="icon" type="image/x-icon">
  <link rel="canonical" href="http://www.django-rest-framework.org/api-guide/routers/" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="Django, API, REST, Routers">
  <meta name="author" content="Tom Christie">

  <!-- Le styles -->
  <link href="../../css/prettify.css" rel="stylesheet">
  <link href="../../css/bootstrap.css" rel="stylesheet">
  <link href="../../css/bootstrap-responsive.css" rel="stylesheet">
  <link href="../../css/default.css" rel="stylesheet">

  <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
  <!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->

  <script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-18852272-2']);
    _gaq.push(['_trackPageview']);

    (function() {
      var ga = document.createElement('script');
      ga.type = 'text/javascript';
      ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ga, s);
    })();
  </script>

  <style>
    span.fusion-wrap a {
      display: block;
      margin-top: 10px;
      color: black;
    }
    a.fusion-poweredby {
      display: block;
      margin-top: 10px;
    }
    @media (max-width: 767px) {
      div.promo {
        display: none;
      }
    }
  </style>
</head>
<body onload="prettyPrint()" class="-page">

  <div class="wrapper">

        <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container-fluid">
          <a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a>
          <a class="repo-link btn btn-inverse btn-small " rel="prev" href="../parsers">
            Next <i class="icon-arrow-right icon-white"></i>
          </a>
          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../viewsets">
            <i class="icon-arrow-left icon-white"></i> Previous
          </a>
          <a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="modal"><i class="icon-search icon-white"></i> Search</a>
          <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </a>
          <a class="brand" href="http://www.django-rest-framework.org">Django REST framework</a>
          <div class="nav-collapse collapse">
            
            <!-- Main navigation -->
            <ul class="nav navbar-nav">
              <li ><a href="/">Home</a></li>
               
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../../tutorial/quickstart">Quickstart</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/1-serialization">1 - Serialization</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/2-requests-and-responses">2 - Requests and responses</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/3-class-based-views">3 - Class based views</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/6-viewsets-and-routers">6 - Viewsets and routers</a>
                  </li>
                  
                </ul>
              </li>
                
              <li class="dropdown active">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../requests">Requests</a>
                  </li>
                  
                  <li >
                    <a href="../responses">Responses</a>
                  </li>
                  
                  <li >
                    <a href="../views">Views</a>
                  </li>
                  
                  <li >
                    <a href="../generic-views">Generic views</a>
                  </li>
                  
                  <li >
                    <a href="../viewsets">Viewsets</a>
                  </li>
                  
                  <li class="active" >
                    <a href=".">Routers</a>
                  </li>
                  
                  <li >
                    <a href="../parsers">Parsers</a>
                  </li>
                  
                  <li >
                    <a href="../renderers">Renderers</a>
                  </li>
                  
                  <li >
                    <a href="../serializers">Serializers</a>
                  </li>
                  
                  <li >
                    <a href="../fields">Serializer fields</a>
                  </li>
                  
                  <li >
                    <a href="../relations">Serializer relations</a>
                  </li>
                  
                  <li >
                    <a href="../validators">Validators</a>
                  </li>
                  
                  <li >
                    <a href="../authentication">Authentication</a>
                  </li>
                  
                  <li >
                    <a href="../permissions">Permissions</a>
                  </li>
                  
                  <li >
                    <a href="../throttling">Throttling</a>
                  </li>
                  
                  <li >
                    <a href="../filtering">Filtering</a>
                  </li>
                  
                  <li >
                    <a href="../pagination">Pagination</a>
                  </li>
                  
                  <li >
                    <a href="../content-negotiation">Content negotiation</a>
                  </li>
                  
                  <li >
                    <a href="../format-suffixes">Format suffixes</a>
                  </li>
                  
                  <li >
                    <a href="../reverse">Returning URLs</a>
                  </li>
                  
                  <li >
                    <a href="../exceptions">Exceptions</a>
                  </li>
                  
                  <li >
                    <a href="../status-codes">Status codes</a>
                  </li>
                  
                  <li >
                    <a href="../testing">Testing</a>
                  </li>
                  
                  <li >
                    <a href="../settings">Settings</a>
                  </li>
                  
                </ul>
              </li>
                
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../../topics/documenting-your-api">Documenting your API</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/ajax-csrf-cors">AJAX, CSRF & CORS</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/browser-enhancements">Browser enhancements</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/browsable-api">The Browsable API</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/third-party-resources">Third Party Resources</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/contributing">Contributing to REST framework</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/rest-framework-2-announcement">2.0 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/2.2-announcement">2.2 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/2.3-announcement">2.3 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/2.4-announcement">2.4 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/3.0-announcement">3.0 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/kickstarter-announcement">Kickstarter Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/release-notes">Release Notes</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/credits">Credits</a>
                  </li>
                  
                </ul>
              </li>
               

            </ul>
            
          </div>
          <!--/.nav-collapse -->

        </div>
      </div>
    </div>

    <div class="body-content">
      <div class="container-fluid">

        <!-- Search Modal -->
        <div id="searchModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3 id="myModalLabel">Documentation search</h3>
          </div>

          <div class="modal-body">
            <!-- Custom google search -->
            <script>
              (function() {
                var cx = '015016005043623903336:rxraeohqk6w';
                var gcse = document.createElement('script');
                gcse.type = 'text/javascript';
                gcse.async = true;
                gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
                  '//www.google.com/cse/cse.js?cx=' + cx;
                var s = document.getElementsByTagName('script')[0];
                s.parentNode.insertBefore(gcse, s);
              })();
            </script>
            <gcse:search></gcse:search>
          </div>

          <div class="modal-footer">
            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
          </div>
        </div>

        <div class="row-fluid">

          <div class="span3">
            <!-- TODO
            <p style="margin-top: -12px">
              <a class="btn btn-mini btn-primary" style="width: 60px">&laquo; previous</a>
              <a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next &raquo;</a>
            </p>
          -->
            <div id="table-of-contents">
              <ul class="nav nav-list side-nav well sidebar-nav-fixed">

                

                

                  <li class="main">
                    <a href="#routers">Routers</a>
                  </li>

                  
                    <li>
                      <a href="#usage">Usage</a>
                    </li>
                  

                

                  <li class="main">
                    <a href="#api-guide">API Guide</a>
                  </li>

                  
                    <li>
                      <a href="#simplerouter">SimpleRouter</a>
                    </li>
                  
                    <li>
                      <a href="#defaultrouter">DefaultRouter</a>
                    </li>
                  

                

                  <li class="main">
                    <a href="#custom-routers">Custom Routers</a>
                  </li>

                  
                    <li>
                      <a href="#customizing-dynamic-routes">Customizing dynamic routes</a>
                    </li>
                  
                    <li>
                      <a href="#example">Example</a>
                    </li>
                  
                    <li>
                      <a href="#advanced-custom-routers">Advanced custom routers</a>
                    </li>
                  

                

                  <li class="main">
                    <a href="#third-party-packages">Third Party Packages</a>
                  </li>

                  
                    <li>
                      <a href="#drf-nested-routers">DRF Nested Routers</a>
                    </li>
                  
                    <li>
                      <a href="#wqdb">wq.db</a>
                    </li>
                  
                    <li>
                      <a href="#drf-extensions">DRF-extensions</a>
                    </li>
                  

                

                

              </ul>

            </div>
          </div>

          <div id="main-content" class="span9">
            
              
                <a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/routers.py">
                  <span class="label label-info">routers.py</span>
                </a>
              
            

            <h1 id="routers">Routers</h1>
<blockquote>
<p>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.</p>
<p>&mdash; <a href="http://guides.rubyonrails.org/routing.html">Ruby on Rails Documentation</a></p>
</blockquote>
<p>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.</p>
<p>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.</p>
<h2 id="usage">Usage</h2>
<p>Here's an example of a simple URL conf, that uses <code>SimpleRouter</code>.</p>
<pre><code>from rest_framework import routers

router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
urlpatterns = router.urls
</code></pre>
<p>There are two mandatory arguments to the <code>register()</code> method:</p>
<ul>
<li><code>prefix</code> - The URL prefix to use for this set of routes.</li>
<li><code>viewset</code> - The viewset class.</li>
</ul>
<p>Optionally, you may also specify an additional argument:</p>
<ul>
<li><code>base_name</code> - The base to use for the URL names that are created.  If unset the basename will be automatically generated based on the <code>model</code> or <code>queryset</code> attribute on the viewset, if it has one.  Note that if the viewset does not include a <code>model</code> or <code>queryset</code> attribute then you must set <code>base_name</code> when registering the viewset.</li>
</ul>
<p>The example above would generate the following URL patterns:</p>
<ul>
<li>URL pattern: <code>^users/$</code>  Name: <code>'user-list'</code></li>
<li>URL pattern: <code>^users/{pk}/$</code>  Name: <code>'user-detail'</code></li>
<li>URL pattern: <code>^accounts/$</code>  Name: <code>'account-list'</code></li>
<li>URL pattern: <code>^accounts/{pk}/$</code>  Name: <code>'account-detail'</code></li>
</ul>
<hr />
<p><strong>Note</strong>: The <code>base_name</code> argument is used to specify the initial part of the view name pattern.  In the example above, that's the <code>user</code> or <code>account</code> part.</p>
<p>Typically you won't <em>need</em> to specify the <code>base-name</code> argument, but if you have a viewset where you've defined a custom <code>get_queryset</code> method, then the viewset may not have a <code>.queryset</code> attribute set.  If you try to register that viewset you'll see an error like this:</p>
<pre><code>'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
</code></pre>
<p>This means you'll need to explicitly set the <code>base_name</code> argument when registering the viewset, as it could not be automatically determined from the model name.</p>
<hr />
<h3 id="extra-link-and-actions">Extra link and actions</h3>
<p>Any methods on the viewset decorated with <code>@detail_route</code> or <code>@list_route</code> will also be routed.
For example, given a method like this on the <code>UserViewSet</code> class:</p>
<pre><code>from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import detail_route

class UserViewSet(ModelViewSet):
    ...

    @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
    def set_password(self, request, pk=None):
        ...
</code></pre>
<p>The following URL pattern would additionally be generated:</p>
<ul>
<li>URL pattern: <code>^users/{pk}/set_password/$</code>  Name: <code>'user-set-password'</code></li>
</ul>
<p>For more information see the viewset documentation on <a href="../../viewsets.html#marking-extra-actions-for-routing">marking extra actions for routing</a>.</p>
<h1 id="api-guide">API Guide</h1>
<h2 id="simplerouter">SimpleRouter</h2>
<p>This router includes routes for the standard set of <code>list</code>, <code>create</code>, <code>retrieve</code>, <code>update</code>, <code>partial_update</code> and <code>destroy</code> actions.  The viewset can also mark additional methods to be routed, using the <code>@detail_route</code> or <code>@list_route</code> decorators.</p>
<table border=1>
    <tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
    <tr><td rowspan=2>{prefix}/</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
    <tr><td>POST</td><td>create</td></tr>
    <tr><td>{prefix}/{methodname}/</td><td>GET, or as specified by `methods` argument</td><td>`@list_route` decorated method</td><td>{basename}-{methodname}</td></tr>
    <tr><td rowspan=4>{prefix}/{lookup}/</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
    <tr><td>PUT</td><td>update</td></tr>
    <tr><td>PATCH</td><td>partial_update</td></tr>
    <tr><td>DELETE</td><td>destroy</td></tr>
    <tr><td>{prefix}/{lookup}/{methodname}/</td><td>GET, or as specified by `methods` argument</td><td>`@detail_route` decorated method</td><td>{basename}-{methodname}</td></tr>
</table>

<p>By default the URLs created by <code>SimpleRouter</code> are appended with a trailing slash.
This behavior can be modified by setting the <code>trailing_slash</code> argument to <code>False</code> when instantiating the router.  For example:</p>
<pre><code>router = SimpleRouter(trailing_slash=False)
</code></pre>
<p>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.</p>
<p>The router will match lookup values containing any characters except slashes and period characters.  For a more restrictive (or lenient) lookup pattern, set the <code>lookup_value_regex</code> attribute on the viewset.  For example, you can limit the lookup to valid UUIDs:</p>
<pre><code>class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    lookup_field = 'my_model_id'
    lookup_value_regex = '[0-9a-f]{32}'
</code></pre>
<h2 id="defaultrouter">DefaultRouter</h2>
<p>This router is similar to <code>SimpleRouter</code> 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 <code>.json</code> style format suffixes.</p>
<table border=1>
    <tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
    <tr><td>[.format]</td><td>GET</td><td>automatically generated root view</td><td>api-root</td></tr></tr>
    <tr><td rowspan=2>{prefix}/[.format]</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
    <tr><td>POST</td><td>create</td></tr>
    <tr><td>{prefix}/{methodname}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@list_route` decorated method</td><td>{basename}-{methodname}</td></tr>
    <tr><td rowspan=4>{prefix}/{lookup}/[.format]</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
    <tr><td>PUT</td><td>update</td></tr>
    <tr><td>PATCH</td><td>partial_update</td></tr>
    <tr><td>DELETE</td><td>destroy</td></tr>
    <tr><td>{prefix}/{lookup}/{methodname}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@detail_route` decorated method</td><td>{basename}-{methodname}</td></tr>
</table>

<p>As with <code>SimpleRouter</code> the trailing slashes on the URL routes can be removed by setting the <code>trailing_slash</code> argument to <code>False</code> when instantiating the router.</p>
<pre><code>router = DefaultRouter(trailing_slash=False)
</code></pre>
<h1 id="custom-routers">Custom Routers</h1>
<p>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 your 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.</p>
<p>The simplest way to implement a custom router is to subclass one of the existing router classes.  The <code>.routes</code> attribute is used to template the URL patterns that will be mapped to each viewset. The <code>.routes</code> attribute is a list of <code>Route</code> named tuples.</p>
<p>The arguments to the <code>Route</code> named tuple are:</p>
<p><strong>url</strong>: A string representing the URL to be routed.  May include the following format strings:</p>
<ul>
<li><code>{prefix}</code> - The URL prefix to use for this set of routes.</li>
<li><code>{lookup}</code> - The lookup field used to match against a single instance.</li>
<li><code>{trailing_slash}</code> - Either a '/' or an empty string, depending on the <code>trailing_slash</code> argument.</li>
</ul>
<p><strong>mapping</strong>: A mapping of HTTP method names to the view methods</p>
<p><strong>name</strong>: The name of the URL as used in <code>reverse</code> calls. May include the following format string:</p>
<ul>
<li><code>{basename}</code> - The base to use for the URL names that are created.</li>
</ul>
<p><strong>initkwargs</strong>: A dictionary of any additional arguments that should be passed when instantiating the view.  Note that the <code>suffix</code> argument is reserved for identifying the viewset type, used when generating the view name and breadcrumb links.</p>
<h2 id="customizing-dynamic-routes">Customizing dynamic routes</h2>
<p>You can also customize how the <code>@list_route</code> and <code>@detail_route</code> decorators are routed.
To route either or both of these decorators, include a <code>DynamicListRoute</code> and/or <code>DynamicDetailRoute</code> named tuple in the <code>.routes</code> list.</p>
<p>The arguments to <code>DynamicListRoute</code> and <code>DynamicDetailRoute</code> are:</p>
<p><strong>url</strong>: A string representing the URL to be routed. May include the same format strings as <code>Route</code>, and additionally accepts the <code>{methodname}</code> and <code>{methodnamehyphen}</code> format strings.</p>
<p><strong>name</strong>: The name of the URL as used in <code>reverse</code> calls. May include the following format strings: <code>{basename}</code>, <code>{methodname}</code> and <code>{methodnamehyphen}</code>.</p>
<p><strong>initkwargs</strong>: A dictionary of any additional arguments that should be passed when instantiating the view.</p>
<h2 id="example">Example</h2>
<p>The following example will only route to the <code>list</code> and <code>retrieve</code> actions, and does not use the trailing slash convention.</p>
<pre><code>from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter

class CustomReadOnlyRouter(SimpleRouter):
    """
    A router for read-only APIs, which doesn't use trailing slashes.
    """
    routes = [
        Route(
            url=r'^{prefix}$',
            mapping={'get': 'list'},
            name='{basename}-list',
            initkwargs={'suffix': 'List'}
        ),
        Route(
            url=r'^{prefix}/{lookup}$',
           mapping={'get': 'retrieve'},
           name='{basename}-detail',
           initkwargs={'suffix': 'Detail'}
        ),
        DynamicDetailRoute(
            url=r'^{prefix}/{lookup}/{methodnamehyphen}$',
            name='{basename}-{methodnamehyphen}',
            initkwargs={}
        )
    ]
</code></pre>
<p>Let's take a look at the routes our <code>CustomReadOnlyRouter</code> would generate for a simple viewset.</p>
<p><code>views.py</code>:</p>
<pre><code>class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A viewset that provides the standard actions
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_field = 'username'

    @detail_route()
    def group_names(self, request):
        """
        Returns a list of all the group names that the given
        user belongs to.
        """
        user = self.get_object()
        groups = user.groups.all()
        return Response([group.name for group in groups])
</code></pre>
<p><code>urls.py</code>:</p>
<pre><code>router = CustomReadOnlyRouter()
router.register('users', UserViewSet)
urlpatterns = router.urls
</code></pre>
<p>The following mappings would be generated...</p>
<table border=1>
    <tr><th>URL</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
    <tr><td>/users</td><td>GET</td><td>list</td><td>user-list</td></tr>
    <tr><td>/users/{username}</td><td>GET</td><td>retrieve</td><td>user-detail</td></tr>
    <tr><td>/users/{username}/group-names</td><td>GET</td><td>group_names</td><td>user-group-names</td></tr>
</table>

<p>For another example of setting the <code>.routes</code> attribute, see the source code for the <code>SimpleRouter</code> class.</p>
<h2 id="advanced-custom-routers">Advanced custom routers</h2>
<p>If you want to provide totally custom behavior, you can override <code>BaseRouter</code> and override the <code>get_urls(self)</code> 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 <code>self.registry</code> attribute.</p>
<p>You may also want to override the <code>get_default_base_name(self, viewset)</code> method, or else always explicitly set the <code>base_name</code> argument when registering your viewsets with the router.</p>
<h1 id="third-party-packages">Third Party Packages</h1>
<p>The following third party packages are also available.</p>
<h2 id="drf-nested-routers">DRF Nested Routers</h2>
<p>The <a href="https://github.com/alanjds/drf-nested-routers">drf-nested-routers package</a> provides routers and relationship fields for working with nested resources.</p>
<h2 id="wqdb">wq.db</h2>
<p>The <a href="http://wq.io/wq.db">wq.db package</a> provides an advanced <a href="http://wq.io/docs/app.py">Router</a> class (and singleton instance) that extends <code>DefaultRouter</code> with a <code>register_model()</code> API. Much like Django's <code>admin.site.register</code>, the only required argument to <code>app.router.register_model</code> is a model class.  Reasonable defaults for a url prefix and viewset will be inferred from the model and global configuration.</p>
<pre><code>from wq.db.rest import app
from myapp.models import MyModel

app.router.register_model(MyModel)
</code></pre>
<h2 id="drf-extensions">DRF-extensions</h2>
<p>The <a href="http://chibisov.github.io/drf-extensions/docs/"><code>DRF-extensions</code> package</a> provides <a href="http://chibisov.github.io/drf-extensions/docs/#routers">routers</a> for creating <a href="http://chibisov.github.io/drf-extensions/docs/#nested-routes">nested viewsets</a>, <a href="http://chibisov.github.io/drf-extensions/docs/#collection-level-controllers">collection level controllers</a> with <a href="http://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name">customizable endpoint names</a>.</p>

          </div>
          <!--/span-->
        </div>
        <!--/row-->
      </div>
      <!--/.fluid-container-->
    </div>
    <!--/.body content-->
    <div id="push"></div>
  </div>
  <!--/.wrapper -->

  <footer class="span12">
    <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a>
    </p>
  </footer>

  <!-- Le javascript
  ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script src="../../js/jquery-1.8.1-min.js"></script>
  <script src="../../js/prettify-1.0.js"></script>
  <script src="../../js/bootstrap-2.1.1-min.js"></script>
  <script src="../../js/theme.js"></script>

  <script>
    //$('.side-nav').scrollspy()
    var shiftWindow = function() {
      scrollBy(0, -50)
    };
    if (location.hash) shiftWindow();
    window.addEventListener("hashchange", shiftWindow);

    $('.dropdown-menu').on('click touchstart', function(event) {
      event.stopPropagation();
    });

    // Dynamically force sidenav to no higher than browser window
    $('.side-nav').css('max-height', window.innerHeight - 130);

    $(function() {
      $(window).resize(function() {
        $('.side-nav').css('max-height', window.innerHeight - 130);
      });
    });
  </script>
</body>

</html>