django-rest-framework/docs/api-guide/routers.md
2013-04-25 17:39:33 +01:00

3.9 KiB

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 DefaultRouter.

router = routers.SimpleRouter()
router.register(r'users', UserViewSet, 'user')
router.register(r'accounts', AccountViewSet, 'account')
urlpatterns = router.urls

There are three arguments to the register() method:

  • prefix - The URL prefix to use for this set of routes.
  • viewset - The viewset class.
  • basename - The base to use for the URL names that are created.

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'

Any @link or @action methods on the viewsets will also be routed. For example, a given method like this on the UserViewSet class:

@action(permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
    ...

The following URL pattern would additionally be generated:

  • URL pattern: ^users/{pk}/set_password/$ Name: 'user-set-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 @link or @action decorators.

URL StyleHTTP MethodActionURL Name
{prefix}/GETlist{basename}-list
POSTcreate
{prefix}/{lookup}/GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{methodname}/GET@link decorated method{basename}-{methodname}
POST@action decorated method

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}/{lookup}/[.format]GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{methodname}/[.format]GET@link decorated method{basename}-{methodname}
POST@action decorated method

Custom Routers