Renderers  Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client. — Django documentation  REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types. How the renderer is determined The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request. The basic process of content negotiation involves examining the request's Accept header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL http://example.com/api/users_count.json might be an endpoint that always returns JSON data. For more information see the documentation on content negotiation. Setting the renderers The default set of renderers may be set globally, using the DEFAULT_RENDERER_CLASSES setting. For example, the following settings would use JSON as the main media type and also include the self describing API. REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ]
}
 You can also set the renderers used for an individual view, or viewset, using the APIView class-based views. from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView

class UserCountView(APIView):
    """
    A view that returns the count of active users in JSON.
    """
    renderer_classes = [JSONRenderer]

    def get(self, request, format=None):
        user_count = User.objects.filter(active=True).count()
        content = {'user_count': user_count}
        return Response(content)
 Or, if you're using the @api_view decorator with function based views. @api_view(['GET'])
@renderer_classes([JSONRenderer])
def user_count_view(request, format=None):
    """
    A view that returns the count of active users in JSON.
    """
    user_count = User.objects.filter(active=True).count()
    content = {'user_count': user_count}
    return Response(content)
 Ordering of renderer classes It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an Accept: */* header, or not including an Accept header at all, then REST framework will select the first renderer in the list to use for the response. For example if your API serves JSON responses and the HTML browsable API, you might want to make JSONRenderer your default renderer, in order to send JSON responses to clients that do not specify an Accept header. If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making TemplateHTMLRenderer your default renderer, in order to play nicely with older browsers that send broken accept headers. API Reference JSONRenderer Renders the request data into JSON, using utf-8 encoding. Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace: {"unicode black star":"★","value":999}
 The client may additionally include an 'indent' media type parameter, in which case the returned JSON will be indented. For example Accept: application/json; indent=4. {
    "unicode black star": "★",
    "value": 999
}
 The default JSON encoding style can be altered using the UNICODE_JSON and COMPACT_JSON settings keys. .media_type: application/json .format: 'json' .charset: None TemplateHTMLRenderer Renders data to HTML, using Django's standard template rendering. Unlike other renderers, the data passed to the Response does not need to be serialized. Also, unlike other renderers, you may want to include a template_name argument when creating the Response. The TemplateHTMLRenderer will create a RequestContext, using the response.data as the context dict, and determine a template name to use to render the context. Note: When used with a view that makes use of a serializer the Response sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example: response.data = {'results': response.data}
 The template name is determined by (in order of preference):  An explicit template_name argument passed to the response. An explicit .template_name attribute set on this class. The return result of calling view.get_template_names().  An example of a view that uses TemplateHTMLRenderer: class UserDetail(generics.RetrieveAPIView):
    """
    A view that returns a templated HTML representation of a given user.
    """
    queryset = User.objects.all()
    renderer_classes = [TemplateHTMLRenderer]

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return Response({'user': self.object}, template_name='user_detail.html')
 You can use TemplateHTMLRenderer either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. If you're building websites that use TemplateHTMLRenderer along with other renderer classes, you should consider listing TemplateHTMLRenderer as the first class in the renderer_classes list, so that it will be prioritised first even for browsers that send poorly formed ACCEPT: headers. See the HTML & Forms Topic Page for further examples of TemplateHTMLRenderer usage. .media_type: text/html .format: 'html' .charset: utf-8 See also: StaticHTMLRenderer StaticHTMLRenderer A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned. An example of a view that uses StaticHTMLRenderer: @api_view(['GET'])
@renderer_classes([StaticHTMLRenderer])
def simple_html_view(request):
    data = '
Hello, world
'
    return Response(data)
 You can use StaticHTMLRenderer either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. .media_type: text/html .format: 'html' .charset: utf-8 See also: TemplateHTMLRenderer BrowsableAPIRenderer Renders data into HTML for the Browsable API:  This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. .media_type: text/html .format: 'api' .charset: utf-8 .template: 'rest_framework/api.html' Customizing BrowsableAPIRenderer By default the response content will be rendered with the highest priority renderer apart from BrowsableAPIRenderer. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the get_default_renderer() method. For example: class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
    def get_default_renderer(self, view):
        return JSONRenderer()
 AdminRenderer Renders data into HTML for an admin-like display:  This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data. Note that views that have nested or list serializers for their input won't work well with the AdminRenderer, as the HTML forms are unable to properly support them. Note: The AdminRenderer is only able to include links to detail pages when a properly configured URL_FIELD_NAME (url by default) attribute is present in the data. For HyperlinkedModelSerializer this will be the case, but for ModelSerializer or plain Serializer classes you'll need to make sure to include the field explicitly. For example here we use models get_absolute_url method: class AccountSerializer(serializers.ModelSerializer):
    url = serializers.CharField(source='get_absolute_url', read_only=True)

    class Meta:
        model = Account
 .media_type: text/html .format: 'admin' .charset: utf-8 .template: 'rest_framework/admin.html' HTMLFormRenderer Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing <form> tags, a hidden CSRF input or any submit buttons. This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the render_form template tag. {% load rest_framework %}

<form action="/submit-report/" method="post">
    {% csrf_token %}
    {% render_form serializer %}
    <input type="submit" value="Save" />
</form>
 For more information see the HTML & Forms documentation. .media_type: text/html .format: 'form' .charset: utf-8 .template: 'rest_framework/horizontal/form.html' MultiPartRenderer This renderer is used for rendering HTML multipart form data. It is not suitable as a response renderer, but is instead used for creating test requests, using REST framework's test client and test request factory. .media_type: multipart/form-data; boundary=BoUnDaRyStRiNg .format: 'multipart' .charset: utf-8 Custom renderers To implement a custom renderer, you should override BaseRenderer, set the .media_type and .format properties, and implement the .render(self, data, media_type=None, renderer_context=None) method. The method should return a bytestring, which will be used as the body of the HTTP response. The arguments passed to the .render() method are: data The request data, as set by the Response() instantiation. media_type=None Optional. If provided, this is the accepted media type, as determined by the content negotiation stage. Depending on the client's Accept: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example "application/json; nested=true". renderer_context=None Optional. If provided, this is a dictionary of contextual information provided by the view. By default this will include the following keys: view, request, response, args, kwargs. Example The following is an example plaintext renderer that will return a response with the data parameter as the content of the response. from django.utils.encoding import smart_text
from rest_framework import renderers

class PlainTextRenderer(renderers.BaseRenderer):
    media_type = 'text/plain'
    format = 'txt'

    def render(self, data, media_type=None, renderer_context=None):
        return smart_text(data, encoding=self.charset)
 Setting the character set By default renderer classes are assumed to be using the UTF-8 encoding. To use a different encoding, set the charset attribute on the renderer. class PlainTextRenderer(renderers.BaseRenderer):
    media_type = 'text/plain'
    format = 'txt'
    charset = 'iso-8859-1'

    def render(self, data, media_type=None, renderer_context=None):
        return data.encode(self.charset)
 Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the Response class, with the charset attribute set on the renderer used to determine the encoding. If the renderer returns a bytestring representing raw binary content, you should set a charset value of None, which will ensure the Content-Type header of the response will not have a charset value set. In some cases you may also want to set the render_style attribute to 'binary'. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string. class JPEGRenderer(renderers.BaseRenderer):
    media_type = 'image/jpeg'
    format = 'jpg'
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        return data
 Advanced renderer usage You can do some pretty flexible things using REST framework's renderers. Some examples...  Provide either flat or nested representations from the same endpoint, depending on the requested media type. Serve both regular HTML webpages, and JSON based API responses from the same endpoints. Specify multiple types of HTML representation for API clients to use. Underspecify a renderer's media type, such as using media_type = 'image/*', and use the Accept header to vary the encoding of the response.  Varying behaviour by media type In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access request.accepted_renderer to determine the negotiated renderer that will be used for the response. For example: @api_view(['GET'])
@renderer_classes([TemplateHTMLRenderer, JSONRenderer])
def list_users(request):
    """
    A view that can return JSON or HTML representations
    of the users in the system.
    """
    queryset = Users.objects.filter(active=True)

    if request.accepted_renderer.format == 'html':
        # TemplateHTMLRenderer takes a context dict,
        # and additionally requires a 'template_name'.
        # It does not require serialization.
        data = {'users': queryset}
        return Response(data, template_name='list_users.html')

    # JSONRenderer requires serialized data as normal.
    serializer = UserSerializer(instance=queryset)
    data = serializer.data
    return Response(data)
 Underspecifying the media type In some cases you might want a renderer to serve a range of media types. In this case you can underspecify the media types it should respond to, by using a media_type value such as image/*, or */*. If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the content_type attribute. For example: return Response(data, content_type='image/png')
 Designing your media types For the purposes of many Web APIs, simple JSON responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and HATEOAS you'll need to consider the design and usage of your media types in more detail. In the words of Roy Fielding, "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.". For good examples of custom media types, see GitHub's use of a custom application/vnd.github+json media type, and Mike Amundsen's IANA approved application/vnd.collection+json JSON-based hypermedia. HTML error views Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an Http404 or PermissionDenied exception, or a subclass of APIException. If you're using either the TemplateHTMLRenderer or the StaticHTMLRenderer and an exception is raised, the behavior is slightly different, and mirrors Django's default handling of error views. Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.  Load and render a template named {status_code}.html. Load and render a template named api_exception.html. Render the HTTP status code and text, for example "404 Not Found".  Templates will render with a RequestContext which includes the status_code and details keys. Note: If DEBUG=True, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text. Third party packages The following third party packages are also available. YAML REST framework YAML provides YAML parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Installation & configuration Install using pip. $ pip install djangorestframework-yaml
 Modify your REST framework settings. REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework_yaml.parsers.YAMLParser',
    ],
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework_yaml.renderers.YAMLRenderer',
    ],
}
 XML REST Framework XML provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Installation & configuration Install using pip. $ pip install djangorestframework-xml
 Modify your REST framework settings. REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework_xml.parsers.XMLParser',
    ],
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework_xml.renderers.XMLRenderer',
    ],
}
 JSONP REST framework JSONP provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Warning: If you require cross-domain AJAX requests, you should generally be using the more modern approach of CORS as an alternative to JSONP. See the CORS documentation for more details. The jsonp approach is essentially a browser hack, and is only appropriate for globally readable API endpoints, where GET requests are unauthenticated and do not require any user permissions. Installation & configuration Install using pip. $ pip install djangorestframework-jsonp
 Modify your REST framework settings. REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework_jsonp.renderers.JSONPRenderer',
    ],
}
 MessagePack MessagePack is a fast, efficient binary serialization format. Juan Riaza maintains the djangorestframework-msgpack package which provides MessagePack renderer and parser support for REST framework. XLSX (Binary Spreadsheet Endpoints) XLSX is the world's most popular binary spreadsheet format. Tim Allen of The Wharton School maintains drf-renderer-xlsx, which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis. Installation & configuration Install using pip. $ pip install drf-renderer-xlsx
 Modify your REST framework settings. REST_FRAMEWORK = {
    ...

    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        'drf_renderer_xlsx.renderers.XLSXRenderer',
    ],
}
 To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the Content-Disposition header. If no filename is provided, it will default to export.xlsx. For example: from rest_framework.viewsets import ReadOnlyModelViewSet
