Overview
Routers provide a convenient way of automatically determining the URL configuration for your API. They work by registering viewsets and generating URL patterns automatically.BaseRouter
Signature:class BaseRouter
The base class for all routers. Provides the basic interface for registering viewsets and generating URLs.
Instance Methods
register()
Signature:register(prefix, viewset, basename=None)
Registers a viewset with the router.
The URL prefix to use for this set of routes.
The viewset class to register.
The base name for the URL patterns. If unset, will be automatically generated based on the viewset’s
queryset attribute.If the viewset doesn’t have a
queryset attribute, you must specify the basename argument.get_urls()
Signature:get_urls()
Returns a list of URL patterns for all registered viewsets.
Returns: list[URLPattern]
get_default_basename()
Signature:get_default_basename(viewset)
Determines the basename automatically from the viewset.
The viewset class.
str
Raises: AssertionError if the viewset doesn’t have a queryset attribute
is_already_registered()
Signature:is_already_registered(basename)
Checks if a basename is already registered.
The basename to check.
bool
Properties
urls
Returns the list of URL patterns. This property caches the result ofget_urls().
Returns: list[URLPattern]
Attributes
registry
A list of tuples containing(prefix, viewset, basename) for all registered viewsets.
Type: list[tuple[str, class, str]]
SimpleRouter
Signature:class SimpleRouter(BaseRouter)
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.
Constructor
Signature:__init__(trailing_slash=True, use_regex_path=True)
Whether to append trailing slashes to URLs.
Whether to use regex patterns (True) or path converters (False).
Generated Routes
| URL Pattern | HTTP Method | Action | URL Name |
|---|---|---|---|
| / | GET | list | -list |
| / | POST | create | -list |
| // | GET | retrieve | -detail |
| // | PUT | update | -detail |
| // | PATCH | partial_update | -detail |
| // | DELETE | destroy | -detail |
| // | GET* | @action(detail=False) | - |
| /// | GET* | @action(detail=True) | - |
methods argument
Instance Methods
get_default_basename()
Signature:get_default_basename(viewset)
Determines the basename from the viewset’s queryset model name.
The viewset class.
str - Lowercase model name
get_routes()
Signature:get_routes(viewset)
Returns the list of Route namedtuples for the viewset, including dynamically generated routes from @action decorated methods.
The viewset class.
list[Route]
get_method_map()
Signature:get_method_map(viewset, method_map)
Returns a mapping of HTTP methods to actions, filtered to only include mappings that are actually implemented by the viewset.
The viewset class.
Mapping of HTTP methods to action names.
dict[str, str]
get_lookup_regex()
Signature:get_lookup_regex(viewset, lookup_prefix='')
Returns the portion of the URL regex used to match against a single instance.
The viewset class.
Prefix for the lookup (used by nested routers).
str
Uses the viewset’s lookup_field (defaults to 'pk') and lookup_url_kwarg attributes. For regex patterns, uses lookup_value_regex (defaults to [^/.]+). For path converters, uses lookup_value_converter (defaults to str).
Customizing Lookup Patterns
For regex patterns, setlookup_value_regex on your viewset:
lookup_value_converter:
Class Attributes
routes
A list of Route and DynamicRoute namedtuples that define the URL patterns. Type:list[Route | DynamicRoute]
DefaultRouter
Signature:class DefaultRouter(SimpleRouter)
Extends SimpleRouter by additionally including a default API root view that returns a response containing hyperlinks to all the list views. Also generates routes for optional .json style format suffixes.
Constructor
Signature:__init__(trailing_slash=True, use_regex_path=True, root_renderers=None)
Whether to append trailing slashes to URLs.
Whether to use regex patterns (True) or path converters (False).
List of renderer classes for the root view. Defaults to
DEFAULT_RENDERER_CLASSES.Generated Routes
Includes all routes from SimpleRouter, plus:| URL Pattern | HTTP Method | Action | URL Name |
|---|---|---|---|
| / | GET | auto-generated root view | api-root |
.json, etc.) are appended to all URLs if include_format_suffixes=True.
Instance Methods
get_api_root_view()
Signature:get_api_root_view(api_urls=None)
Returns the root view for the API.
List of URL patterns.
callable - View function
Class Attributes
include_root_view
Whether to include the API root view. Type:bool
Default: True
include_format_suffixes
Whether to include format suffix patterns (.json, .xml, etc.).
Type: bool
Default: True
root_view_name
The URL name for the root view. Type:str
Default: 'api-root'
APIRootView
The view class to use for the root view. Type:class
Default: APIRootView
APISchemaView
The view class to use for schema generation. Type:class
Default: SchemaView
SchemaGenerator
The schema generator class. Type:class
Default: SchemaGenerator
Route Namedtuples
Route
Defines a standard route pattern. Fields:URL pattern string. May include format strings:
{prefix}, {lookup}, {trailing_slash}.Mapping of HTTP method names to view action names.
Name pattern for URL reversing. May include format string:
{basename}.Whether this is a detail route (True) or list route (False).
Additional arguments passed when instantiating the view.
DynamicRoute
Defines a route pattern for@action decorated methods.
Fields:
URL pattern string. May include format strings:
{prefix}, {lookup}, {trailing_slash}, {url_path}.Name pattern for URL reversing. May include format strings:
{basename}, {url_name}.Whether this is a detail route (True) or list route (False).
Additional arguments passed when instantiating the view.
Custom Routers
You can create custom routers by subclassingSimpleRouter and setting the .routes attribute.
Advanced Custom Routers
For complete control, overrideBaseRouter and implement get_urls():
self.registry as a list of (prefix, viewset, basename) tuples.
APIRootView
Signature:class APIRootView(APIView)
The default root view used by DefaultRouter.
Class Attributes
api_root_dict
A dictionary mapping URL names to their prefixes. Type:dict[str, str] | None
Default: None
_ignore_model_permissions
When True, model permissions are not checked. Type:bool
Default: True
schema
The schema for this view. Set toNone to exclude from schema generation.
Type: AutoSchema | None
Default: None
Instance Methods
get()
Signature:get(request, *args, **kwargs)
Returns a plain {"name": "hyperlink"} response with links to all registered viewsets.
The request instance.
Positional arguments.
Keyword arguments.
Response
Using Routers with URL Configuration
Appending to URL Patterns
Using include()
With Application Namespace
With Application and Instance Namespace
Utility Functions
escape_curly_brackets()
Signature:escape_curly_brackets(url_path)
Double brackets in regex of url_path for escape string formatting.
The URL path to escape.
str
flatten()
Signature:flatten(list_of_lists)
Takes an iterable of iterables, returns a single iterable containing all items.
Nested iterables to flatten.
itertools.chain