from drf_renderer_xlsx.mixins import XLSXFileMixin
from drf_renderer_xlsx.renderers import XLSXRenderer

from .models import MyExampleModel
from .serializers import MyExampleSerializer

class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
    queryset = MyExampleModel.objects.all()
    serializer_class = MyExampleSerializer
    renderer_classes = [XLSXRenderer]
    filename = 'my_export.xlsx'
 CSV Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. Mjumbe Poe maintains the djangorestframework-csv package which provides CSV renderer support for REST framework. UltraJSON UltraJSON is an optimized C JSON encoder which can give significantly faster JSON rendering. Adam Mertz maintains drf_ujson2, a fork of the now unmaintained drf-ujson-renderer, which implements JSON rendering using the UJSON package. CamelCase JSON djangorestframework-camel-case provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by Vitaly Babiy. Pandas (CSV, Excel, PNG) Django REST Pandas provides a serializer and renderers that support additional data processing and output via the Pandas DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both .xls and .xlsx), and a number of other formats. It is maintained by S. Andrew Sheppard as part of the wq Project. LaTeX Rest Framework Latex provides a renderer that outputs PDFs using Laulatex. It is maintained by Pebble (S/F Software). renderers.py


Requests  If you're doing REST-based web service stuff ... you should ignore request.POST. — Malcom Tredinnick, Django developers group  REST framework's Request class extends the standard HttpRequest, adding support for REST framework's flexible request parsing and request authentication. Request parsing REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data. .data request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES attributes except that:  It includes all parsed content, including file and non-file inputs. It supports parsing the content of HTTP methods other than POST, meaning that you can access the content of PUT and PATCH requests. It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data similarly to how you handle incoming form data.  For more details see the parsers documentation. .query_params request.query_params is a more correctly named synonym for request.GET. For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just GET requests. .parsers The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Parser instances, based on the parser_classes set on the view or based on the DEFAULT_PARSER_CLASSES setting. You won't typically need to access this property. Note: If a client sends malformed content, then accessing request.data may raise a ParseError. By default REST framework's APIView class or @api_view decorator will catch the error and return a 400 Bad Request response. If a client sends a request with a content-type that cannot be parsed then a UnsupportedMediaType exception will be raised, which by default will be caught and return a 415 Unsupported Media Type response. Content negotiation The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialization schemes for different media types. .accepted_renderer The renderer instance that was selected by the content negotiation stage. .accepted_media_type A string representing the media type that was accepted by the content negotiation stage. Authentication REST framework provides flexible, per-request authentication, that gives you the ability to:  Use different authentication policies for different parts of your API. Support the use of multiple authentication policies. Provide both user and token information associated with the incoming request.  .user request.user typically returns an instance of django.contrib.auth.models.User, although the behavior depends on the authentication policy being used. If the request is unauthenticated the default value of request.user is an instance of django.contrib.auth.models.AnonymousUser. For more details see the authentication documentation. .auth request.auth returns any additional authentication context. The exact behavior of request.auth depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against. If the request is unauthenticated, or if no additional context is present, the default value of request.auth is None. For more details see the authentication documentation. .authenticators The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Authentication instances, based on the authentication_classes set on the view or based on the DEFAULT_AUTHENTICATORS setting. You won't typically need to access this property. Note: You may see a WrappedAttributeError raised when calling the .user or .auth properties. These errors originate from an authenticator as a standard AttributeError, however it's necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the AttributeError originates from the authenticator and will instead assume that the request object does not have a .user or .auth property. The authenticator will need to be fixed. Browser enhancements REST framework supports a few browser enhancements such as browser-based PUT, PATCH and DELETE forms. .method request.method returns the uppercased string representation of the request's HTTP method. Browser-based PUT, PATCH and DELETE forms are transparently supported. For more information see the browser enhancements documentation. .content_type request.content_type, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided. You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior. If you do need to access the content type of the request you should use the .content_type property in preference to using request.META.get('HTTP_CONTENT_TYPE'), as it provides transparent support for browser-based non-form content. For more information see the browser enhancements documentation. .stream request.stream returns a stream representing the content of the request body. You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior. Standard HttpRequest attributes As REST framework's Request extends Django's HttpRequest, all the other standard attributes and methods are also available. For example the request.META and request.session dictionaries are available as normal. Note that due to implementation reasons the Request class does not inherit from HttpRequest class, but instead extends the class using composition. request.py


Responses  Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process. — Django documentation  REST framework supports HTTP content negotiation by providing a Response class which allows you to return content that can be rendered into multiple content types, depending on the client request. The Response class subclasses Django's SimpleTemplateResponse. Response objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. There's no requirement for you to use the Response class, you can also return regular HttpResponse or StreamingHttpResponse objects from your views if required. Using the Response class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats. Unless you want to heavily customize REST framework for some reason, you should always use an APIView class or @api_view function for views that return Response objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view. Creating responses Response() Signature: Response(data, status=None, template_name=None, headers=None, content_type=None) Unlike regular HttpResponse objects, you do not instantiate Response objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives. The renderers used by the Response class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the Response object. You can use REST framework's Serializer classes to perform this data serialization, or use your own custom serialization. Arguments:
data: The serialized data for the response.
status: A status code for the response. Defaults to 200. See also status codes.
template_name: A template name to use if HTMLRenderer is selected.
headers: A dictionary of HTTP headers to use in the response.
content_type: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly.  Attributes .data The unrendered, serialized data of the response. .status_code The numeric status code of the HTTP response. .content The rendered content of the response. The .render() method must have been called before .content can be accessed. .template_name The template_name, if supplied. Only required if HTMLRenderer or some other custom template renderer is the accepted renderer for the response. .accepted_renderer The renderer instance that will be used to render the response. Set automatically by the APIView or @api_view immediately before the response is returned from the view. .accepted_media_type The media type that was selected by the content negotiation stage. Set automatically by the APIView or @api_view immediately before the response is returned from the view. .renderer_context A dictionary of additional context information that will be passed to the renderer's .render() method. Set automatically by the APIView or @api_view immediately before the response is returned from the view. Standard HttpResponse attributes The Response class extends SimpleTemplateResponse, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way: response = Response()
response['Cache-Control'] = 'no-cache'
 .render() Signature: .render() As with any other TemplateResponse, this method is called to render the serialized data of the response into the final response content. When .render() is called, the response content will be set to the result of calling the .render(data, accepted_media_type, renderer_context) method on the accepted_renderer instance. You won't typically need to call .render() yourself, as it's handled by Django's standard response cycle. response.py


Generic views  Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself. — Django Documentation  One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns. The generic views provided by REST framework allow you to quickly build API views that map closely to your database models. If the generic views don't suit the needs of your API, you can drop down to using the regular APIView class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views. Examples Typically when using the generic views, you'll override the view, and set several class attributes. from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
from rest_framework import generics
from rest_framework.permissions import IsAdminUser

class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [IsAdminUser]
 For more complex cases you might also want to override various methods on the view class. For example. class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [IsAdminUser]

    def list(self, request):
        # Note the use of `get_queryset()` instead of `self.queryset`
        queryset = self.get_queryset()
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)
 For very simple cases you might want to pass through any class attributes using the .as_view() method. For example, your URLconf might include something like the following entry: path('users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
 API Reference GenericAPIView This class extends REST framework's APIView class, adding commonly required behavior for standard list and detail views. Each of the concrete generic views provided is built by combining GenericAPIView, with one or more mixin classes. Attributes Basic settings: The following attributes control the basic view behavior.
queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.
serializer_class - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the get_serializer_class() method.
lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to 'pk'. Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value.
lookup_url_kwarg - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as lookup_field.  Pagination: The following attributes are used to control pagination when used with list views.
pagination_class - The pagination class that should be used when paginating list results. Defaults to the same value as the DEFAULT_PAGINATION_CLASS setting, which is 'rest_framework.pagination.PageNumberPagination'. Setting pagination_class=None will disable pagination on this view.  Filtering:
filter_backends - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the DEFAULT_FILTER_BACKENDS setting.  Methods Base methods: get_queryset(self) Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the queryset attribute. This method should always be used rather than accessing self.queryset directly, as self.queryset gets evaluated only once, and those results are cached for all subsequent requests. May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request. For example: def get_queryset(self):
    user = self.request.user
    return user.accounts.all()
 get_object(self) Returns an object instance that should be used for detail views. Defaults to using the lookup_field parameter to filter the base queryset. May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg. For example: def get_object(self):
    queryset = self.get_queryset()
    filter = {}
    for field in self.multiple_lookup_fields:
        filter[field] = self.kwargs[field]

    obj = get_object_or_404(queryset, **filter)
    self.check_object_permissions(self.request, obj)
    return obj
 Note that if your API doesn't include any object level permissions, you may optionally exclude the self.check_object_permissions, and simply return the object from the get_object_or_404 lookup. filter_queryset(self, queryset) Given a queryset, filter it with whichever filter backends are in use, returning a new queryset. For example: def filter_queryset(self, queryset):
    filter_backends = [CategoryFilter]

    if 'geo_route' in self.request.query_params:
        filter_backends = [GeoRouteFilter, CategoryFilter]
    elif 'geo_point' in self.request.query_params:
        filter_backends = [GeoPointFilter, CategoryFilter]

    for backend in list(filter_backends):
        queryset = backend().filter_queryset(self.request, queryset, view=self)

    return queryset
 get_serializer_class(self) Returns the class that should be used for the serializer. Defaults to returning the serializer_class attribute. May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users. For example: def get_serializer_class(self):
    if self.request.user.is_staff:
        return FullAccountSerializer
    return BasicAccountSerializer
 Save and deletion hooks: The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
perform_create(self, serializer) - Called by CreateModelMixin when saving a new object instance.
perform_update(self, serializer) - Called by UpdateModelMixin when saving an existing object instance.
perform_destroy(self, instance) - Called by DestroyModelMixin when deleting an object instance.  These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument. def perform_create(self, serializer):
    serializer.save(user=self.request.user)
 These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update. def perform_update(self, serializer):
    instance = serializer.save()
    send_email_confirmation(user=self.request.user, modified=instance)
 You can also use these hooks to provide additional validation, by raising a ValidationError(). This can be useful if you need some validation logic to apply at the point of database save. For example: def perform_create(self, serializer):
    queryset = SignupRequest.objects.filter(user=self.request.user)
    if queryset.exists():
        raise ValidationError('You have already signed up')
    serializer.save(user=self.request.user)
 Other methods: You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using GenericAPIView.
get_serializer_context(self) - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including 'request', 'view' and 'format' keys.
get_serializer(self, instance=None, data=None, many=False, partial=False) - Returns a serializer instance.
get_paginated_response(self, data) - Returns a paginated style Response object.
paginate_queryset(self, queryset) - Paginate a queryset if required, either returning a page object, or None if pagination is not configured for this view.
filter_queryset(self, queryset) - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.  Mixins The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as .get() and .post(), directly. This allows for more flexible composition of behavior. The mixin classes can be imported from rest_framework.mixins. ListModelMixin Provides a .list(request, *args, **kwargs) method, that implements listing a queryset. If the queryset is populated, this returns a 200 OK response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated. CreateModelMixin Provides a .create(request, *args, **kwargs) method, that implements creating and saving a new model instance. If an object is created this returns a 201 Created response, with a serialized representation of the object as the body of the response. If the representation contains a key named url, then the Location header of the response will be populated with that value. If the request data provided for creating the object was invalid, a 400 Bad Request response will be returned, with the error details as the body of the response. RetrieveModelMixin Provides a .retrieve(request, *args, **kwargs) method, that implements returning an existing model instance in a response. If an object can be retrieved this returns a 200 OK response, with a serialized representation of the object as the body of the response. Otherwise it will return a 404 Not Found. UpdateModelMixin Provides a .update(request, *args, **kwargs) method, that implements updating and saving an existing model instance. Also provides a .partial_update(request, *args, **kwargs) method, which is similar to the update method, except that all fields for the update will be optional. This allows support for HTTP PATCH requests. If an object is updated this returns a 200 OK response, with a serialized representation of the object as the body of the response. If the request data provided for updating the object was invalid, a 400 Bad Request response will be returned, with the error details as the body of the response. DestroyModelMixin Provides a .destroy(request, *args, **kwargs) method, that implements deletion of an existing model instance. If an object is deleted this returns a 204 No Content response, otherwise it will return a 404 Not Found. Concrete View Classes The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior. The view classes can be imported from rest_framework.generics. CreateAPIView Used for create-only endpoints. Provides a post method handler. Extends: GenericAPIView, CreateModelMixin ListAPIView Used for read-only endpoints to represent a collection of model instances. Provides a get method handler. Extends: GenericAPIView, ListModelMixin RetrieveAPIView Used for read-only endpoints to represent a single model instance. Provides a get method handler. Extends: GenericAPIView, RetrieveModelMixin DestroyAPIView Used for delete-only endpoints for a single model instance. Provides a delete method handler. Extends: GenericAPIView, DestroyModelMixin UpdateAPIView Used for update-only endpoints for a single model instance. Provides put and patch method handlers. Extends: GenericAPIView, UpdateModelMixin ListCreateAPIView Used for read-write endpoints to represent a collection of model instances. Provides get and post method handlers. Extends: GenericAPIView, ListModelMixin, CreateModelMixin RetrieveUpdateAPIView Used for read or update endpoints to represent a single model instance. Provides get, put and patch method handlers. Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin RetrieveDestroyAPIView Used for read or delete endpoints to represent a single model instance. Provides get and delete method handlers. Extends: GenericAPIView, RetrieveModelMixin, DestroyModelMixin RetrieveUpdateDestroyAPIView Used for read-write-delete endpoints to represent a single model instance. Provides get, put, patch and delete method handlers. Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin Customizing the generic views Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed. Creating custom mixins For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following: class MultipleFieldLookupMixin:
    """
    Apply this mixin to any view or viewset to get multiple field filtering
    based on a `lookup_fields` attribute, instead of the default single field filtering.
    """
    def get_object(self):
        queryset = self.get_queryset()             # Get the base queryset
        queryset = self.filter_queryset(queryset)  # Apply any filter backends
        filter = {}
        for field in self.lookup_fields:
            if self.kwargs[field]: # Ignore empty fields.
                filter[field] = self.kwargs[field]
        obj = get_object_or_404(queryset, **filter)  # Lookup the object
        self.check_object_permissions(self.request, obj)
        return obj
 You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior. class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_fields = ['account', 'username']
 Using custom mixins is a good option if you have custom behavior that needs to be used. Creating custom base classes If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example: class BaseRetrieveView(MultipleFieldLookupMixin,
                       generics.RetrieveAPIView):
    pass

class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
                                    generics.RetrieveUpdateDestroyAPIView):
    pass
 Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project. PUT as create Prior to version 3.0 the REST framework mixins treated PUT as either an update or a create operation, depending on if the object already existed or not. Allowing PUT as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning 404 responses. Both styles "PUT as 404" and "PUT as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious. If you need to generic PUT-as-create behavior you may want to include something like this AllowPUTAsCreateMixin class as a mixin to your views. Third party packages The following third party packages provide additional generic view implementations. Django Rest Multiple Models Django Rest Multiple Models provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request. mixins.pygenerics.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. from rest_framework import routers

router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
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: '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... router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)

urlpatterns = [
    path('forgot-password/', ForgotPasswordFormView.as_view()),
]

urlpatterns += router.urls
 Alternatively you can use Django's include function, like so... urlpatterns = [
    path('forgot-password', ForgotPasswordFormView.as_view()),
    path('', include(router.urls)),
]
 You may use include with an application namespace: urlpatterns = [
    path('forgot-password/', ForgotPasswordFormView.as_view()),
    path('api/', include((router.urls, 'app_name'))),
]
 Or both an application and instance namespace: urlpatterns = [
    path('forgot-password/', ForgotPasswordFormView.as_view()),
    path('api/', include((router.urls, 'app_name'), namespace='instance_name')),
]
 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 parameters on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as view_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 clash you 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: from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import action

class UserViewSet(ModelViewSet):
    ...

    @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
    def set_password(self, request, pk=None):
        ...
 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: from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import action

class UserViewSet(ModelViewSet):
    ...

    @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],
            url_path='change-password', url_name='change_password')
    def set_password(self, request, pk=None):
        ...
 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 Style
HTTP Method
Action
URL Name

{prefix}/
GET
list
{basename}-list

POST
create

{prefix}/{url_path}/
GET, or as specified by `methods` argument
`@action(detail=False)` decorated method
{basename}-{url_name}

{prefix}/{lookup}/
GET
retrieve
{basename}-detail

PUT
update

PATCH
partial_update

DELETE
destroy

{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: 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: class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    lookup_field = 'my_model_id'
    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 Style
HTTP Method
Action
URL Name

[.format]
GET
automatically generated root view
api-root

{prefix}/[.format]
GET
list
{basename}-list

POST
create

{prefix}/{url_path}/[.format]
GET, or as specified by `methods` argument
`@action(detail=False)` decorated method
{basename}-{url_name}

{prefix}/{lookup}/[.format]
GET
retrieve
{basename}-detail

PUT
update

PATCH
partial_update

DELETE
destroy

{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. 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. from rest_framework.routers import Route, DynamicRoute, 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',
            detail=False,
            initkwargs={'suffix': 'List'}
        ),
        Route(
            url=r'^{prefix}/{lookup}$',
            mapping={'get': 'retrieve'},
            name='{basename}-detail',
            detail=True,
            initkwargs={'suffix': 'Detail'}
        ),
        DynamicRoute(
            url=r'^{prefix}/{lookup}/{url_path}$',
            name='{basename}-{url_name}',
            detail=True,
            initkwargs={}
        )
    ]
 Let's take a look at the routes our CustomReadOnlyRouter would generate for a simple viewset. views.py: class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A viewset that provides the standard actions
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_field = 'username'

    @action(detail=True)
    def group_names(self, request, pk=None):
        """
        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])
 urls.py: router = CustomReadOnlyRouter()
router.register('users', UserViewSet)
urlpatterns = router.urls
 The following mappings would be generated...
URL
HTTP Method
Action
URL Name

/users
GET
list
user-list

/users/{username}
GET
retrieve
user-detail

/users/{username}/group_names
GET
group_names
user-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. from wq.db import rest
from myapp.models import MyModel

rest.router.register_model(MyModel)
 DRF-extensions The DRF-extensions package provides routers for creating nested viewsets, collection level controllers with customizable endpoint names. routers.py


Schema  A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support. — Heroku, JSON Schema for the Heroku Platform API  API schemas are a useful tool that allow for a range of use cases, including generating reference documentation, or driving dynamic client libraries that can interact with your API. Django REST Framework provides support for automatic generation of OpenAPI schemas. Overview Schema generation has several moving parts. It's worth having an overview:
SchemaGenerator is a top-level class that is responsible for walking your configured URL patterns, finding APIView subclasses, enquiring for their schema representation, and compiling the final schema object.
AutoSchema encapsulates all the details necessary for per-view schema introspection. Is attached to each view via the schema attribute. You subclass AutoSchema in order to customize your schema. The generateschema management command allows you to generate a static schema offline. Alternatively, you can route SchemaView to dynamically generate and serve your schema.
settings.DEFAULT_SCHEMA_CLASS allows you to specify an AutoSchema subclass to serve as your project's default.  The following sections explain more. Generating an OpenAPI Schema Install dependencies pip install pyyaml uritemplate

pyyaml is used to generate schema into YAML-based OpenAPI format.
uritemplate is used internally to get parameters in path.  Generating a static schema with the generateschema management command If your schema is static, you can use the generateschema management command: ./manage.py generateschema --file openapi-schema.yml
 Once you've generated a schema in this way you can annotate it with any additional information that cannot be automatically inferred by the schema generator. You might want to check your API schema into version control and update it with each new release, or serve the API schema from your site's static media. Generating a dynamic schema with SchemaView If you require a dynamic schema, because foreign key choices depend on database values, for example, you can route a SchemaView that will generate and serve your schema on demand. To route a SchemaView, use the get_schema_view() helper. In urls.py: from rest_framework.schemas import get_schema_view

urlpatterns = [
    # ...
    # Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
    #   * `title` and `description` parameters are passed to `SchemaGenerator`.
    #   * Provide view name for use with `reverse()`.
    path('openapi', get_schema_view(
        title="Your Project",
        description="API for all things …",
        version="1.0.0"
    ), name='openapi-schema'),
    # ...
]
 get_schema_view() The get_schema_view() helper takes the following keyword arguments:
title: May be used to provide a descriptive title for the schema definition.
description: Longer descriptive text.
version: The version of the API.  url: May be used to pass a canonical base URL for the schema. schema_view = get_schema_view(
    title='Server Monitoring API',
    url='https://www.example.org/api/'
)
   urlconf: A string representing the import path to the URL conf that you want to generate an API schema for. This defaults to the value of Django's ROOT_URLCONF setting. schema_view = get_schema_view(
    title='Server Monitoring API',
    url='https://www.example.org/api/',
    urlconf='myproject.urls'
)
   patterns: List of url patterns to limit the schema introspection to. If you only want the myproject.api urls to be exposed in the schema: schema_url_patterns = [
    path('api/', include('myproject.api.urls')),
]

schema_view = get_schema_view(
    title='Server Monitoring API',
    url='https://www.example.org/api/',
    patterns=schema_url_patterns,
)
   generator_class: May be used to specify a SchemaGenerator subclass to be passed to the SchemaView.
authentication_classes: May be used to specify the list of authentication classes that will apply to the schema endpoint. Defaults to settings.DEFAULT_AUTHENTICATION_CLASSES

permission_classes: May be used to specify the list of permission classes that will apply to the schema endpoint. Defaults to settings.DEFAULT_PERMISSION_CLASSES.
renderer_classes: May be used to pass the set of renderer classes that can be used to render the API root endpoint.  SchemaGenerator Schema-level customization from rest_framework.schemas.openapi import SchemaGenerator
 SchemaGenerator is a class that walks a list of routed URL patterns, requests the schema for each view and collates the resulting OpenAPI schema. Typically you won't need to instantiate SchemaGenerator yourself, but you can do so like so: generator = SchemaGenerator(title='Stock Prices API')
 Arguments:
title required: The name of the API.
description: Longer descriptive text.
version: The version of the API. Defaults to 0.1.0.
url: The root URL of the API schema. This option is not required unless the schema is included under path prefix.
patterns: A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.
urlconf: A URL conf module name to use when generating the schema. Defaults to settings.ROOT_URLCONF.  In order to customize the top-level schema, subclass rest_framework.schemas.openapi.SchemaGenerator and provide your subclass as an argument to the generateschema command or get_schema_view() helper function. get_schema(self, request) Returns a dictionary that represents the OpenAPI schema: generator = SchemaGenerator(title='Stock Prices API')
schema = generator.get_schema()
 The request argument is optional, and may be used if you want to apply per-user permissions to the resulting schema generation. This is a good point to override if you want to customize the generated dictionary For example you might wish to add terms of service to the top-level info object: class TOSSchemaGenerator(SchemaGenerator):
    def get_schema(self, *args, **kwargs):
        schema = super().get_schema(*args, **kwargs)
        schema["info"]["termsOfService"] = "https://example.com/tos.html"
        return schema
 AutoSchema Per-View Customization from rest_framework.schemas.openapi import AutoSchema
 By default, view introspection is performed by an AutoSchema instance accessible via the schema attribute on APIView. auto_schema = some_view.schema
 AutoSchema provides the OpenAPI elements needed for each view, request method and path:  A list of OpenAPI components. In DRF terms these are mappings of serializers that describe request and response bodies. The appropriate OpenAPI operation object that describes the endpoint, including path and query parameters for pagination, filtering, and so on.  components = auto_schema.get_components(...)
operation = auto_schema.get_operation(...)
 In compiling the schema, SchemaGenerator calls get_components() and get_operation() for each view, allowed method, and path. Note: The automatic introspection of components, and many operation parameters relies on the relevant attributes and methods of GenericAPIView: get_serializer(), pagination_class, filter_backends, etc. For basic APIView subclasses, default introspection is essentially limited to the URL kwarg path parameters for this reason. AutoSchema encapsulates the view introspection needed for schema generation. Because of this all the schema generation logic is kept in a single place, rather than being spread around the already extensive view, serializer and field APIs. Keeping with this pattern, try not to let schema logic leak into your own views, serializers, or fields when customizing the schema generation. You might be tempted to do something like this: class CustomSchema(AutoSchema):
    """
    AutoSchema subclass using schema_extra_info on the view.
    """
    ...

class CustomView(APIView):
    schema = CustomSchema()
    schema_extra_info = ... some extra info ...
 Here, the AutoSchema subclass goes looking for schema_extra_info on the view. This is OK (it doesn't actually hurt) but it means you'll end up with your schema logic spread out in a number of different places. Instead try to subclass AutoSchema such that the extra_info doesn't leak out into the view: class BaseSchema(AutoSchema):
    """
    AutoSchema subclass that knows how to use extra_info.
    """
    ...

class CustomSchema(BaseSchema):
    extra_info = ... some extra info ...

class CustomView(APIView):
    schema = CustomSchema()
 This style is slightly more verbose but maintains the encapsulation of the schema related code. It's more cohesive in the parlance. It'll keep the rest of your API code more tidy. If an option applies to many view classes, rather than creating a specific subclass per-view, you may find it more convenient to allow specifying the option as an __init__() kwarg to your base AutoSchema subclass: class CustomSchema(BaseSchema):
    def __init__(self, **kwargs):
        # store extra_info for later
        self.extra_info = kwargs.pop("extra_info")
        super().__init__(**kwargs)

class CustomView(APIView):
    schema = CustomSchema(
        extra_info=... some extra info ...
    )
 This saves you having to create a custom subclass per-view for a commonly used option. Not all AutoSchema methods expose related __init__() kwargs, but those for the more commonly needed options do. AutoSchema methods get_components() Generates the OpenAPI components that describe request and response bodies, deriving their properties from the serializer. Returns a dictionary mapping the component name to the generated representation. By default this has just a single pair but you may override get_components() to return multiple pairs if your view uses multiple serializers. get_component_name() Computes the component's name from the serializer. You may see warnings if your API has duplicate component names. If so you can override get_component_name() or pass the component_name __init__() kwarg (see below) to provide different names. map_serializer() Maps serializers to their OpenAPI representations. Most serializers should conform to the standard OpenAPI object type, but you may wish to override map_serializer() in order to customize this or other serializer-level fields. map_field() Maps individual serializer fields to their schema representation. The base implementation will handle the default fields that Django REST Framework provides. For SerializerMethodField instances, for which the schema is unknown, or custom field subclasses you should override map_field() to generate the correct schema: class CustomSchema(AutoSchema):
    """Extension of ``AutoSchema`` to add support for custom field schemas."""

    def map_field(self, field):
        # Handle SerializerMethodFields or custom fields here...
        # ...
        return super().map_field(field)
 Authors of third-party packages should aim to provide an AutoSchema subclass, and a mixin, overriding map_field() so that users can easily generate schemas for their custom fields. get_tags() OpenAPI groups operations by tags. By default tags taken from the first path segment of the routed URL. For example, a URL like /users/{id}/ will generate the tag users. You can pass an __init__() kwarg to manually specify tags (see below), or override get_tags() to provide custom logic. get_operation() Returns the OpenAPI operation object that describes the endpoint, including path and query parameters for pagination, filtering, and so on. Together with get_components(), this is the main entry point to the view introspection. get_operation_id() There must be a unique operationid for each operation. By default the operationId is deduced from the model name, serializer name or view name. The operationId looks like "listItems", "retrieveItem", "updateItem", etc. The operationId is camelCase by convention. get_operation_id_base() If you have several views with the same model name, you may see duplicate operationIds. In order to work around this, you can override get_operation_id_base() to provide a different base for name part of the ID. get_serializer() If the view has implemented get_serializer(), returns the result. get_request_serializer() By default returns get_serializer() but can be overridden to differentiate between request and response objects. get_response_serializer() By default returns get_serializer() but can be overridden to differentiate between request and response objects. AutoSchema.__init__() kwargs AutoSchema provides a number of __init__() kwargs that can be used for common customizations, if the default generated values are not appropriate. The available kwargs are:
tags: Specify a list of tags.
component_name: Specify the component name.
operation_id_base: Specify the resource-name part of operation IDs.  You pass the kwargs when declaring the AutoSchema instance on your view: class PetDetailView(generics.RetrieveUpdateDestroyAPIView):
    schema = AutoSchema(
        tags=['Pets'],
        component_name='Pet',
        operation_id_base='Pet',
    )
    ...
 Assuming a Pet model and PetSerializer serializer, the kwargs in this example are probably not needed. Often, though, you'll need to pass the kwargs if you have multiple view targeting the same model, or have multiple views with identically named serializers. If your views have related customizations that are needed frequently, you can create a base AutoSchema subclass for your project that takes additional __init__() kwargs to save subclassing AutoSchema for each view. schemas


Throttling  HTTP/1.1 420 Enhance Your Calm Twitter API rate limiting response  Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API. As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests. Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive. Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day. Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed. How throttling is determined As with permissions and authentication, throttling in REST framework is always defined as a list of classes. Before running the main body of the view each throttle in the list is checked. If any throttle check fails an exceptions.Throttled exception will be raised, and the main body of the view will not run. Setting the throttling policy The default throttling policy may be set globally, using the DEFAULT_THROTTLE_CLASSES and DEFAULT_THROTTLE_RATES settings. For example. REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }
}
 The rate descriptions used in DEFAULT_THROTTLE_RATES may include second, minute, hour or day as the throttle period. You can also set the throttling policy on a per-view or per-viewset basis, using the APIView class-based views. from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView

class ExampleView(APIView):
    throttle_classes = [UserRateThrottle]

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)
 If you're using the @api_view decorator with function based views you can use the following decorator. @api_view(['GET'])
@throttle_classes([UserRateThrottle])
def example_view(request, format=None):
    content = {
        'status': 'request was permitted'
    }
    return Response(content)
 It's also possible to set throttle classes for routes that are created using the @action decorator. Throttle classes set in this way will override any viewset level class settings. @action(detail=True, methods=["post"], throttle_classes=[UserRateThrottle])
def example_adhoc_method(request, pk=None):
    content = {
        'status': 'request was permitted'
    }
    return Response(content)
 How clients are identified The X-Forwarded-For HTTP header and REMOTE_ADDR WSGI variable are used to uniquely identify client IP addresses for throttling. If the X-Forwarded-For header is present then it will be used, otherwise the value of the REMOTE_ADDR variable from the WSGI environment will be used. If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the NUM_PROXIES setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the X-Forwarded-For header, once any application proxy IP addresses have first been excluded. If set to zero, then the REMOTE_ADDR value will always be used as the identifying IP address. It is important to understand that if you configure the NUM_PROXIES setting, then all clients behind a unique NAT'd gateway will be treated as a single client. Further context on how the X-Forwarded-For header works, and identifying a remote client IP can be found here. Setting up the cache The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate cache settings. The default value of LocMemCache backend should be okay for simple setups. See Django's cache documentation for more details. If you need to use a cache other than 'default', you can do so by creating a custom throttle class and setting the cache attribute. For example: from django.core.cache import caches

class CustomAnonRateThrottle(AnonRateThrottle):
    cache = caches['alternate']
 You'll need to remember to also set your custom throttle class in the 'DEFAULT_THROTTLE_CLASSES' settings key, or using the throttle_classes view attribute. API Reference AnonRateThrottle The AnonRateThrottle will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against. The allowed request rate is determined from one of the following (in order of preference).  The rate property on the class, which may be provided by overriding AnonRateThrottle and setting the property. The DEFAULT_THROTTLE_RATES['anon'] setting.  AnonRateThrottle is suitable if you want to restrict the rate of requests from unknown sources. UserRateThrottle The UserRateThrottle will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against. The allowed request rate is determined from one of the following (in order of preference).  The rate property on the class, which may be provided by overriding UserRateThrottle and setting the property. The DEFAULT_THROTTLE_RATES['user'] setting.  An API may have multiple UserRateThrottles in place at the same time. To do so, override UserRateThrottle and set a unique "scope" for each class. For example, multiple user throttle rates could be implemented by using the following classes... class BurstRateThrottle(UserRateThrottle):
    scope = 'burst'

class SustainedRateThrottle(UserRateThrottle):
    scope = 'sustained'
 ...and the following settings. REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'example.throttles.BurstRateThrottle',
        'example.throttles.SustainedRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'burst': '60/min',
        'sustained': '1000/day'
    }
}
 UserRateThrottle is suitable if you want simple global rate restrictions per-user. ScopedRateThrottle The ScopedRateThrottle class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a .throttle_scope property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address. The allowed request rate is determined by the DEFAULT_THROTTLE_RATES setting using a key from the request "scope". For example, given the following views... class ContactListView(APIView):
    throttle_scope = 'contacts'
    ...

class ContactDetailView(APIView):
    throttle_scope = 'contacts'
    ...

class UploadView(APIView):
    throttle_scope = 'uploads'
    ...
 ...and the following settings. REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.ScopedRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'contacts': '1000/day',
        'uploads': '20/day'
    }
}
 User requests to either ContactListView or ContactDetailView would be restricted to a total of 1000 requests per-day. User requests to UploadView would be restricted to 20 requests per day. Custom throttles To create a custom throttle, override BaseThrottle and implement .allow_request(self, request, view). The method should return True if the request should be allowed, and False otherwise. Optionally you may also override the .wait() method. If implemented, .wait() should return a recommended number of seconds to wait before attempting the next request, or None. The .wait() method will only be called if .allow_request() has previously returned False. If the .wait() method is implemented and the request is throttled, then a Retry-After header will be included in the response. Example The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests. import random

class RandomRateThrottle(throttling.BaseThrottle):
    def allow_request(self, request, view):
        return random.randint(1, 10) != 1
 throttling.py


Filtering  The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. — Django documentation  The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset. The simplest way to filter the queryset of any view that subclasses GenericAPIView is to override the .get_queryset() method. Overriding this method allows you to customize the queryset returned by the view in a number of different ways. Filtering against the current user You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned. You can do so by filtering based on the value of request.user. For example: from myapp.models import Purchase
from myapp.serializers import PurchaseSerializer
from rest_framework import generics

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        This view should return a list of all the purchases
        for the currently authenticated user.
        """
        user = self.request.user
        return Purchase.objects.filter(purchaser=user)
 Filtering against the URL Another style of filtering might involve restricting the queryset based on some part of the URL. For example if your URL config contained an entry like this: re_path('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
 You could then write a view that returned a purchase queryset filtered by the username portion of the URL: class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        This view should return a list of all the purchases for
        the user as determined by the username portion of the URL.
        """
        username = self.kwargs['username']
        return Purchase.objects.filter(purchaser__username=username)
 Filtering against query parameters A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url. We can override .get_queryset() to deal with URLs such as http://example.com/api/purchases?username=denvercoder9, and filter the queryset only if the username parameter is included in the URL: class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        Optionally restricts the returned purchases to a given user,
        by filtering against a `username` query parameter in the URL.
        """
        queryset = Purchase.objects.all()
        username = self.request.query_params.get('username')
        if username is not None:
            queryset = queryset.filter(purchaser__username=username)
        return queryset
 Generic Filtering As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters. Generic filters can also present themselves as HTML controls in the browsable API and admin API.  Setting filter backends The default filter backends may be set globally, using the DEFAULT_FILTER_BACKENDS setting. For example. REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
 You can also set the filter backends on a per-view, or per-viewset basis, using the GenericAPIView class-based views. import django_filters.rest_framework
from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
from rest_framework import generics

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
 Filtering and object lookups Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object. For instance, given the previous example, and a product with an id of 4675, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance: http://example.com/api/products/4675/?category=clothing&max_price=10.00
 Overriding the initial queryset Note that you can use both an overridden .get_queryset() and generic filtering together, and everything will work as expected. For example, if Product had a many-to-many relationship with User, named purchase, you might want to write a view like this: class PurchasedProductsList(generics.ListAPIView):
    """
    Return a list of all the products that the authenticated
    user has ever purchased, with optional filtering.
    """
    model = Product
    serializer_class = ProductSerializer
    filterset_class = ProductFilter

    def get_queryset(self):
        user = self.request.user
        return user.purchase_set.all()
 API Guide DjangoFilterBackend The django-filter library includes a DjangoFilterBackend class which supports highly customizable field filtering for REST framework. To use DjangoFilterBackend, first install django-filter. pip install django-filter
 Then add 'django_filters' to Django's INSTALLED_APPS: INSTALLED_APPS = [
    ...
    'django_filters',
    ...
]
 You should now either add the filter backend to your settings: REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
 Or add the filter backend to an individual View or ViewSet. from django_filters.rest_framework import DjangoFilterBackend

class UserListView(generics.ListAPIView):
    ...
    filter_backends = [DjangoFilterBackend]
 If all you need is simple equality-based filtering, you can set a filterset_fields attribute on the view, or viewset, listing the set of fields you wish to filter against. class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['category', 'in_stock']
 This will automatically create a FilterSet class for the given fields, and will allow you to make requests such as: http://example.com/api/products?category=clothing&in_stock=True
 For more advanced filtering requirements you can specify a FilterSet class that should be used by the view. You can read more about FilterSets in the django-filter documentation. It's also recommended that you read the section on DRF integration. SearchFilter The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin's search functionality. When in use, the browsable API will include a SearchFilter control:  The SearchFilter class will only be applied if the view has a search_fields attribute set. The search_fields attribute should be a list of names of text type fields on the model, such as CharField or TextField. from rest_framework import filters

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['username', 'email']
 This will allow the client to filter the items in the list by making queries such as: http://example.com/api/users?search=russell
 You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: search_fields = ['username', 'email', 'profile__profession']
 For JSONField and HStoreField fields you can filter based on nested values within the data structure using the same double-underscore notation: search_fields = ['data__breed', 'data__owner__other_pets__0__name']
 By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. The search behavior may be restricted by prepending various characters to the search_fields.  '^' Starts-with search. '=' Exact matches. '@' Full-text search. (Currently only supported Django's PostgreSQL backend.) '$' Regex search.  For example: search_fields = ['=username', '=email']
 By default, the search parameter is named 'search', but this may be overridden with the SEARCH_PARAM setting. To dynamically change search fields based on request content, it's possible to subclass the SearchFilter and override the get_search_fields() function. For example, the following subclass will only search on title if the query parameter title_only is in the request: from rest_framework import filters

class CustomSearchFilter(filters.SearchFilter):
    def get_search_fields(self, view, request):
        if request.query_params.get('title_only'):
            return ['title']
        return super(CustomSearchFilter, self).get_search_fields(view, request)
 For more details, see the Django documentation. OrderingFilter The OrderingFilter class supports simple query parameter controlled ordering of results.  By default, the query parameter is named 'ordering', but this may by overridden with the ORDERING_PARAM setting. For example, to order users by username: http://example.com/api/users?ordering=username
 The client may also specify reverse orderings by prefixing the field name with '-', like so: http://example.com/api/users?ordering=-username
 Multiple orderings may also be specified: http://example.com/api/users?ordering=account,username
 Specifying which fields may be ordered against It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an ordering_fields attribute on the view, like so: class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['username', 'email']
 This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data. If you don't specify an ordering_fields attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the serializer_class attribute. If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on any model field or queryset aggregate, by using the special value '__all__'. class BookingsListView(generics.ListAPIView):
    queryset = Booking.objects.all()
    serializer_class = BookingSerializer
    filter_backends = [filters.OrderingFilter]
    ordering_fields = '__all__'
 Specifying a default ordering If an ordering attribute is set on the view, this will be used as the default ordering. Typically you'd instead control this by setting order_by on the initial queryset, but using the ordering parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results. class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['username', 'email']
    ordering = ['username']
 The ordering attribute may be either a string or a list/tuple of strings. Custom generic filtering You can also provide your own generic filtering backend, or write an installable app for other developers to use. To do so override BaseFilterBackend, and override the .filter_queryset(self, request, queryset, view) method. The method should return a new, filtered queryset. As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user. Example For example, you might need to restrict users to only being able to see objects they created. class IsOwnerFilterBackend(filters.BaseFilterBackend):
    """
    Filter that only allows users to see their own objects.
    """
    def filter_queryset(self, request, queryset, view):
        return queryset.filter(owner=request.user)
 We could achieve the same behavior by overriding get_queryset() on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API. Customizing the interface Generic filters may also present an interface in the browsable API. To do so you should implement a to_html() method which returns a rendered HTML representation of the filter. This method should have the following signature: to_html(self, request, queryset, view) The method should return a rendered HTML string. Filtering & schemas You can also make the filter controls available to the schema autogeneration that REST framework provides, by implementing a get_schema_fields() method. This method should have the following signature: get_schema_fields(self, view) The method should return a list of coreapi.Field instances. Third party packages The following third party packages provide additional filter implementations. Django REST framework filters package The django-rest-framework-filters package works together with the DjangoFilterBackend class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field. Django REST framework full word search filter The djangorestframework-word-filter developed as alternative to filters.SearchFilter which will search full word in text, or exact match. Django URL Filter django-url-filter provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django QuerySets. drf-url-filters drf-url-filter is a simple Django app to apply filters on drf ModelViewSet's Queryset in a clean, simple and configurable way. It also supports validations on incoming query params and their values. A beautiful python package Voluptuous is being used for validations on the incoming query parameters. The best part about voluptuous is you can define your own validations as per your query params requirements. filters.py