diff --git a/api-guide/schemas/index.html b/api-guide/schemas/index.html
index 1664341f3..5ec13eb9e 100644
--- a/api-guide/schemas/index.html
+++ b/api-guide/schemas/index.html
@@ -428,8 +428,8 @@
-
- schemas.py
+
+ schemas
diff --git a/api-guide/validators/index.html b/api-guide/validators/index.html
index 68ee195d3..21da39eb6 100644
--- a/api-guide/validators/index.html
+++ b/api-guide/validators/index.html
@@ -660,7 +660,7 @@ serializer class, and instead write any validation logic explicitly, either
in the .validate()
method, or else in the view.
For example:
class BillingRecordSerializer(serializers.ModelSerializer):
- def validate(self, data):
+ def validate(self, attrs):
# Apply custom validation either here, or in the view.
class Meta:
diff --git a/community/third-party-packages/index.html b/community/third-party-packages/index.html
index 1942b5741..00dbf2b13 100644
--- a/community/third-party-packages/index.html
+++ b/community/third-party-packages/index.html
@@ -581,6 +581,8 @@ You probably want to also tag the version now:
djangorestframework-queryfields - Serializer mixin allowing clients to control which fields will be sent in the API response.
drf-flex-fields - Serializer providing dynamic field expansion and sparse field sets via URL parameters.
drf-action-serializer - Serializer providing per-action fields config for use with ViewSets to prevent having to write multiple serializers.
+djangorestframework-dataclasses - Serializer providing automatic field generation for Python dataclasses, like the built-in ModelSerializer does for models.
+django-restql - Turn your REST API into a GraphQL like API(It allows clients to control which fields will be sent in a response, uses GraphQL like syntax, supports read and write on both flat and nested fields).
Serializer fields
diff --git a/img/premium/retool-readme.png b/img/premium/retool-readme.png
new file mode 100644
index 000000000..45058b4b3
Binary files /dev/null and b/img/premium/retool-readme.png differ
diff --git a/index.html b/index.html
index 622b5482a..73bdf1f2c 100644
--- a/index.html
+++ b/index.html
@@ -541,11 +541,12 @@ continued development by signing up for a p
- Cadre
- Kloudless
- Lights On Software
+ - Retool
-Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, ESG, Rollbar, Cadre, Kloudless, and Lights On Software.
+Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, ESG, Rollbar, Cadre, Kloudless, Lights On Software, and Retool.
Requirements
REST framework requires the following:
diff --git a/search/search_index.json b/search/search_index.json
index 8cabed5c9..3f12909fd 100644
--- a/search/search_index.json
+++ b/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":".promo li a { float: left; width: 130px; height: 20px; text-align: center; margin: 10px 30px; padding: 150px 0 0 0; background-position: 0 50%; background-size: 130px auto; background-repeat: no-repeat; font-size: 120%; color: black; } .promo li { list-style: none; } Django REST Framework Django REST framework is a powerful and flexible toolkit for building Web APIs. Some reasons you might want to use REST framework: The Web browsable API is a huge usability win for your developers. Authentication policies including packages for OAuth1a and OAuth2 . Serialization that supports both ORM and non-ORM data sources. Customizable all the way down - just use regular function-based views if you don't need the more powerful features . Extensive documentation , and great community support . Used and trusted by internationally recognised companies including Mozilla , Red Hat , Heroku , and Eventbrite . Funding REST framework is a collaboratively funded project . If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan . Every single sign-up helps us make REST framework long-term financially sustainable. Sentry Stream ESG Rollbar Cadre Kloudless Lights On Software Many thanks to all our wonderful sponsors , and in particular to our premium backers, Sentry , Stream , ESG , Rollbar , Cadre , Kloudless , and Lights On Software . Requirements REST framework requires the following: Python (3.5, 3.6, 3.7) Django (1.11, 2.0, 2.1, 2.2) We highly recommend and only officially support the latest patch release of each Python and Django series. The following packages are optional: coreapi (1.32.0+) - Schema generation support. Markdown (3.0.0+) - Markdown support for the browsable API. Pygments (2.4.0+) - Add syntax highlighting to Markdown processing. django-filter (1.0.1+) - Filtering support. django-guardian (1.1.1+) - Object level permissions support. Installation Install using pip , including any optional packages you want... pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support ...or clone the project from github. git clone https://github.com/encode/django-rest-framework Add 'rest_framework' to your INSTALLED_APPS setting. INSTALLED_APPS = [ ... 'rest_framework', ] If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py file. urlpatterns = [ ... url(r'^api-auth/', include('rest_framework.urls')) ] Note that the URL path can be whatever you want. Example Let's take a look at a quick example of using REST framework to build a simple model-backed API. We'll create a read-write API for accessing information on the users of our project. Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK . Start off by adding the following to your settings.py module: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } Don't forget to make sure you've also added rest_framework to your INSTALLED_APPS . We're ready to create our API now. Here's our project's root urls.py module: from django.conf.urls import url, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'is_staff'] # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'users', UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] You can now open the API in your browser at http://127.0.0.1:8000/ , and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system. Quickstart Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework. Development See the Contribution guidelines for information on how to clone the repository, run the test suite and contribute changes back to REST Framework. Support For support please see the REST framework discussion group , try the #restframework channel on irc.freenode.net , search the IRC archives , or raise a question on Stack Overflow , making sure to include the 'django-rest-framework' tag. For priority support please sign up for a professional or premium sponsorship plan . For updates on REST framework development, you may also want to follow the author on Twitter. Follow @_tomchristie !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\"); Security If you believe you\u2019ve found something in Django REST framework which has security implications, please do not raise the issue in a public forum . Send a description of the issue via email to rest-framework-security@googlegroups.com . The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure. License Copyright \u00a9 2011-present, Encode OSS Ltd . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.","title":"Home"},{"location":"#funding","text":"REST framework is a collaboratively funded project . If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan . Every single sign-up helps us make REST framework long-term financially sustainable. Sentry Stream ESG Rollbar Cadre Kloudless Lights On Software Many thanks to all our wonderful sponsors , and in particular to our premium backers, Sentry , Stream , ESG , Rollbar , Cadre , Kloudless , and Lights On Software .","title":"Funding"},{"location":"#requirements","text":"REST framework requires the following: Python (3.5, 3.6, 3.7) Django (1.11, 2.0, 2.1, 2.2) We highly recommend and only officially support the latest patch release of each Python and Django series. The following packages are optional: coreapi (1.32.0+) - Schema generation support. Markdown (3.0.0+) - Markdown support for the browsable API. Pygments (2.4.0+) - Add syntax highlighting to Markdown processing. django-filter (1.0.1+) - Filtering support. django-guardian (1.1.1+) - Object level permissions support.","title":"Requirements"},{"location":"#installation","text":"Install using pip , including any optional packages you want... pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support ...or clone the project from github. git clone https://github.com/encode/django-rest-framework Add 'rest_framework' to your INSTALLED_APPS setting. INSTALLED_APPS = [ ... 'rest_framework', ] If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py file. urlpatterns = [ ... url(r'^api-auth/', include('rest_framework.urls')) ] Note that the URL path can be whatever you want.","title":"Installation"},{"location":"#example","text":"Let's take a look at a quick example of using REST framework to build a simple model-backed API. We'll create a read-write API for accessing information on the users of our project. Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK . Start off by adding the following to your settings.py module: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } Don't forget to make sure you've also added rest_framework to your INSTALLED_APPS . We're ready to create our API now. Here's our project's root urls.py module: from django.conf.urls import url, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'is_staff'] # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'users', UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] You can now open the API in your browser at http://127.0.0.1:8000/ , and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.","title":"Example"},{"location":"#quickstart","text":"Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework.","title":"Quickstart"},{"location":"#development","text":"See the Contribution guidelines for information on how to clone the repository, run the test suite and contribute changes back to REST Framework.","title":"Development"},{"location":"#support","text":"For support please see the REST framework discussion group , try the #restframework channel on irc.freenode.net , search the IRC archives , or raise a question on Stack Overflow , making sure to include the 'django-rest-framework' tag. For priority support please sign up for a professional or premium sponsorship plan . For updates on REST framework development, you may also want to follow the author on Twitter. Follow @_tomchristie !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");","title":"Support"},{"location":"#security","text":"If you believe you\u2019ve found something in Django REST framework which has security implications, please do not raise the issue in a public forum . Send a description of the issue via email to rest-framework-security@googlegroups.com . The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.","title":"Security"},{"location":"#license","text":"Copyright \u00a9 2011-present, Encode OSS Ltd . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.","title":"License"},{"location":"api-guide/authentication/","text":"Authentication Auth needs to be pluggable. \u2014 Jacob Kaplan-Moss, \"REST worst practices\" Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The permission and throttling policies can then use those credentials to determine if the request should be permitted. REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes. Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed. The request.user property will typically be set to an instance of the contrib.auth package's User class. The request.auth property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with. Note: Don't forget that authentication by itself won't allow or disallow an incoming request , it simply identifies the credentials that the request was made with. For information on how to setup the permission polices for your API please see the permissions documentation . How authentication is determined The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set request.user and request.auth using the return value of the first class that successfully authenticates. If no class authenticates, request.user will be set to an instance of django.contrib.auth.models.AnonymousUser , and request.auth will be set to None . The value of request.user and request.auth for unauthenticated requests can be modified using the UNAUTHENTICATED_USER and UNAUTHENTICATED_TOKEN settings. Setting the authentication scheme The default authentication schemes may be set globally, using the DEFAULT_AUTHENTICATION_CLASSES setting. For example. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } You can also set the authentication scheme on a per-view or per-viewset basis, using the APIView class-based views. from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content) Or, if you're using the @api_view decorator with function based views. @api_view(['GET']) @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def example_view(request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content) Unauthorized and Forbidden responses When an unauthenticated request is denied permission there are two different error codes that may be appropriate. HTTP 401 Unauthorized HTTP 403 Permission Denied HTTP 401 responses must always include a WWW-Authenticate header, that instructs the client how to authenticate. HTTP 403 responses do not include the WWW-Authenticate header. The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. The first authentication class set on the view is used when determining the type of response . Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a 403 Permission Denied response will always be used, regardless of the authentication scheme. Apache mod_wsgi specific configuration Note that if deploying to Apache using mod_wsgi , the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level. If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the WSGIPassAuthorization directive in the appropriate context and setting it to 'On' . # this can go in either server config, virtual host, directory or .htaccess WSGIPassAuthorization On API Reference BasicAuthentication This authentication scheme uses HTTP Basic Authentication , signed against a user's username and password. Basic authentication is generally only appropriate for testing. If successfully authenticated, BasicAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be None . Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example: WWW-Authenticate: Basic realm=\"api\" Note: If you use BasicAuthentication in production you must ensure that your API is only available over https . You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage. TokenAuthentication This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. To use the TokenAuthentication scheme you'll need to configure the authentication classes to include TokenAuthentication , and additionally include rest_framework.authtoken in your INSTALLED_APPS setting: INSTALLED_APPS = [ ... 'rest_framework.authtoken' ] Note: Make sure to run manage.py migrate after changing your settings. The rest_framework.authtoken app provides Django database migrations. You'll also need to create tokens for your users. from rest_framework.authtoken.models import Token token = Token.objects.create(user=...) print(token.key) For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal \"Token\", with whitespace separating the two strings. For example: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b Note: If you want to use a different keyword in the header, such as Bearer , simply subclass TokenAuthentication and set the keyword class variable. If successfully authenticated, TokenAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be a rest_framework.authtoken.models.Token instance. Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example: WWW-Authenticate: Token The curl command line tool may be useful for testing token authenticated APIs. For example: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' Note: If you use TokenAuthentication in production you must ensure that your API is only available over https . Generating Tokens By using signals If you want every user to have an automatically generated Token, you can simply catch the User's post_save signal. from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) Note that you'll want to ensure you place this code snippet in an installed models.py module, or some other location that will be imported by Django on startup. If you've already created some users, you can generate tokens for all existing users like this: from django.contrib.auth.models import User from rest_framework.authtoken.models import Token for user in User.objects.all(): Token.objects.get_or_create(user=user) By exposing an api endpoint When using TokenAuthentication , you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the obtain_auth_token view to your URLconf: from rest_framework.authtoken import views urlpatterns += [ url(r'^api-token-auth/', views.obtain_auth_token) ] Note that the URL part of the pattern can be whatever you want to use. The obtain_auth_token view will return a JSON response when valid username and password fields are POSTed to the view using form data or JSON: { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' } Note that the default obtain_auth_token view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. By default there are no permissions or throttling applied to the obtain_auth_token view. If you do wish to apply throttling you'll need to override the view class, and include them using the throttle_classes attribute. If you need a customized version of the obtain_auth_token view, you can do so by subclassing the ObtainAuthToken view class, and using that in your url conf instead. For example, you may return additional user information beyond the token value: from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email }) And in your urls.py : urlpatterns += [ url(r'^api-token-auth/', CustomAuthToken.as_view()) ] With Django admin It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the TokenAdmin class to customize it to your needs, more specifically by declaring the user field as raw_field . your_app/admin.py : from rest_framework.authtoken.admin import TokenAdmin TokenAdmin.raw_id_fields = ['user'] Using Django manage.py command Since version 3.6.4 it's possible to generate a user token using the following command: ./manage.py drf_create_token this command will return the API token for the given user, creating it if it doesn't exist: Generated token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b for user user1 In case you want to regenerate the token (for example if it has been compromised or leaked) you can pass an additional parameter: ./manage.py drf_create_token -r SessionAuthentication This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website. If successfully authenticated, SessionAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be None . Unauthenticated responses that are denied permission will result in an HTTP 403 Forbidden response. If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any \"unsafe\" HTTP method calls, such as PUT , PATCH , POST or DELETE requests. See the Django CSRF documentation for more details. Warning : Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected. CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied. RemoteUserAuthentication This authentication scheme allows you to delegate authentication to your web server, which sets the REMOTE_USER environment variable. To use it, you must have django.contrib.auth.backends.RemoteUserBackend (or a subclass) in your AUTHENTICATION_BACKENDS setting. By default, RemoteUserBackend creates User objects for usernames that don't already exist. To change this and other behaviour, consult the Django documentation . If successfully authenticated, RemoteUserAuthentication provides the following credentials: request.user will be a Django User instance. request.auth will be None . Consult your web server's documentation for information about configuring an authentication method, e.g.: Apache Authentication How-To NGINX (Restricting Access) Custom authentication To implement a custom authentication scheme, subclass BaseAuthentication and override the .authenticate(self, request) method. The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise. In some circumstances instead of returning None , you may want to raise an AuthenticationFailed exception from the .authenticate() method. Typically the approach you should take is: If authentication is not attempted, return None . Any other authentication schemes also in use will still be checked. If authentication is attempted but fails, raise a AuthenticationFailed exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes. You may also override the .authenticate_header(self, request) method. If implemented, it should return a string that will be used as the value of the WWW-Authenticate header in a HTTP 401 Unauthorized response. If the .authenticate_header() method is not overridden, the authentication scheme will return HTTP 403 Forbidden responses when an unauthenticated request is denied access. Note: When your custom authenticator is invoked by the request object's .user or .auth properties, you may see an AttributeError re-raised as a WrappedAttributeError . This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the AttributeError originates from your custom authenticator and will instead assume that the request object does not have a .user or .auth property. These errors should be fixed or otherwise handled by your authenticator. Example The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'. from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('HTTP_X_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) Third party packages The following third party packages are also available. Django OAuth Toolkit The Django OAuth Toolkit package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by Evonove and uses the excellent OAuthLib . The package is well documented, and well supported and is currently our recommended package for OAuth 2.0 support . Installation & configuration Install using pip . pip install django-oauth-toolkit Add the package to your INSTALLED_APPS and modify your REST framework settings. INSTALLED_APPS = [ ... 'oauth2_provider', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ] } For more details see the Django REST framework - Getting started documentation. Django REST framework OAuth The Django REST framework OAuth package provides both OAuth1 and OAuth2 support for REST framework. This package was previously included directly in REST framework but is now supported and maintained as a third party package. Installation & configuration Install the package using pip . pip install djangorestframework-oauth For details on configuration and usage see the Django REST framework OAuth documentation for authentication and permissions . JSON Web Token Authentication JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is djangorestframework-simplejwt which provides some features as well as a pluggable token blacklist app. Hawk HTTP Authentication The HawkREST library builds on the Mohawk library to let you work with Hawk signed requests and responses in your API. Hawk lets two parties securely communicate with each other using messages signed by a shared key. It is based on HTTP MAC access authentication (which was based on parts of OAuth 1.0 ). HTTP Signature Authentication HTTP Signature (currently a IETF draft ) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to Amazon's HTTP Signature scheme , used by many of its services, it permits stateless, per-request authentication. Elvio Toccalino maintains the djangorestframework-httpsignature (outdated) package which provides an easy to use HTTP Signature Authentication mechanism. You can use the updated fork version of djangorestframework-httpsignature , which is drf-httpsig . Djoser Djoser library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system. django-rest-auth Django-rest-auth library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management. django-rest-framework-social-oauth2 Django-rest-framework-social-oauth2 library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to \"in-house\" oauth2 tokens and use and generate oauth2 tokens to authenticate your users. django-rest-knox Django-rest-knox library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into). drfpasswordless drfpasswordless adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's own TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.","title":"Authentication"},{"location":"api-guide/authentication/#authentication","text":"Auth needs to be pluggable. \u2014 Jacob Kaplan-Moss, \"REST worst practices\" Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The permission and throttling policies can then use those credentials to determine if the request should be permitted. REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes. Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed. The request.user property will typically be set to an instance of the contrib.auth package's User class. The request.auth property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with. Note: Don't forget that authentication by itself won't allow or disallow an incoming request , it simply identifies the credentials that the request was made with. For information on how to setup the permission polices for your API please see the permissions documentation .","title":"Authentication"},{"location":"api-guide/authentication/#how-authentication-is-determined","text":"The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set request.user and request.auth using the return value of the first class that successfully authenticates. If no class authenticates, request.user will be set to an instance of django.contrib.auth.models.AnonymousUser , and request.auth will be set to None . The value of request.user and request.auth for unauthenticated requests can be modified using the UNAUTHENTICATED_USER and UNAUTHENTICATED_TOKEN settings.","title":"How authentication is determined"},{"location":"api-guide/authentication/#setting-the-authentication-scheme","text":"The default authentication schemes may be set globally, using the DEFAULT_AUTHENTICATION_CLASSES setting. For example. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } You can also set the authentication scheme on a per-view or per-viewset basis, using the APIView class-based views. from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content) Or, if you're using the @api_view decorator with function based views. @api_view(['GET']) @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def example_view(request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content)","title":"Setting the authentication scheme"},{"location":"api-guide/authentication/#unauthorized-and-forbidden-responses","text":"When an unauthenticated request is denied permission there are two different error codes that may be appropriate. HTTP 401 Unauthorized HTTP 403 Permission Denied HTTP 401 responses must always include a WWW-Authenticate header, that instructs the client how to authenticate. HTTP 403 responses do not include the WWW-Authenticate header. The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. The first authentication class set on the view is used when determining the type of response . Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a 403 Permission Denied response will always be used, regardless of the authentication scheme.","title":"Unauthorized and Forbidden responses"},{"location":"api-guide/authentication/#apache-mod_wsgi-specific-configuration","text":"Note that if deploying to Apache using mod_wsgi , the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level. If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the WSGIPassAuthorization directive in the appropriate context and setting it to 'On' . # this can go in either server config, virtual host, directory or .htaccess WSGIPassAuthorization On","title":"Apache mod_wsgi specific configuration"},{"location":"api-guide/authentication/#api-reference","text":"","title":"API Reference"},{"location":"api-guide/authentication/#basicauthentication","text":"This authentication scheme uses HTTP Basic Authentication , signed against a user's username and password. Basic authentication is generally only appropriate for testing. If successfully authenticated, BasicAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be None . Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example: WWW-Authenticate: Basic realm=\"api\" Note: If you use BasicAuthentication in production you must ensure that your API is only available over https . You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.","title":"BasicAuthentication"},{"location":"api-guide/authentication/#tokenauthentication","text":"This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. To use the TokenAuthentication scheme you'll need to configure the authentication classes to include TokenAuthentication , and additionally include rest_framework.authtoken in your INSTALLED_APPS setting: INSTALLED_APPS = [ ... 'rest_framework.authtoken' ] Note: Make sure to run manage.py migrate after changing your settings. The rest_framework.authtoken app provides Django database migrations. You'll also need to create tokens for your users. from rest_framework.authtoken.models import Token token = Token.objects.create(user=...) print(token.key) For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal \"Token\", with whitespace separating the two strings. For example: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b Note: If you want to use a different keyword in the header, such as Bearer , simply subclass TokenAuthentication and set the keyword class variable. If successfully authenticated, TokenAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be a rest_framework.authtoken.models.Token instance. Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example: WWW-Authenticate: Token The curl command line tool may be useful for testing token authenticated APIs. For example: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' Note: If you use TokenAuthentication in production you must ensure that your API is only available over https .","title":"TokenAuthentication"},{"location":"api-guide/authentication/#generating-tokens","text":"","title":"Generating Tokens"},{"location":"api-guide/authentication/#by-using-signals","text":"If you want every user to have an automatically generated Token, you can simply catch the User's post_save signal. from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) Note that you'll want to ensure you place this code snippet in an installed models.py module, or some other location that will be imported by Django on startup. If you've already created some users, you can generate tokens for all existing users like this: from django.contrib.auth.models import User from rest_framework.authtoken.models import Token for user in User.objects.all(): Token.objects.get_or_create(user=user)","title":"By using signals"},{"location":"api-guide/authentication/#by-exposing-an-api-endpoint","text":"When using TokenAuthentication , you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the obtain_auth_token view to your URLconf: from rest_framework.authtoken import views urlpatterns += [ url(r'^api-token-auth/', views.obtain_auth_token) ] Note that the URL part of the pattern can be whatever you want to use. The obtain_auth_token view will return a JSON response when valid username and password fields are POSTed to the view using form data or JSON: { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' } Note that the default obtain_auth_token view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. By default there are no permissions or throttling applied to the obtain_auth_token view. If you do wish to apply throttling you'll need to override the view class, and include them using the throttle_classes attribute. If you need a customized version of the obtain_auth_token view, you can do so by subclassing the ObtainAuthToken view class, and using that in your url conf instead. For example, you may return additional user information beyond the token value: from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email }) And in your urls.py : urlpatterns += [ url(r'^api-token-auth/', CustomAuthToken.as_view()) ]","title":"By exposing an api endpoint"},{"location":"api-guide/authentication/#with-django-admin","text":"It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the TokenAdmin class to customize it to your needs, more specifically by declaring the user field as raw_field . your_app/admin.py : from rest_framework.authtoken.admin import TokenAdmin TokenAdmin.raw_id_fields = ['user']","title":"With Django admin"},{"location":"api-guide/authentication/#using-django-managepy-command","text":"Since version 3.6.4 it's possible to generate a user token using the following command: ./manage.py drf_create_token this command will return the API token for the given user, creating it if it doesn't exist: Generated token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b for user user1 In case you want to regenerate the token (for example if it has been compromised or leaked) you can pass an additional parameter: ./manage.py drf_create_token -r ","title":"Using Django manage.py command"},{"location":"api-guide/authentication/#sessionauthentication","text":"This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website. If successfully authenticated, SessionAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be None . Unauthenticated responses that are denied permission will result in an HTTP 403 Forbidden response. If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any \"unsafe\" HTTP method calls, such as PUT , PATCH , POST or DELETE requests. See the Django CSRF documentation for more details. Warning : Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected. CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.","title":"SessionAuthentication"},{"location":"api-guide/authentication/#remoteuserauthentication","text":"This authentication scheme allows you to delegate authentication to your web server, which sets the REMOTE_USER environment variable. To use it, you must have django.contrib.auth.backends.RemoteUserBackend (or a subclass) in your AUTHENTICATION_BACKENDS setting. By default, RemoteUserBackend creates User objects for usernames that don't already exist. To change this and other behaviour, consult the Django documentation . If successfully authenticated, RemoteUserAuthentication provides the following credentials: request.user will be a Django User instance. request.auth will be None . Consult your web server's documentation for information about configuring an authentication method, e.g.: Apache Authentication How-To NGINX (Restricting Access)","title":"RemoteUserAuthentication"},{"location":"api-guide/authentication/#custom-authentication","text":"To implement a custom authentication scheme, subclass BaseAuthentication and override the .authenticate(self, request) method. The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise. In some circumstances instead of returning None , you may want to raise an AuthenticationFailed exception from the .authenticate() method. Typically the approach you should take is: If authentication is not attempted, return None . Any other authentication schemes also in use will still be checked. If authentication is attempted but fails, raise a AuthenticationFailed exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes. You may also override the .authenticate_header(self, request) method. If implemented, it should return a string that will be used as the value of the WWW-Authenticate header in a HTTP 401 Unauthorized response. If the .authenticate_header() method is not overridden, the authentication scheme will return HTTP 403 Forbidden responses when an unauthenticated request is denied access. Note: When your custom authenticator is invoked by the request object's .user or .auth properties, you may see an AttributeError re-raised as a WrappedAttributeError . This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the AttributeError originates from your custom authenticator and will instead assume that the request object does not have a .user or .auth property. These errors should be fixed or otherwise handled by your authenticator.","title":"Custom authentication"},{"location":"api-guide/authentication/#example","text":"The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'. from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('HTTP_X_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None)","title":"Example"},{"location":"api-guide/authentication/#third-party-packages","text":"The following third party packages are also available.","title":"Third party packages"},{"location":"api-guide/authentication/#django-oauth-toolkit","text":"The Django OAuth Toolkit package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by Evonove and uses the excellent OAuthLib . The package is well documented, and well supported and is currently our recommended package for OAuth 2.0 support .","title":"Django OAuth Toolkit"},{"location":"api-guide/authentication/#installation-configuration","text":"Install using pip . pip install django-oauth-toolkit Add the package to your INSTALLED_APPS and modify your REST framework settings. INSTALLED_APPS = [ ... 'oauth2_provider', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ] } For more details see the Django REST framework - Getting started documentation.","title":"Installation & configuration"},{"location":"api-guide/authentication/#django-rest-framework-oauth","text":"The Django REST framework OAuth package provides both OAuth1 and OAuth2 support for REST framework. This package was previously included directly in REST framework but is now supported and maintained as a third party package.","title":"Django REST framework OAuth"},{"location":"api-guide/authentication/#installation-configuration_1","text":"Install the package using pip . pip install djangorestframework-oauth For details on configuration and usage see the Django REST framework OAuth documentation for authentication and permissions .","title":"Installation & configuration"},{"location":"api-guide/authentication/#json-web-token-authentication","text":"JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is djangorestframework-simplejwt which provides some features as well as a pluggable token blacklist app.","title":"JSON Web Token Authentication"},{"location":"api-guide/authentication/#hawk-http-authentication","text":"The HawkREST library builds on the Mohawk library to let you work with Hawk signed requests and responses in your API. Hawk lets two parties securely communicate with each other using messages signed by a shared key. It is based on HTTP MAC access authentication (which was based on parts of OAuth 1.0 ).","title":"Hawk HTTP Authentication"},{"location":"api-guide/authentication/#http-signature-authentication","text":"HTTP Signature (currently a IETF draft ) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to Amazon's HTTP Signature scheme , used by many of its services, it permits stateless, per-request authentication. Elvio Toccalino maintains the djangorestframework-httpsignature (outdated) package which provides an easy to use HTTP Signature Authentication mechanism. You can use the updated fork version of djangorestframework-httpsignature , which is drf-httpsig .","title":"HTTP Signature Authentication"},{"location":"api-guide/authentication/#djoser","text":"Djoser library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.","title":"Djoser"},{"location":"api-guide/authentication/#django-rest-auth","text":"Django-rest-auth library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.","title":"django-rest-auth"},{"location":"api-guide/authentication/#django-rest-framework-social-oauth2","text":"Django-rest-framework-social-oauth2 library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to \"in-house\" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.","title":"django-rest-framework-social-oauth2"},{"location":"api-guide/authentication/#django-rest-knox","text":"Django-rest-knox library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).","title":"django-rest-knox"},{"location":"api-guide/authentication/#drfpasswordless","text":"drfpasswordless adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's own TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.","title":"drfpasswordless"},{"location":"api-guide/caching/","text":"Caching A certain woman had a very sharp consciousness but almost no memory ... She remembered enough to work, and she worked hard. - Lydia Davis Caching in REST Framework works well with the cache utilities provided in Django. Using cache with apiview and viewsets Django provides a method_decorator to use decorators with class based views. This can be used with other cache decorators such as cache_page and vary_on_cookie . from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import viewsets class UserViewSet(viewsets.Viewset): # Cache requested url for each user for 2 hours @method_decorator(cache_page(60*60*2)) @method_decorator(vary_on_cookie) def list(self, request, format=None): content = { 'user_feed': request.user.get_user_feed() } return Response(content) class PostView(APIView): # Cache page for the requested url @method_decorator(cache_page(60*60*2)) def get(self, request, format=None): content = { 'title': 'Post title', 'body': 'Post content' } return Response(content) NOTE: The cache_page decorator only caches the GET and HEAD responses with status 200.","title":"Caching"},{"location":"api-guide/caching/#caching","text":"A certain woman had a very sharp consciousness but almost no memory ... She remembered enough to work, and she worked hard. - Lydia Davis Caching in REST Framework works well with the cache utilities provided in Django.","title":"Caching"},{"location":"api-guide/caching/#using-cache-with-apiview-and-viewsets","text":"Django provides a method_decorator to use decorators with class based views. This can be used with other cache decorators such as cache_page and vary_on_cookie . from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import viewsets class UserViewSet(viewsets.Viewset): # Cache requested url for each user for 2 hours @method_decorator(cache_page(60*60*2)) @method_decorator(vary_on_cookie) def list(self, request, format=None): content = { 'user_feed': request.user.get_user_feed() } return Response(content) class PostView(APIView): # Cache page for the requested url @method_decorator(cache_page(60*60*2)) def get(self, request, format=None): content = { 'title': 'Post title', 'body': 'Post content' } return Response(content) NOTE: The cache_page decorator only caches the GET and HEAD responses with status 200.","title":"Using cache with apiview and viewsets"},{"location":"api-guide/content-negotiation/","text":"Content negotiation HTTP has provisions for several mechanisms for \"content negotiation\" - the process of selecting the best representation for a given response when there are multiple representations available. \u2014 RFC 2616 , Fielding et al. Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences. Determining the accepted renderer REST framework uses a simple style of content negotiation to determine which media type should be returned to a client, based on the available renderers, the priorities of each of those renderers, and the client's Accept: header. The style used is partly client-driven, and partly server-driven. More specific media types are given preference to less specific media types. If multiple media types have the same specificity, then preference is given to based on the ordering of the renderers configured for the given view. For example, given the following Accept header: application/json; indent=4, application/json, application/yaml, text/html, */* The priorities for each of the given media types would be: application/json; indent=4 application/json , application/yaml and text/html */* If the requested view was only configured with renderers for YAML and HTML , then REST framework would select whichever renderer was listed first in the renderer_classes list or DEFAULT_RENDERER_CLASSES setting. For more information on the HTTP Accept header, see RFC 2616 Note : \"q\" values are not taken into account by REST framework when determining preference. The use of \"q\" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation. This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences. Custom content negotiation It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override BaseContentNegotiation . REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the .select_parser(request, parsers) and .select_renderer(request, renderers, format_suffix) methods. The select_parser() method should return one of the parser instances from the list of available parsers, or None if none of the parsers can handle the incoming request. The select_renderer() method should return a two-tuple of (renderer instance, media type), or raise a NotAcceptable exception. Example The following is a custom content negotiation class which ignores the client request when selecting the appropriate parser or renderer. from rest_framework.negotiation import BaseContentNegotiation class IgnoreClientContentNegotiation(BaseContentNegotiation): def select_parser(self, request, parsers): \"\"\" Select the first parser in the `.parser_classes` list. \"\"\" return parsers[0] def select_renderer(self, request, renderers, format_suffix): \"\"\" Select the first renderer in the `.renderer_classes` list. \"\"\" return (renderers[0], renderers[0].media_type) Setting the content negotiation The default content negotiation class may be set globally, using the DEFAULT_CONTENT_NEGOTIATION_CLASS setting. For example, the following settings would use our example IgnoreClientContentNegotiation class. REST_FRAMEWORK = { 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation', } You can also set the content negotiation used for an individual view, or viewset, using the APIView class-based views. from myapp.negotiation import IgnoreClientContentNegotiation from rest_framework.response import Response from rest_framework.views import APIView class NoNegotiationView(APIView): \"\"\" An example view that does not perform content negotiation. \"\"\" content_negotiation_class = IgnoreClientContentNegotiation def get(self, request, format=None): return Response({ 'accepted media type': request.accepted_renderer.media_type })","title":"Content negotiation"},{"location":"api-guide/content-negotiation/#content-negotiation","text":"HTTP has provisions for several mechanisms for \"content negotiation\" - the process of selecting the best representation for a given response when there are multiple representations available. \u2014 RFC 2616 , Fielding et al. Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences.","title":"Content negotiation"},{"location":"api-guide/content-negotiation/#determining-the-accepted-renderer","text":"REST framework uses a simple style of content negotiation to determine which media type should be returned to a client, based on the available renderers, the priorities of each of those renderers, and the client's Accept: header. The style used is partly client-driven, and partly server-driven. More specific media types are given preference to less specific media types. If multiple media types have the same specificity, then preference is given to based on the ordering of the renderers configured for the given view. For example, given the following Accept header: application/json; indent=4, application/json, application/yaml, text/html, */* The priorities for each of the given media types would be: application/json; indent=4 application/json , application/yaml and text/html */* If the requested view was only configured with renderers for YAML and HTML , then REST framework would select whichever renderer was listed first in the renderer_classes list or DEFAULT_RENDERER_CLASSES setting. For more information on the HTTP Accept header, see RFC 2616 Note : \"q\" values are not taken into account by REST framework when determining preference. The use of \"q\" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation. This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.","title":"Determining the accepted renderer"},{"location":"api-guide/content-negotiation/#custom-content-negotiation","text":"It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override BaseContentNegotiation . REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the .select_parser(request, parsers) and .select_renderer(request, renderers, format_suffix) methods. The select_parser() method should return one of the parser instances from the list of available parsers, or None if none of the parsers can handle the incoming request. The select_renderer() method should return a two-tuple of (renderer instance, media type), or raise a NotAcceptable exception.","title":"Custom content negotiation"},{"location":"api-guide/content-negotiation/#example","text":"The following is a custom content negotiation class which ignores the client request when selecting the appropriate parser or renderer. from rest_framework.negotiation import BaseContentNegotiation class IgnoreClientContentNegotiation(BaseContentNegotiation): def select_parser(self, request, parsers): \"\"\" Select the first parser in the `.parser_classes` list. \"\"\" return parsers[0] def select_renderer(self, request, renderers, format_suffix): \"\"\" Select the first renderer in the `.renderer_classes` list. \"\"\" return (renderers[0], renderers[0].media_type)","title":"Example"},{"location":"api-guide/content-negotiation/#setting-the-content-negotiation","text":"The default content negotiation class may be set globally, using the DEFAULT_CONTENT_NEGOTIATION_CLASS setting. For example, the following settings would use our example IgnoreClientContentNegotiation class. REST_FRAMEWORK = { 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation', } You can also set the content negotiation used for an individual view, or viewset, using the APIView class-based views. from myapp.negotiation import IgnoreClientContentNegotiation from rest_framework.response import Response from rest_framework.views import APIView class NoNegotiationView(APIView): \"\"\" An example view that does not perform content negotiation. \"\"\" content_negotiation_class = IgnoreClientContentNegotiation def get(self, request, format=None): return Response({ 'accepted media type': request.accepted_renderer.media_type })","title":"Setting the content negotiation"},{"location":"api-guide/exceptions/","text":"Exceptions Exceptions\u2026 allow error handling to be organized cleanly in a central or high-level place within the program structure. \u2014 Doug Hellmann, Python Exception Handling Techniques Exception handling in REST framework views REST framework's views handle various exceptions, and deal with returning appropriate error responses. The handled exceptions are: Subclasses of APIException raised inside REST framework. Django's Http404 exception. Django's PermissionDenied exception. In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error. Most error responses will include a key detail in the body of the response. For example, the following request: DELETE http://api.example.com/foo/bar HTTP/1.1 Accept: application/json Might receive an error response indicating that the DELETE method is not allowed on that resource: HTTP/1.1 405 Method Not Allowed Content-Type: application/json Content-Length: 42 {\"detail\": \"Method 'DELETE' not allowed.\"} Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the \"non_field_errors\" key, or whatever string value has been set for the NON_FIELD_ERRORS_KEY setting. Any example validation error might look like this: HTTP/1.1 400 Bad Request Content-Type: application/json Content-Length: 94 {\"amount\": [\"A valid integer is required.\"], \"description\": [\"This field may not be blank.\"]} Custom exception handling You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API. The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response. For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so: HTTP/1.1 405 Method Not Allowed Content-Type: application/json Content-Length: 62 {\"status_code\": 405, \"detail\": \"Method 'DELETE' not allowed.\"} In order to alter the style of the response, you could write the following custom exception handler: from rest_framework.views import exception_handler def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response is not None: response.data['status_code'] = response.status_code return response The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as context['view'] . The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER setting key. For example: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler' } If not specified, the 'EXCEPTION_HANDLER' setting defaults to the standard exception handler provided by REST framework: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' } Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails. API Reference APIException Signature: APIException() The base class for all exceptions raised inside an APIView class or @api_view . To provide a custom exception, subclass APIException and set the .status_code , .default_detail , and default_code attributes on the class. For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the \"503 Service Unavailable\" HTTP response code. You could do this like so: from rest_framework.exceptions import APIException class ServiceUnavailable(APIException): status_code = 503 default_detail = 'Service temporarily unavailable, try again later.' default_code = 'service_unavailable' Inspecting API exceptions There are a number of different properties available for inspecting the status of an API exception. You can use these to build custom exception handling for your project. The available attributes and methods are: .detail - Return the textual description of the error. .get_codes() - Return the code identifier of the error. .get_full_details() - Return both the textual description and the code identifier. In most cases the error detail will be a simple item: >>> print(exc.detail) You do not have permission to perform this action. >>> print(exc.get_codes()) permission_denied >>> print(exc.get_full_details()) {'message':'You do not have permission to perform this action.','code':'permission_denied'} In the case of validation errors the error detail will be either a list or dictionary of items: >>> print(exc.detail) {\"name\":\"This field is required.\",\"age\":\"A valid integer is required.\"} >>> print(exc.get_codes()) {\"name\":\"required\",\"age\":\"invalid\"} >>> print(exc.get_full_details()) {\"name\":{\"message\":\"This field is required.\",\"code\":\"required\"},\"age\":{\"message\":\"A valid integer is required.\",\"code\":\"invalid\"}} ParseError Signature: ParseError(detail=None, code=None) Raised if the request contains malformed data when accessing request.data . By default this exception results in a response with the HTTP status code \"400 Bad Request\". AuthenticationFailed Signature: AuthenticationFailed(detail=None, code=None) Raised when an incoming request includes incorrect authentication. By default this exception results in a response with the HTTP status code \"401 Unauthenticated\", but it may also result in a \"403 Forbidden\" response, depending on the authentication scheme in use. See the authentication documentation for more details. NotAuthenticated Signature: NotAuthenticated(detail=None, code=None) Raised when an unauthenticated request fails the permission checks. By default this exception results in a response with the HTTP status code \"401 Unauthenticated\", but it may also result in a \"403 Forbidden\" response, depending on the authentication scheme in use. See the authentication documentation for more details. PermissionDenied Signature: PermissionDenied(detail=None, code=None) Raised when an authenticated request fails the permission checks. By default this exception results in a response with the HTTP status code \"403 Forbidden\". NotFound Signature: NotFound(detail=None, code=None) Raised when a resource does not exists at the given URL. This exception is equivalent to the standard Http404 Django exception. By default this exception results in a response with the HTTP status code \"404 Not Found\". MethodNotAllowed Signature: MethodNotAllowed(method, detail=None, code=None) Raised when an incoming request occurs that does not map to a handler method on the view. By default this exception results in a response with the HTTP status code \"405 Method Not Allowed\". NotAcceptable Signature: NotAcceptable(detail=None, code=None) Raised when an incoming request occurs with an Accept header that cannot be satisfied by any of the available renderers. By default this exception results in a response with the HTTP status code \"406 Not Acceptable\". UnsupportedMediaType Signature: UnsupportedMediaType(media_type, detail=None, code=None) Raised if there are no parsers that can handle the content type of the request data when accessing request.data . By default this exception results in a response with the HTTP status code \"415 Unsupported Media Type\". Throttled Signature: Throttled(wait=None, detail=None, code=None) Raised when an incoming request fails the throttling checks. By default this exception results in a response with the HTTP status code \"429 Too Many Requests\". ValidationError Signature: ValidationError(detail, code=None) The ValidationError exception is slightly different from the other APIException classes: The detail argument is mandatory, not optional. The detail argument may be a list or dictionary of error details, and may also be a nested data structure. By convention you should import the serializers module and use a fully qualified ValidationError style, in order to differentiate it from Django's built-in validation error. For example. raise serializers.ValidationError('This field must be an integer value.') The ValidationError class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid with the raise_exception keyword argument: serializer.is_valid(raise_exception=True) The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above. By default this exception results in a response with the HTTP status code \"400 Bad Request\". Generic Error Views Django REST Framework provides two error views suitable for providing generic JSON 500 Server Error and 400 Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an API-only application.) Use these as per Django's Customizing error views documentation . rest_framework.exceptions.server_error Returns a response with status code 500 and application/json content type. Set as handler500 : handler500 = 'rest_framework.exceptions.server_error' rest_framework.exceptions.bad_request Returns a response with status code 400 and application/json content type. Set as handler400 : handler400 = 'rest_framework.exceptions.bad_request'","title":"Exceptions"},{"location":"api-guide/exceptions/#exceptions","text":"Exceptions\u2026 allow error handling to be organized cleanly in a central or high-level place within the program structure. \u2014 Doug Hellmann, Python Exception Handling Techniques","title":"Exceptions"},{"location":"api-guide/exceptions/#exception-handling-in-rest-framework-views","text":"REST framework's views handle various exceptions, and deal with returning appropriate error responses. The handled exceptions are: Subclasses of APIException raised inside REST framework. Django's Http404 exception. Django's PermissionDenied exception. In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error. Most error responses will include a key detail in the body of the response. For example, the following request: DELETE http://api.example.com/foo/bar HTTP/1.1 Accept: application/json Might receive an error response indicating that the DELETE method is not allowed on that resource: HTTP/1.1 405 Method Not Allowed Content-Type: application/json Content-Length: 42 {\"detail\": \"Method 'DELETE' not allowed.\"} Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the \"non_field_errors\" key, or whatever string value has been set for the NON_FIELD_ERRORS_KEY setting. Any example validation error might look like this: HTTP/1.1 400 Bad Request Content-Type: application/json Content-Length: 94 {\"amount\": [\"A valid integer is required.\"], \"description\": [\"This field may not be blank.\"]}","title":"Exception handling in REST framework views"},{"location":"api-guide/exceptions/#custom-exception-handling","text":"You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API. The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response. For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so: HTTP/1.1 405 Method Not Allowed Content-Type: application/json Content-Length: 62 {\"status_code\": 405, \"detail\": \"Method 'DELETE' not allowed.\"} In order to alter the style of the response, you could write the following custom exception handler: from rest_framework.views import exception_handler def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response is not None: response.data['status_code'] = response.status_code return response The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as context['view'] . The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER setting key. For example: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler' } If not specified, the 'EXCEPTION_HANDLER' setting defaults to the standard exception handler provided by REST framework: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' } Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails.","title":"Custom exception handling"},{"location":"api-guide/exceptions/#api-reference","text":"","title":"API Reference"},{"location":"api-guide/exceptions/#apiexception","text":"Signature: APIException() The base class for all exceptions raised inside an APIView class or @api_view . To provide a custom exception, subclass APIException and set the .status_code , .default_detail , and default_code attributes on the class. For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the \"503 Service Unavailable\" HTTP response code. You could do this like so: from rest_framework.exceptions import APIException class ServiceUnavailable(APIException): status_code = 503 default_detail = 'Service temporarily unavailable, try again later.' default_code = 'service_unavailable'","title":"APIException"},{"location":"api-guide/exceptions/#inspecting-api-exceptions","text":"There are a number of different properties available for inspecting the status of an API exception. You can use these to build custom exception handling for your project. The available attributes and methods are: .detail - Return the textual description of the error. .get_codes() - Return the code identifier of the error. .get_full_details() - Return both the textual description and the code identifier. In most cases the error detail will be a simple item: >>> print(exc.detail) You do not have permission to perform this action. >>> print(exc.get_codes()) permission_denied >>> print(exc.get_full_details()) {'message':'You do not have permission to perform this action.','code':'permission_denied'} In the case of validation errors the error detail will be either a list or dictionary of items: >>> print(exc.detail) {\"name\":\"This field is required.\",\"age\":\"A valid integer is required.\"} >>> print(exc.get_codes()) {\"name\":\"required\",\"age\":\"invalid\"} >>> print(exc.get_full_details()) {\"name\":{\"message\":\"This field is required.\",\"code\":\"required\"},\"age\":{\"message\":\"A valid integer is required.\",\"code\":\"invalid\"}}","title":"Inspecting API exceptions"},{"location":"api-guide/exceptions/#parseerror","text":"Signature: ParseError(detail=None, code=None) Raised if the request contains malformed data when accessing request.data . By default this exception results in a response with the HTTP status code \"400 Bad Request\".","title":"ParseError"},{"location":"api-guide/exceptions/#authenticationfailed","text":"Signature: AuthenticationFailed(detail=None, code=None) Raised when an incoming request includes incorrect authentication. By default this exception results in a response with the HTTP status code \"401 Unauthenticated\", but it may also result in a \"403 Forbidden\" response, depending on the authentication scheme in use. See the authentication documentation for more details.","title":"AuthenticationFailed"},{"location":"api-guide/exceptions/#notauthenticated","text":"Signature: NotAuthenticated(detail=None, code=None) Raised when an unauthenticated request fails the permission checks. By default this exception results in a response with the HTTP status code \"401 Unauthenticated\", but it may also result in a \"403 Forbidden\" response, depending on the authentication scheme in use. See the authentication documentation for more details.","title":"NotAuthenticated"},{"location":"api-guide/exceptions/#permissiondenied","text":"Signature: PermissionDenied(detail=None, code=None) Raised when an authenticated request fails the permission checks. By default this exception results in a response with the HTTP status code \"403 Forbidden\".","title":"PermissionDenied"},{"location":"api-guide/exceptions/#notfound","text":"Signature: NotFound(detail=None, code=None) Raised when a resource does not exists at the given URL. This exception is equivalent to the standard Http404 Django exception. By default this exception results in a response with the HTTP status code \"404 Not Found\".","title":"NotFound"},{"location":"api-guide/exceptions/#methodnotallowed","text":"Signature: MethodNotAllowed(method, detail=None, code=None) Raised when an incoming request occurs that does not map to a handler method on the view. By default this exception results in a response with the HTTP status code \"405 Method Not Allowed\".","title":"MethodNotAllowed"},{"location":"api-guide/exceptions/#notacceptable","text":"Signature: NotAcceptable(detail=None, code=None) Raised when an incoming request occurs with an Accept header that cannot be satisfied by any of the available renderers. By default this exception results in a response with the HTTP status code \"406 Not Acceptable\".","title":"NotAcceptable"},{"location":"api-guide/exceptions/#unsupportedmediatype","text":"Signature: UnsupportedMediaType(media_type, detail=None, code=None) Raised if there are no parsers that can handle the content type of the request data when accessing request.data . By default this exception results in a response with the HTTP status code \"415 Unsupported Media Type\".","title":"UnsupportedMediaType"},{"location":"api-guide/exceptions/#throttled","text":"Signature: Throttled(wait=None, detail=None, code=None) Raised when an incoming request fails the throttling checks. By default this exception results in a response with the HTTP status code \"429 Too Many Requests\".","title":"Throttled"},{"location":"api-guide/exceptions/#validationerror","text":"Signature: ValidationError(detail, code=None) The ValidationError exception is slightly different from the other APIException classes: The detail argument is mandatory, not optional. The detail argument may be a list or dictionary of error details, and may also be a nested data structure. By convention you should import the serializers module and use a fully qualified ValidationError style, in order to differentiate it from Django's built-in validation error. For example. raise serializers.ValidationError('This field must be an integer value.') The ValidationError class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid with the raise_exception keyword argument: serializer.is_valid(raise_exception=True) The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above. By default this exception results in a response with the HTTP status code \"400 Bad Request\".","title":"ValidationError"},{"location":"api-guide/exceptions/#generic-error-views","text":"Django REST Framework provides two error views suitable for providing generic JSON 500 Server Error and 400 Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an API-only application.) Use these as per Django's Customizing error views documentation .","title":"Generic Error Views"},{"location":"api-guide/exceptions/#rest_frameworkexceptionsserver_error","text":"Returns a response with status code 500 and application/json content type. Set as handler500 : handler500 = 'rest_framework.exceptions.server_error'","title":"rest_framework.exceptions.server_error"},{"location":"api-guide/exceptions/#rest_frameworkexceptionsbad_request","text":"Returns a response with status code 400 and application/json content type. Set as handler400 : handler400 = 'rest_framework.exceptions.bad_request'","title":"rest_framework.exceptions.bad_request"},{"location":"api-guide/fields/","text":"Serializer fields Each field in a Form class is responsible not only for validating data, but also for \"cleaning\" it \u2014 normalizing it to a consistent format. \u2014 Django documentation Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects. Note: The serializer fields are declared in fields.py , but by convention you should import them using from rest_framework import serializers and refer to fields as serializers. . Core arguments Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: read_only Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored. Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization. Defaults to False write_only Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. Defaults to False required Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization. Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. Defaults to True . default If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all. The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned. May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a set_context method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for validators . When serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance. Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error. allow_null Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. Note that, without an explicit default , setting this argument to True will imply a default value of null for serialization output, but does not imply a default for input deserialization. Defaults to False source The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url') , or may use dotted notation to traverse attributes, such as EmailField(source='user.email') . When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal. The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. Defaults to the name of the field. validators A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError , but Django's built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages. error_messages A dictionary of error codes to error messages. label A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. help_text A text string that may be used as a description of the field in HTML form fields or other descriptive elements. initial A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as you may do with any regular Django Field : import datetime from rest_framework import serializers class ExampleSerializer(serializers.Serializer): day = serializers.DateField(initial=datetime.date.today) style A dictionary of key-value pairs that can be used to control how renderers should render the field. Two examples here are 'input_type' and 'base_template' : # Use for the input. password = serializers.CharField( style={'input_type': 'password'} ) # Use a radio input instead of a select input. color_channel = serializers.ChoiceField( choices=['red', 'green', 'blue'], style={'base_template': 'radio.html'} ) For more details see the HTML & Forms documentation. Boolean fields BooleanField A boolean representation. When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to False , even if it has a default=True option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input. Note that Django 2.1 removed the blank kwarg from models.BooleanField . Prior to Django 2.1 models.BooleanField fields were always blank=True . Thus since Django 2.1 default serializers.BooleanField instances will be generated without the required kwarg (i.e. equivalent to required=True ) whereas with previous versions of Django, default BooleanField instances will be generated with a required=False option. If you want to control this behaviour manually, explicitly declare the BooleanField on the serializer class, or use the extra_kwargs option to set the required flag. Corresponds to django.db.models.fields.BooleanField . Signature: BooleanField() NullBooleanField A boolean representation that also accepts None as a valid value. Corresponds to django.db.models.fields.NullBooleanField . Signature: NullBooleanField() String fields CharField A text representation. Optionally validates the text to be shorter than max_length and longer than min_length . Corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField . Signature: CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) max_length - Validates that the input contains no more than this number of characters. min_length - Validates that the input contains no fewer than this number of characters. allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False . trim_whitespace - If set to True then leading and trailing whitespace is trimmed. Defaults to True . The allow_null option is also available for string fields, although its usage is discouraged in favor of allow_blank . It is valid to set both allow_blank=True and allow_null=True , but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs. EmailField A text representation, validates the text to be a valid e-mail address. Corresponds to django.db.models.fields.EmailField Signature: EmailField(max_length=None, min_length=None, allow_blank=False) RegexField A text representation, that validates the given value matches against a certain regular expression. Corresponds to django.forms.fields.RegexField . Signature: RegexField(regex, max_length=None, min_length=None, allow_blank=False) The mandatory regex argument may either be a string, or a compiled python regular expression object. Uses Django's django.core.validators.RegexValidator for validation. SlugField A RegexField that validates the input against the pattern [a-zA-Z0-9_-]+ . Corresponds to django.db.models.fields.SlugField . Signature: SlugField(max_length=50, min_length=None, allow_blank=False) URLField A RegexField that validates the input against a URL matching pattern. Expects fully qualified URLs of the form http:/// . Corresponds to django.db.models.fields.URLField . Uses Django's django.core.validators.URLValidator for validation. Signature: URLField(max_length=200, min_length=None, allow_blank=False) UUIDField A field that ensures the input is a valid UUID string. The to_internal_value method will return a uuid.UUID instance. On output the field will return a string in the canonical hyphenated format, for example: \"de305d54-75b4-431b-adb2-eb6b9e546013\" Signature: UUIDField(format='hex_verbose') format : Determines the representation format of the uuid value 'hex_verbose' - The canonical hex representation, including hyphens: \"5ce0e9a5-5ffa-654b-cee0-1238041fb31a\" 'hex' - The compact hex representation of the UUID, not including hyphens: \"5ce0e9a55ffa654bcee01238041fb31a\" 'int' - A 128 bit integer representation of the UUID: \"123456789012312313134124512351145145114\" 'urn' - RFC 4122 URN representation of the UUID: \"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a\" Changing the format parameters only affects representation values. All formats are accepted by to_internal_value FilePathField A field whose choices are limited to the filenames in a certain directory on the filesystem Corresponds to django.forms.fields.FilePathField . Signature: FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs) path - The absolute filesystem path to a directory from which this FilePathField should get its choice. match - A regular expression, as a string, that FilePathField will use to filter filenames. recursive - Specifies whether all subdirectories of path should be included. Default is False . allow_files - Specifies whether files in the specified location should be included. Default is True . Either this or allow_folders must be True . allow_folders - Specifies whether folders in the specified location should be included. Default is False . Either this or allow_files must be True . IPAddressField A field that ensures the input is a valid IPv4 or IPv6 string. Corresponds to django.forms.fields.IPAddressField and django.forms.fields.GenericIPAddressField . Signature : IPAddressField(protocol='both', unpack_ipv4=False, **options) protocol Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive. unpack_ipv4 Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'. Numeric fields IntegerField An integer representation. Corresponds to django.db.models.fields.IntegerField , django.db.models.fields.SmallIntegerField , django.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField . Signature : IntegerField(max_value=None, min_value=None) max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. FloatField A floating point representation. Corresponds to django.db.models.fields.FloatField . Signature : FloatField(max_value=None, min_value=None) max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. DecimalField A decimal representation, represented in Python by a Decimal instance. Corresponds to django.db.models.fields.DecimalField . Signature : DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places . decimal_places The number of decimal places to store with the number. coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting localize will force the value to True . max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. localize Set to True to enable localization of input and output based on the current locale. This will also force coerce_to_string to True . Defaults to False . Note that data formatting is enabled if you have set USE_L10N=True in your settings file. rounding Sets the rounding mode used when quantising to the configured precision. Valid values are decimal module rounding modes . Defaults to None . Example usage To validate numbers up to 999 with a resolution of 2 decimal places, you would use: serializers.DecimalField(max_digits=5, decimal_places=2) And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: serializers.DecimalField(max_digits=19, decimal_places=10) This field also takes an optional argument, coerce_to_string . If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer. If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise. Date and time fields DateTimeField A date and time representation. Corresponds to django.db.models.fields.DateTimeField . Signature: DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None) format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation . In this case the datetime encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] . default_timezone - A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone . If USE_TZ is disabled, then datetime objects will be naive. DateTimeField format strings. Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z' ) When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class. auto_now and auto_now_add model fields. When using ModelSerializer or HyperlinkedModelSerializer , note that any model fields with auto_now=True or auto_now_add=True will use serializer fields that are read_only=True by default. If you want to override this behavior, you'll need to declare the DateTimeField explicitly on the serializer. For example: class CommentSerializer(serializers.ModelSerializer): created = serializers.DateTimeField() class Meta: model = Comment DateField A date representation. Corresponds to django.db.models.fields.DateField Signature: DateField(format=api_settings.DATE_FORMAT, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation . In this case the date encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] . DateField format strings Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style dates should be used. (eg '2013-01-29' ) TimeField A time representation. Corresponds to django.db.models.fields.TimeField Signature: TimeField(format=api_settings.TIME_FORMAT, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation . In this case the time encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] . TimeField format strings Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000' ) DurationField A Duration representation. Corresponds to django.db.models.fields.DurationField The validated_data for these fields will contain a datetime.timedelta instance. The representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]' . Signature: DurationField(max_value=None, min_value=None) max_value Validate that the duration provided is no greater than this value. min_value Validate that the duration provided is no less than this value. Choice selection fields ChoiceField A field that can accept a value out of a limited set of choices. Used by ModelSerializer to automatically generate fields if the corresponding model field includes a choices=\u2026 argument. Signature: ChoiceField(choices) choices - A list of valid values, or a list of (key, display_name) tuples. allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False . html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None . html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \"More than {count} items\u2026\" Both the allow_blank and allow_null are valid options on ChoiceField , although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices. MultipleChoiceField A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. to_internal_value returns a set containing the selected values. Signature: MultipleChoiceField(choices) choices - A list of valid values, or a list of (key, display_name) tuples. allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False . html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None . html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \"More than {count} items\u2026\" As with ChoiceField , both the allow_blank and allow_null options are valid, although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices. File upload fields Parsers and file uploads. The FileField and ImageField classes are only suitable for use with MultiPartParser or FileUploadParser . Most parsers, such as e.g. JSON don't support file uploads. Django's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files. FileField A file representation. Performs Django's standard FileField validation. Corresponds to django.forms.fields.FileField . Signature: FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) max_length - Designates the maximum length for the file name. allow_empty_file - Designates if empty files are allowed. use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise. ImageField An image representation. Validates the uploaded file content as matching a known image format. Corresponds to django.forms.fields.ImageField . Signature: ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) max_length - Designates the maximum length for the file name. allow_empty_file - Designates if empty files are allowed. use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise. Requires either the Pillow package or PIL package. The Pillow package is recommended, as PIL is no longer actively maintained. Composite fields ListField A field class that validates a list of objects. Signature : ListField(child=, allow_empty=True, min_length=None, max_length=None) child - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated. allow_empty - Designates if empty lists are allowed. min_length - Validates that the list contains no fewer than this number of elements. max_length - Validates that the list contains no more than this number of elements. For example, to validate a list of integers you might use something like the following: scores = serializers.ListField( child=serializers.IntegerField(min_value=0, max_value=100) ) The ListField class also supports a declarative style that allows you to write reusable list field classes. class StringListField(serializers.ListField): child = serializers.CharField() We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it. DictField A field class that validates a dictionary of objects. The keys in DictField are always assumed to be string values. Signature : DictField(child=, allow_empty=True) child - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated. allow_empty - Designates if empty dictionaries are allowed. For example, to create a field that validates a mapping of strings to strings, you would write something like this: document = DictField(child=CharField()) You can also use the declarative style, as with ListField . For example: class DocumentField(DictField): child = CharField() HStoreField A preconfigured DictField that is compatible with Django's postgres HStoreField . Signature : HStoreField(child=, allow_empty=True) child - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values. allow_empty - Designates if empty dictionaries are allowed. Note that the child field must be an instance of CharField , as the hstore extension stores values as strings. JSONField A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings. Signature : JSONField(binary, encoder) binary - If set to True then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to False . encoder - Use this JSON encoder to serialize input object. Defaults to None . Miscellaneous fields ReadOnlyField A field class that simply returns the value of the field without modification. This field is used by default with ModelSerializer when including field names that relate to an attribute rather than a model field. Signature : ReadOnlyField() For example, if has_expired was a property on the Account model, then the following serializer would automatically generate it as a ReadOnlyField : class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'has_expired'] HiddenField A field class that does not take a value based on user input, but instead takes its value from a default value or callable. Signature : HiddenField() For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following: modified = serializers.HiddenField(default=timezone.now) The HiddenField class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user. For further examples on HiddenField see the validators documentation. ModelField A generic field that can be tied to any arbitrary model field. The ModelField class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. This field is used by ModelSerializer to correspond to custom model field classes. Signature: ModelField(model_field=) The ModelField class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a ModelField , it must be passed a field that is attached to an instantiated model. For example: ModelField(model_field=MyModel()._meta.get_field('custom_field')) SerializerMethodField This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. Signature : SerializerMethodField(method_name=None) method_name - The name of the method on the serializer to be called. If not included this defaults to get_ . The serializer method referred to by the method_name argument should accept a single argument (in addition to self ), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: from django.contrib.auth.models import User from django.utils.timezone import now from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): days_since_joined = serializers.SerializerMethodField() class Meta: model = User def get_days_since_joined(self, obj): return (now() - obj.date_joined).days Custom fields If you want to create a custom field, you'll need to subclass Field and then override either one or both of the .to_representation() and .to_internal_value() methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, date / time / datetime or None . They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using. The .to_representation() method is called to convert the initial datatype into a primitive, serializable datatype. The to_internal_value() method is called to restore a primitive datatype into its internal python representation. This method should raise a serializers.ValidationError if the data is invalid. Note that the WritableField class that was present in version 2.x no longer exists. You should subclass Field and override to_internal_value() if the field supports data input. Examples A Basic Custom Field Let's look at an example of serializing a class that represents an RGB color value: class Color(object): \"\"\" A color represented in the RGB colorspace. \"\"\" def __init__(self, red, green, blue): assert(red >= 0 and green >= 0 and blue >= 0) assert(red < 256 and green < 256 and blue < 256) self.red, self.green, self.blue = red, green, blue class ColorField(serializers.Field): \"\"\" Color objects are serialized into 'rgb(#, #, #)' notation. \"\"\" def to_representation(self, value): return \"rgb(%d, %d, %d)\" % (value.red, value.green, value.blue) def to_internal_value(self, data): data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] return Color(red, green, blue) By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override .get_attribute() and/or .get_value() . As an example, let's create a field that can be used to represent the class name of the object being serialized: class ClassNameField(serializers.Field): def get_attribute(self, instance): # We pass the object instance onto `to_representation`, # not just the field attribute. return instance def to_representation(self, value): \"\"\" Serialize the value's class name. \"\"\" return value.__class__.__name__ Raising validation errors Our ColorField class above currently does not perform any data validation. To indicate invalid data, we should raise a serializers.ValidationError , like so: def to_internal_value(self, data): if not isinstance(data, str): msg = 'Incorrect type. Expected a string, but got %s' raise ValidationError(msg % type(data).__name__) if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data): raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.') data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] if any([col > 255 or col < 0 for col in (red, green, blue)]): raise ValidationError('Value out of range. Must be between 0 and 255.') return Color(red, green, blue) The .fail() method is a shortcut for raising ValidationError that takes a message string from the error_messages dictionary. For example: default_error_messages = { 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}', 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.', 'out_of_range': 'Value out of range. Must be between 0 and 255.' } def to_internal_value(self, data): if not isinstance(data, str): self.fail('incorrect_type', input_type=type(data).__name__) if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data): self.fail('incorrect_format') data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] if any([col > 255 or col < 0 for col in (red, green, blue)]): self.fail('out_of_range') return Color(red, green, blue) This style keeps your error messages cleaner and more separated from your code, and should be preferred. Using source='*' Here we'll take an example of a flat DataPoint model with x_coordinate and y_coordinate attributes. class DataPoint(models.Model): label = models.CharField(max_length=50) x_coordinate = models.SmallIntegerField() y_coordinate = models.SmallIntegerField() Using a custom field and source='*' we can provide a nested representation of the coordinate pair: class CoordinateField(serializers.Field): def to_representation(self, value): ret = { \"x\": value.x_coordinate, \"y\": value.y_coordinate } return ret def to_internal_value(self, data): ret = { \"x_coordinate\": data[\"x\"], \"y_coordinate\": data[\"y\"], } return ret class DataPointSerializer(serializers.ModelSerializer): coordinates = CoordinateField(source='*') class Meta: model = DataPoint fields = ['label', 'coordinates'] Note that this example doesn't handle validation. Partly for that reason, in a real project, the coordinate nesting might be better handled with a nested serialiser using source='*' , with two IntegerField instances, each with their own source pointing to the relevant field. The key points from the example, though, are: to_representation is passed the entire DataPoint object and must map from that to the desired output. >>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2) >>> out_serializer = DataPointSerializer(instance) >>> out_serializer.data ReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})]) Unless our field is to be read-only, to_internal_value must map back to a dict suitable for updating our target object. With source='*' , the return from to_internal_value will update the root validated data dictionary, rather than a single key. >>> data = { ... \"label\": \"Second Example\", ... \"coordinates\": { ... \"x\": 3, ... \"y\": 4, ... } ... } >>> in_serializer = DataPointSerializer(data=data) >>> in_serializer.is_valid() True >>> in_serializer.validated_data OrderedDict([('label', 'Second Example'), ('y_coordinate', 4), ('x_coordinate', 3)]) For completeness lets do the same thing again but with the nested serialiser approach suggested above: class NestedCoordinateSerializer(serializers.Serializer): x = serializers.IntegerField(source='x_coordinate') y = serializers.IntegerField(source='y_coordinate') class DataPointSerializer(serializers.ModelSerializer): coordinates = NestedCoordinateSerializer(source='*') class Meta: model = DataPoint fields = ['label', 'coordinates'] Here the mapping between the target and source attribute pairs ( x and x_coordinate , y and y_coordinate ) is handled in the IntegerField declarations. It's our NestedCoordinateSerializer that takes source='*' . Our new DataPointSerializer exhibits the same behaviour as the custom field approach. Serialising: >>> out_serializer = DataPointSerializer(instance) >>> out_serializer.data ReturnDict([('label', 'testing'), ('coordinates', OrderedDict([('x', 1), ('y', 2)]))]) Deserialising: >>> in_serializer = DataPointSerializer(data=data) >>> in_serializer.is_valid() True >>> in_serializer.validated_data OrderedDict([('label', 'still testing'), ('x_coordinate', 3), ('y_coordinate', 4)]) But we also get the built-in validation for free: >>> invalid_data = { ... \"label\": \"still testing\", ... \"coordinates\": { ... \"x\": 'a', ... \"y\": 'b', ... } ... } >>> invalid_serializer = DataPointSerializer(data=invalid_data) >>> invalid_serializer.is_valid() False >>> invalid_serializer.errors ReturnDict([('coordinates', {'x': ['A valid integer is required.'], 'y': ['A valid integer is required.']})]) For this reason, the nested serialiser approach would be the first to try. You would use the custom field approach when the nested serialiser becomes infeasible or overly complex. Third party packages The following third party packages are also available. DRF Compound Fields The drf-compound-fields package provides \"compound\" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the many=True option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type. DRF Extra Fields The drf-extra-fields package provides extra serializer fields for REST framework, including Base64ImageField and PointField classes. djangorestframework-recursive the djangorestframework-recursive package provides a RecursiveField for serializing and deserializing recursive structures django-rest-framework-gis The django-rest-framework-gis package provides geographic addons for django rest framework like a GeometryField field and a GeoJSON serializer. django-rest-framework-hstore The django-rest-framework-hstore package provides an HStoreField to support django-hstore DictionaryField model field.","title":"Serializer fields"},{"location":"api-guide/fields/#serializer-fields","text":"Each field in a Form class is responsible not only for validating data, but also for \"cleaning\" it \u2014 normalizing it to a consistent format. \u2014 Django documentation Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects. Note: The serializer fields are declared in fields.py , but by convention you should import them using from rest_framework import serializers and refer to fields as serializers. .","title":"Serializer fields"},{"location":"api-guide/fields/#core-arguments","text":"Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:","title":"Core arguments"},{"location":"api-guide/fields/#read_only","text":"Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored. Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization. Defaults to False","title":"read_only"},{"location":"api-guide/fields/#write_only","text":"Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. Defaults to False","title":"write_only"},{"location":"api-guide/fields/#required","text":"Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization. Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. Defaults to True .","title":"required"},{"location":"api-guide/fields/#default","text":"If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all. The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned. May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a set_context method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for validators . When serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance. Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error.","title":"default"},{"location":"api-guide/fields/#allow_null","text":"Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. Note that, without an explicit default , setting this argument to True will imply a default value of null for serialization output, but does not imply a default for input deserialization. Defaults to False","title":"allow_null"},{"location":"api-guide/fields/#source","text":"The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url') , or may use dotted notation to traverse attributes, such as EmailField(source='user.email') . When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal. The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. Defaults to the name of the field.","title":"source"},{"location":"api-guide/fields/#validators","text":"A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError , but Django's built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages.","title":"validators"},{"location":"api-guide/fields/#error_messages","text":"A dictionary of error codes to error messages.","title":"error_messages"},{"location":"api-guide/fields/#label","text":"A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.","title":"label"},{"location":"api-guide/fields/#help_text","text":"A text string that may be used as a description of the field in HTML form fields or other descriptive elements.","title":"help_text"},{"location":"api-guide/fields/#initial","text":"A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as you may do with any regular Django Field : import datetime from rest_framework import serializers class ExampleSerializer(serializers.Serializer): day = serializers.DateField(initial=datetime.date.today)","title":"initial"},{"location":"api-guide/fields/#style","text":"A dictionary of key-value pairs that can be used to control how renderers should render the field. Two examples here are 'input_type' and 'base_template' : # Use for the input. password = serializers.CharField( style={'input_type': 'password'} ) # Use a radio input instead of a select input. color_channel = serializers.ChoiceField( choices=['red', 'green', 'blue'], style={'base_template': 'radio.html'} ) For more details see the HTML & Forms documentation.","title":"style"},{"location":"api-guide/fields/#boolean-fields","text":"","title":"Boolean fields"},{"location":"api-guide/fields/#booleanfield","text":"A boolean representation. When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to False , even if it has a default=True option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input. Note that Django 2.1 removed the blank kwarg from models.BooleanField . Prior to Django 2.1 models.BooleanField fields were always blank=True . Thus since Django 2.1 default serializers.BooleanField instances will be generated without the required kwarg (i.e. equivalent to required=True ) whereas with previous versions of Django, default BooleanField instances will be generated with a required=False option. If you want to control this behaviour manually, explicitly declare the BooleanField on the serializer class, or use the extra_kwargs option to set the required flag. Corresponds to django.db.models.fields.BooleanField . Signature: BooleanField()","title":"BooleanField"},{"location":"api-guide/fields/#nullbooleanfield","text":"A boolean representation that also accepts None as a valid value. Corresponds to django.db.models.fields.NullBooleanField . Signature: NullBooleanField()","title":"NullBooleanField"},{"location":"api-guide/fields/#string-fields","text":"","title":"String fields"},{"location":"api-guide/fields/#charfield","text":"A text representation. Optionally validates the text to be shorter than max_length and longer than min_length . Corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField . Signature: CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) max_length - Validates that the input contains no more than this number of characters. min_length - Validates that the input contains no fewer than this number of characters. allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False . trim_whitespace - If set to True then leading and trailing whitespace is trimmed. Defaults to True . The allow_null option is also available for string fields, although its usage is discouraged in favor of allow_blank . It is valid to set both allow_blank=True and allow_null=True , but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.","title":"CharField"},{"location":"api-guide/fields/#emailfield","text":"A text representation, validates the text to be a valid e-mail address. Corresponds to django.db.models.fields.EmailField Signature: EmailField(max_length=None, min_length=None, allow_blank=False)","title":"EmailField"},{"location":"api-guide/fields/#regexfield","text":"A text representation, that validates the given value matches against a certain regular expression. Corresponds to django.forms.fields.RegexField . Signature: RegexField(regex, max_length=None, min_length=None, allow_blank=False) The mandatory regex argument may either be a string, or a compiled python regular expression object. Uses Django's django.core.validators.RegexValidator for validation.","title":"RegexField"},{"location":"api-guide/fields/#slugfield","text":"A RegexField that validates the input against the pattern [a-zA-Z0-9_-]+ . Corresponds to django.db.models.fields.SlugField . Signature: SlugField(max_length=50, min_length=None, allow_blank=False)","title":"SlugField"},{"location":"api-guide/fields/#urlfield","text":"A RegexField that validates the input against a URL matching pattern. Expects fully qualified URLs of the form http:/// . Corresponds to django.db.models.fields.URLField . Uses Django's django.core.validators.URLValidator for validation. Signature: URLField(max_length=200, min_length=None, allow_blank=False)","title":"URLField"},{"location":"api-guide/fields/#uuidfield","text":"A field that ensures the input is a valid UUID string. The to_internal_value method will return a uuid.UUID instance. On output the field will return a string in the canonical hyphenated format, for example: \"de305d54-75b4-431b-adb2-eb6b9e546013\" Signature: UUIDField(format='hex_verbose') format : Determines the representation format of the uuid value 'hex_verbose' - The canonical hex representation, including hyphens: \"5ce0e9a5-5ffa-654b-cee0-1238041fb31a\" 'hex' - The compact hex representation of the UUID, not including hyphens: \"5ce0e9a55ffa654bcee01238041fb31a\" 'int' - A 128 bit integer representation of the UUID: \"123456789012312313134124512351145145114\" 'urn' - RFC 4122 URN representation of the UUID: \"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a\" Changing the format parameters only affects representation values. All formats are accepted by to_internal_value","title":"UUIDField"},{"location":"api-guide/fields/#filepathfield","text":"A field whose choices are limited to the filenames in a certain directory on the filesystem Corresponds to django.forms.fields.FilePathField . Signature: FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs) path - The absolute filesystem path to a directory from which this FilePathField should get its choice. match - A regular expression, as a string, that FilePathField will use to filter filenames. recursive - Specifies whether all subdirectories of path should be included. Default is False . allow_files - Specifies whether files in the specified location should be included. Default is True . Either this or allow_folders must be True . allow_folders - Specifies whether folders in the specified location should be included. Default is False . Either this or allow_files must be True .","title":"FilePathField"},{"location":"api-guide/fields/#ipaddressfield","text":"A field that ensures the input is a valid IPv4 or IPv6 string. Corresponds to django.forms.fields.IPAddressField and django.forms.fields.GenericIPAddressField . Signature : IPAddressField(protocol='both', unpack_ipv4=False, **options) protocol Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive. unpack_ipv4 Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.","title":"IPAddressField"},{"location":"api-guide/fields/#numeric-fields","text":"","title":"Numeric fields"},{"location":"api-guide/fields/#integerfield","text":"An integer representation. Corresponds to django.db.models.fields.IntegerField , django.db.models.fields.SmallIntegerField , django.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField . Signature : IntegerField(max_value=None, min_value=None) max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value.","title":"IntegerField"},{"location":"api-guide/fields/#floatfield","text":"A floating point representation. Corresponds to django.db.models.fields.FloatField . Signature : FloatField(max_value=None, min_value=None) max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value.","title":"FloatField"},{"location":"api-guide/fields/#decimalfield","text":"A decimal representation, represented in Python by a Decimal instance. Corresponds to django.db.models.fields.DecimalField . Signature : DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places . decimal_places The number of decimal places to store with the number. coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting localize will force the value to True . max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. localize Set to True to enable localization of input and output based on the current locale. This will also force coerce_to_string to True . Defaults to False . Note that data formatting is enabled if you have set USE_L10N=True in your settings file. rounding Sets the rounding mode used when quantising to the configured precision. Valid values are decimal module rounding modes . Defaults to None .","title":"DecimalField"},{"location":"api-guide/fields/#example-usage","text":"To validate numbers up to 999 with a resolution of 2 decimal places, you would use: serializers.DecimalField(max_digits=5, decimal_places=2) And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: serializers.DecimalField(max_digits=19, decimal_places=10) This field also takes an optional argument, coerce_to_string . If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer. If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise.","title":"Example usage"},{"location":"api-guide/fields/#date-and-time-fields","text":"","title":"Date and time fields"},{"location":"api-guide/fields/#datetimefield","text":"A date and time representation. Corresponds to django.db.models.fields.DateTimeField . Signature: DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None) format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation . In this case the datetime encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] . default_timezone - A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone . If USE_TZ is disabled, then datetime objects will be naive.","title":"DateTimeField"},{"location":"api-guide/fields/#datetimefield-format-strings","text":"Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z' ) When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class.","title":"DateTimeField format strings."},{"location":"api-guide/fields/#auto_now-and-auto_now_add-model-fields","text":"When using ModelSerializer or HyperlinkedModelSerializer , note that any model fields with auto_now=True or auto_now_add=True will use serializer fields that are read_only=True by default. If you want to override this behavior, you'll need to declare the DateTimeField explicitly on the serializer. For example: class CommentSerializer(serializers.ModelSerializer): created = serializers.DateTimeField() class Meta: model = Comment","title":"auto_now and auto_now_add model fields."},{"location":"api-guide/fields/#datefield","text":"A date representation. Corresponds to django.db.models.fields.DateField Signature: DateField(format=api_settings.DATE_FORMAT, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation . In this case the date encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] .","title":"DateField"},{"location":"api-guide/fields/#datefield-format-strings","text":"Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style dates should be used. (eg '2013-01-29' )","title":"DateField format strings"},{"location":"api-guide/fields/#timefield","text":"A time representation. Corresponds to django.db.models.fields.TimeField Signature: TimeField(format=api_settings.TIME_FORMAT, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation . In this case the time encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] .","title":"TimeField"},{"location":"api-guide/fields/#timefield-format-strings","text":"Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000' )","title":"TimeField format strings"},{"location":"api-guide/fields/#durationfield","text":"A Duration representation. Corresponds to django.db.models.fields.DurationField The validated_data for these fields will contain a datetime.timedelta instance. The representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]' . Signature: DurationField(max_value=None, min_value=None) max_value Validate that the duration provided is no greater than this value. min_value Validate that the duration provided is no less than this value.","title":"DurationField"},{"location":"api-guide/fields/#choice-selection-fields","text":"","title":"Choice selection fields"},{"location":"api-guide/fields/#choicefield","text":"A field that can accept a value out of a limited set of choices. Used by ModelSerializer to automatically generate fields if the corresponding model field includes a choices=\u2026 argument. Signature: ChoiceField(choices) choices - A list of valid values, or a list of (key, display_name) tuples. allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False . html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None . html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \"More than {count} items\u2026\" Both the allow_blank and allow_null are valid options on ChoiceField , although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices.","title":"ChoiceField"},{"location":"api-guide/fields/#multiplechoicefield","text":"A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. to_internal_value returns a set containing the selected values. Signature: MultipleChoiceField(choices) choices - A list of valid values, or a list of (key, display_name) tuples. allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False . html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None . html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \"More than {count} items\u2026\" As with ChoiceField , both the allow_blank and allow_null options are valid, although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices.","title":"MultipleChoiceField"},{"location":"api-guide/fields/#file-upload-fields","text":"","title":"File upload fields"},{"location":"api-guide/fields/#parsers-and-file-uploads","text":"The FileField and ImageField classes are only suitable for use with MultiPartParser or FileUploadParser . Most parsers, such as e.g. JSON don't support file uploads. Django's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files.","title":"Parsers and file uploads."},{"location":"api-guide/fields/#filefield","text":"A file representation. Performs Django's standard FileField validation. Corresponds to django.forms.fields.FileField . Signature: FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) max_length - Designates the maximum length for the file name. allow_empty_file - Designates if empty files are allowed. use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.","title":"FileField"},{"location":"api-guide/fields/#imagefield","text":"An image representation. Validates the uploaded file content as matching a known image format. Corresponds to django.forms.fields.ImageField . Signature: ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) max_length - Designates the maximum length for the file name. allow_empty_file - Designates if empty files are allowed. use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise. Requires either the Pillow package or PIL package. The Pillow package is recommended, as PIL is no longer actively maintained.","title":"ImageField"},{"location":"api-guide/fields/#composite-fields","text":"","title":"Composite fields"},{"location":"api-guide/fields/#listfield","text":"A field class that validates a list of objects. Signature : ListField(child=, allow_empty=True, min_length=None, max_length=None) child - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated. allow_empty - Designates if empty lists are allowed. min_length - Validates that the list contains no fewer than this number of elements. max_length - Validates that the list contains no more than this number of elements. For example, to validate a list of integers you might use something like the following: scores = serializers.ListField( child=serializers.IntegerField(min_value=0, max_value=100) ) The ListField class also supports a declarative style that allows you to write reusable list field classes. class StringListField(serializers.ListField): child = serializers.CharField() We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it.","title":"ListField"},{"location":"api-guide/fields/#dictfield","text":"A field class that validates a dictionary of objects. The keys in DictField are always assumed to be string values. Signature : DictField(child=, allow_empty=True) child - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated. allow_empty - Designates if empty dictionaries are allowed. For example, to create a field that validates a mapping of strings to strings, you would write something like this: document = DictField(child=CharField()) You can also use the declarative style, as with ListField . For example: class DocumentField(DictField): child = CharField()","title":"DictField"},{"location":"api-guide/fields/#hstorefield","text":"A preconfigured DictField that is compatible with Django's postgres HStoreField . Signature : HStoreField(child=, allow_empty=True) child - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values. allow_empty - Designates if empty dictionaries are allowed. Note that the child field must be an instance of CharField , as the hstore extension stores values as strings.","title":"HStoreField"},{"location":"api-guide/fields/#jsonfield","text":"A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings. Signature : JSONField(binary, encoder) binary - If set to True then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to False . encoder - Use this JSON encoder to serialize input object. Defaults to None .","title":"JSONField"},{"location":"api-guide/fields/#miscellaneous-fields","text":"","title":"Miscellaneous fields"},{"location":"api-guide/fields/#readonlyfield","text":"A field class that simply returns the value of the field without modification. This field is used by default with ModelSerializer when including field names that relate to an attribute rather than a model field. Signature : ReadOnlyField() For example, if has_expired was a property on the Account model, then the following serializer would automatically generate it as a ReadOnlyField : class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'has_expired']","title":"ReadOnlyField"},{"location":"api-guide/fields/#hiddenfield","text":"A field class that does not take a value based on user input, but instead takes its value from a default value or callable. Signature : HiddenField() For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following: modified = serializers.HiddenField(default=timezone.now) The HiddenField class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user. For further examples on HiddenField see the validators documentation.","title":"HiddenField"},{"location":"api-guide/fields/#modelfield","text":"A generic field that can be tied to any arbitrary model field. The ModelField class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. This field is used by ModelSerializer to correspond to custom model field classes. Signature: ModelField(model_field=) The ModelField class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a ModelField , it must be passed a field that is attached to an instantiated model. For example: ModelField(model_field=MyModel()._meta.get_field('custom_field'))","title":"ModelField"},{"location":"api-guide/fields/#serializermethodfield","text":"This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. Signature : SerializerMethodField(method_name=None) method_name - The name of the method on the serializer to be called. If not included this defaults to get_ . The serializer method referred to by the method_name argument should accept a single argument (in addition to self ), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: from django.contrib.auth.models import User from django.utils.timezone import now from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): days_since_joined = serializers.SerializerMethodField() class Meta: model = User def get_days_since_joined(self, obj): return (now() - obj.date_joined).days","title":"SerializerMethodField"},{"location":"api-guide/fields/#custom-fields","text":"If you want to create a custom field, you'll need to subclass Field and then override either one or both of the .to_representation() and .to_internal_value() methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, date / time / datetime or None . They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using. The .to_representation() method is called to convert the initial datatype into a primitive, serializable datatype. The to_internal_value() method is called to restore a primitive datatype into its internal python representation. This method should raise a serializers.ValidationError if the data is invalid. Note that the WritableField class that was present in version 2.x no longer exists. You should subclass Field and override to_internal_value() if the field supports data input.","title":"Custom fields"},{"location":"api-guide/fields/#examples","text":"","title":"Examples"},{"location":"api-guide/fields/#a-basic-custom-field","text":"Let's look at an example of serializing a class that represents an RGB color value: class Color(object): \"\"\" A color represented in the RGB colorspace. \"\"\" def __init__(self, red, green, blue): assert(red >= 0 and green >= 0 and blue >= 0) assert(red < 256 and green < 256 and blue < 256) self.red, self.green, self.blue = red, green, blue class ColorField(serializers.Field): \"\"\" Color objects are serialized into 'rgb(#, #, #)' notation. \"\"\" def to_representation(self, value): return \"rgb(%d, %d, %d)\" % (value.red, value.green, value.blue) def to_internal_value(self, data): data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] return Color(red, green, blue) By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override .get_attribute() and/or .get_value() . As an example, let's create a field that can be used to represent the class name of the object being serialized: class ClassNameField(serializers.Field): def get_attribute(self, instance): # We pass the object instance onto `to_representation`, # not just the field attribute. return instance def to_representation(self, value): \"\"\" Serialize the value's class name. \"\"\" return value.__class__.__name__","title":"A Basic Custom Field"},{"location":"api-guide/fields/#raising-validation-errors","text":"Our ColorField class above currently does not perform any data validation. To indicate invalid data, we should raise a serializers.ValidationError , like so: def to_internal_value(self, data): if not isinstance(data, str): msg = 'Incorrect type. Expected a string, but got %s' raise ValidationError(msg % type(data).__name__) if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data): raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.') data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] if any([col > 255 or col < 0 for col in (red, green, blue)]): raise ValidationError('Value out of range. Must be between 0 and 255.') return Color(red, green, blue) The .fail() method is a shortcut for raising ValidationError that takes a message string from the error_messages dictionary. For example: default_error_messages = { 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}', 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.', 'out_of_range': 'Value out of range. Must be between 0 and 255.' } def to_internal_value(self, data): if not isinstance(data, str): self.fail('incorrect_type', input_type=type(data).__name__) if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data): self.fail('incorrect_format') data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] if any([col > 255 or col < 0 for col in (red, green, blue)]): self.fail('out_of_range') return Color(red, green, blue) This style keeps your error messages cleaner and more separated from your code, and should be preferred.","title":"Raising validation errors"},{"location":"api-guide/fields/#using-source","text":"Here we'll take an example of a flat DataPoint model with x_coordinate and y_coordinate attributes. class DataPoint(models.Model): label = models.CharField(max_length=50) x_coordinate = models.SmallIntegerField() y_coordinate = models.SmallIntegerField() Using a custom field and source='*' we can provide a nested representation of the coordinate pair: class CoordinateField(serializers.Field): def to_representation(self, value): ret = { \"x\": value.x_coordinate, \"y\": value.y_coordinate } return ret def to_internal_value(self, data): ret = { \"x_coordinate\": data[\"x\"], \"y_coordinate\": data[\"y\"], } return ret class DataPointSerializer(serializers.ModelSerializer): coordinates = CoordinateField(source='*') class Meta: model = DataPoint fields = ['label', 'coordinates'] Note that this example doesn't handle validation. Partly for that reason, in a real project, the coordinate nesting might be better handled with a nested serialiser using source='*' , with two IntegerField instances, each with their own source pointing to the relevant field. The key points from the example, though, are: to_representation is passed the entire DataPoint object and must map from that to the desired output. >>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2) >>> out_serializer = DataPointSerializer(instance) >>> out_serializer.data ReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})]) Unless our field is to be read-only, to_internal_value must map back to a dict suitable for updating our target object. With source='*' , the return from to_internal_value will update the root validated data dictionary, rather than a single key. >>> data = { ... \"label\": \"Second Example\", ... \"coordinates\": { ... \"x\": 3, ... \"y\": 4, ... } ... } >>> in_serializer = DataPointSerializer(data=data) >>> in_serializer.is_valid() True >>> in_serializer.validated_data OrderedDict([('label', 'Second Example'), ('y_coordinate', 4), ('x_coordinate', 3)]) For completeness lets do the same thing again but with the nested serialiser approach suggested above: class NestedCoordinateSerializer(serializers.Serializer): x = serializers.IntegerField(source='x_coordinate') y = serializers.IntegerField(source='y_coordinate') class DataPointSerializer(serializers.ModelSerializer): coordinates = NestedCoordinateSerializer(source='*') class Meta: model = DataPoint fields = ['label', 'coordinates'] Here the mapping between the target and source attribute pairs ( x and x_coordinate , y and y_coordinate ) is handled in the IntegerField declarations. It's our NestedCoordinateSerializer that takes source='*' . Our new DataPointSerializer exhibits the same behaviour as the custom field approach. Serialising: >>> out_serializer = DataPointSerializer(instance) >>> out_serializer.data ReturnDict([('label', 'testing'), ('coordinates', OrderedDict([('x', 1), ('y', 2)]))]) Deserialising: >>> in_serializer = DataPointSerializer(data=data) >>> in_serializer.is_valid() True >>> in_serializer.validated_data OrderedDict([('label', 'still testing'), ('x_coordinate', 3), ('y_coordinate', 4)]) But we also get the built-in validation for free: >>> invalid_data = { ... \"label\": \"still testing\", ... \"coordinates\": { ... \"x\": 'a', ... \"y\": 'b', ... } ... } >>> invalid_serializer = DataPointSerializer(data=invalid_data) >>> invalid_serializer.is_valid() False >>> invalid_serializer.errors ReturnDict([('coordinates', {'x': ['A valid integer is required.'], 'y': ['A valid integer is required.']})]) For this reason, the nested serialiser approach would be the first to try. You would use the custom field approach when the nested serialiser becomes infeasible or overly complex.","title":"Using source='*'"},{"location":"api-guide/fields/#third-party-packages","text":"The following third party packages are also available.","title":"Third party packages"},{"location":"api-guide/fields/#drf-compound-fields","text":"The drf-compound-fields package provides \"compound\" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the many=True option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.","title":"DRF Compound Fields"},{"location":"api-guide/fields/#drf-extra-fields","text":"The drf-extra-fields package provides extra serializer fields for REST framework, including Base64ImageField and PointField classes.","title":"DRF Extra Fields"},{"location":"api-guide/fields/#djangorestframework-recursive","text":"the djangorestframework-recursive package provides a RecursiveField for serializing and deserializing recursive structures","title":"djangorestframework-recursive"},{"location":"api-guide/fields/#django-rest-framework-gis","text":"The django-rest-framework-gis package provides geographic addons for django rest framework like a GeometryField field and a GeoJSON serializer.","title":"django-rest-framework-gis"},{"location":"api-guide/fields/#django-rest-framework-hstore","text":"The django-rest-framework-hstore package provides an HStoreField to support django-hstore DictionaryField model field.","title":"django-rest-framework-hstore"},{"location":"api-guide/filtering/","text":"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. \u2014 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: url('^purchases/(?P.+)/$', 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', None) 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 . Then add django_filters to Django's INSTALLED_APPS pip install django-filter 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 FilterSet s 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'] 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 MySQL 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. Pagination & 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 QuerySet s. 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.","title":"Filtering"},{"location":"api-guide/filtering/#filtering","text":"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. \u2014 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.","title":"Filtering"},{"location":"api-guide/filtering/#filtering-against-the-current-user","text":"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)","title":"Filtering against the current user"},{"location":"api-guide/filtering/#filtering-against-the-url","text":"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: url('^purchases/(?P.+)/$', 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)","title":"Filtering against the URL"},{"location":"api-guide/filtering/#filtering-against-query-parameters","text":"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', None) if username is not None: queryset = queryset.filter(purchaser__username=username) return queryset","title":"Filtering against query parameters"},{"location":"api-guide/filtering/#generic-filtering","text":"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.","title":"Generic Filtering"},{"location":"api-guide/filtering/#setting-filter-backends","text":"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]","title":"Setting filter backends"},{"location":"api-guide/filtering/#filtering-and-object-lookups","text":"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","title":"Filtering and object lookups"},{"location":"api-guide/filtering/#overriding-the-initial-queryset","text":"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()","title":"Overriding the initial queryset"},{"location":"api-guide/filtering/#api-guide","text":"","title":"API Guide"},{"location":"api-guide/filtering/#djangofilterbackend","text":"The django-filter library includes a DjangoFilterBackend class which supports highly customizable field filtering for REST framework. To use DjangoFilterBackend , first install django-filter . Then add django_filters to Django's INSTALLED_APPS pip install django-filter 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 FilterSet s in the django-filter documentation . It's also recommended that you read the section on DRF integration .","title":"DjangoFilterBackend"},{"location":"api-guide/filtering/#searchfilter","text":"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'] 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 MySQL 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 .","title":"SearchFilter"},{"location":"api-guide/filtering/#orderingfilter","text":"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","title":"OrderingFilter"},{"location":"api-guide/filtering/#specifying-which-fields-may-be-ordered-against","text":"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__'","title":"Specifying which fields may be ordered against"},{"location":"api-guide/filtering/#specifying-a-default-ordering","text":"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.","title":"Specifying a default ordering"},{"location":"api-guide/filtering/#custom-generic-filtering","text":"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.","title":"Custom generic filtering"},{"location":"api-guide/filtering/#example","text":"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.","title":"Example"},{"location":"api-guide/filtering/#customizing-the-interface","text":"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.","title":"Customizing the interface"},{"location":"api-guide/filtering/#pagination-schemas","text":"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.","title":"Pagination & schemas"},{"location":"api-guide/filtering/#third-party-packages","text":"The following third party packages provide additional filter implementations.","title":"Third party packages"},{"location":"api-guide/filtering/#django-rest-framework-filters-package","text":"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.","title":"Django REST framework filters package"},{"location":"api-guide/filtering/#django-rest-framework-full-word-search-filter","text":"The djangorestframework-word-filter developed as alternative to filters.SearchFilter which will search full word in text, or exact match.","title":"Django REST framework full word search filter"},{"location":"api-guide/filtering/#django-url-filter","text":"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 QuerySet s.","title":"Django URL Filter"},{"location":"api-guide/filtering/#drf-url-filters","text":"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.","title":"drf-url-filters"},{"location":"api-guide/format-suffixes/","text":"Format suffixes Section 6.2.1 does not say that content negotiation should be used all the time. \u2014 Roy Fielding, REST discuss mailing list A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation. Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf. format_suffix_patterns Signature : format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None) Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided. Arguments: urlpatterns : Required. A URL pattern list. suffix_required : Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to False , meaning that suffixes are optional by default. allowed : Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. Example: from rest_framework.urlpatterns import format_suffix_patterns from blog import views urlpatterns = [ url(r'^/$', views.apt_root), url(r'^comments/$', views.comment_list), url(r'^comments/(?P[0-9]+)/$', views.comment_detail) ] urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) When using format_suffix_patterns , you must make sure to add the 'format' keyword argument to the corresponding views. For example: @api_view(['GET', 'POST']) def comment_list(request, format=None): # do stuff... Or with class-based views: class CommentList(APIView): def get(self, request, format=None): # do stuff... def post(self, request, format=None): # do stuff... The name of the kwarg used may be modified by using the FORMAT_SUFFIX_KWARG setting. Also note that format_suffix_patterns does not support descending into include URL patterns. Using with i18n_patterns If using the i18n_patterns function provided by Django, as well as format_suffix_patterns you should make sure that the i18n_patterns function is applied as the final, or outermost function. For example: url patterns = [ \u2026 ] urlpatterns = i18n_patterns( format_suffix_patterns(urlpatterns, allowed=['json', 'html']) ) Query parameter formats An alternative to the format suffixes is to include the requested format in a query parameter. REST framework provides this option by default, and it is used in the browsable API to switch between differing available representations. To select a representation using its short format, use the format query parameter. For example: http://example.com/organizations/?format=csv . The name of this query parameter can be modified using the URL_FORMAT_OVERRIDE setting. Set the value to None to disable this behavior. Accept headers vs. format suffixes There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that HTTP Accept headers should always be used instead. It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators: \u201cThat's why I always prefer extensions. Neither choice has anything to do with REST.\u201d \u2014 Roy Fielding, REST discuss mailing list The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.","title":"Format suffixes"},{"location":"api-guide/format-suffixes/#format-suffixes","text":"Section 6.2.1 does not say that content negotiation should be used all the time. \u2014 Roy Fielding, REST discuss mailing list A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation. Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf.","title":"Format suffixes"},{"location":"api-guide/format-suffixes/#format_suffix_patterns","text":"Signature : format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None) Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided. Arguments: urlpatterns : Required. A URL pattern list. suffix_required : Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to False , meaning that suffixes are optional by default. allowed : Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. Example: from rest_framework.urlpatterns import format_suffix_patterns from blog import views urlpatterns = [ url(r'^/$', views.apt_root), url(r'^comments/$', views.comment_list), url(r'^comments/(?P[0-9]+)/$', views.comment_detail) ] urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) When using format_suffix_patterns , you must make sure to add the 'format' keyword argument to the corresponding views. For example: @api_view(['GET', 'POST']) def comment_list(request, format=None): # do stuff... Or with class-based views: class CommentList(APIView): def get(self, request, format=None): # do stuff... def post(self, request, format=None): # do stuff... The name of the kwarg used may be modified by using the FORMAT_SUFFIX_KWARG setting. Also note that format_suffix_patterns does not support descending into include URL patterns.","title":"format_suffix_patterns"},{"location":"api-guide/format-suffixes/#using-with-i18n_patterns","text":"If using the i18n_patterns function provided by Django, as well as format_suffix_patterns you should make sure that the i18n_patterns function is applied as the final, or outermost function. For example: url patterns = [ \u2026 ] urlpatterns = i18n_patterns( format_suffix_patterns(urlpatterns, allowed=['json', 'html']) )","title":"Using with i18n_patterns"},{"location":"api-guide/format-suffixes/#query-parameter-formats","text":"An alternative to the format suffixes is to include the requested format in a query parameter. REST framework provides this option by default, and it is used in the browsable API to switch between differing available representations. To select a representation using its short format, use the format query parameter. For example: http://example.com/organizations/?format=csv . The name of this query parameter can be modified using the URL_FORMAT_OVERRIDE setting. Set the value to None to disable this behavior.","title":"Query parameter formats"},{"location":"api-guide/format-suffixes/#accept-headers-vs-format-suffixes","text":"There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that HTTP Accept headers should always be used instead. It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators: \u201cThat's why I always prefer extensions. Neither choice has anything to do with REST.\u201d \u2014 Roy Fielding, REST discuss mailing list The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.","title":"Accept headers vs. format suffixes"},{"location":"api-guide/generic-views/","text":"Generic views Django\u2019s 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. \u2014 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: url(r'^/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) Note : These methods replace the old-style version 2.x pre_save , post_save , pre_delete and post_delete methods, which are no longer available. 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(object): \"\"\" 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 Framework bulk The django-rest-framework-bulk package implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests. 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.","title":"Generic views"},{"location":"api-guide/generic-views/#generic-views","text":"Django\u2019s 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. \u2014 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.","title":"Generic views"},{"location":"api-guide/generic-views/#examples","text":"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: url(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')","title":"Examples"},{"location":"api-guide/generic-views/#api-reference","text":"","title":"API Reference"},{"location":"api-guide/generic-views/#genericapiview","text":"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.","title":"GenericAPIView"},{"location":"api-guide/generic-views/#attributes","text":"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.","title":"Attributes"},{"location":"api-guide/generic-views/#methods","text":"Base methods :","title":"Methods"},{"location":"api-guide/generic-views/#get_querysetself","text":"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()","title":"get_queryset(self)"},{"location":"api-guide/generic-views/#get_objectself","text":"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.","title":"get_object(self)"},{"location":"api-guide/generic-views/#filter_querysetself-queryset","text":"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","title":"filter_queryset(self, queryset)"},{"location":"api-guide/generic-views/#get_serializer_classself","text":"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) Note : These methods replace the old-style version 2.x pre_save , post_save , pre_delete and post_delete methods, which are no longer available. 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.","title":"get_serializer_class(self)"},{"location":"api-guide/generic-views/#mixins","text":"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 .","title":"Mixins"},{"location":"api-guide/generic-views/#listmodelmixin","text":"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.","title":"ListModelMixin"},{"location":"api-guide/generic-views/#createmodelmixin","text":"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.","title":"CreateModelMixin"},{"location":"api-guide/generic-views/#retrievemodelmixin","text":"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 .","title":"RetrieveModelMixin"},{"location":"api-guide/generic-views/#updatemodelmixin","text":"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.","title":"UpdateModelMixin"},{"location":"api-guide/generic-views/#destroymodelmixin","text":"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 .","title":"DestroyModelMixin"},{"location":"api-guide/generic-views/#concrete-view-classes","text":"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 .","title":"Concrete View Classes"},{"location":"api-guide/generic-views/#createapiview","text":"Used for create-only endpoints. Provides a post method handler. Extends: GenericAPIView , CreateModelMixin","title":"CreateAPIView"},{"location":"api-guide/generic-views/#listapiview","text":"Used for read-only endpoints to represent a collection of model instances . Provides a get method handler. Extends: GenericAPIView , ListModelMixin","title":"ListAPIView"},{"location":"api-guide/generic-views/#retrieveapiview","text":"Used for read-only endpoints to represent a single model instance . Provides a get method handler. Extends: GenericAPIView , RetrieveModelMixin","title":"RetrieveAPIView"},{"location":"api-guide/generic-views/#destroyapiview","text":"Used for delete-only endpoints for a single model instance . Provides a delete method handler. Extends: GenericAPIView , DestroyModelMixin","title":"DestroyAPIView"},{"location":"api-guide/generic-views/#updateapiview","text":"Used for update-only endpoints for a single model instance . Provides put and patch method handlers. Extends: GenericAPIView , UpdateModelMixin","title":"UpdateAPIView"},{"location":"api-guide/generic-views/#listcreateapiview","text":"Used for read-write endpoints to represent a collection of model instances . Provides get and post method handlers. Extends: GenericAPIView , ListModelMixin , CreateModelMixin","title":"ListCreateAPIView"},{"location":"api-guide/generic-views/#retrieveupdateapiview","text":"Used for read or update endpoints to represent a single model instance . Provides get , put and patch method handlers. Extends: GenericAPIView , RetrieveModelMixin , UpdateModelMixin","title":"RetrieveUpdateAPIView"},{"location":"api-guide/generic-views/#retrievedestroyapiview","text":"Used for read or delete endpoints to represent a single model instance . Provides get and delete method handlers. Extends: GenericAPIView , RetrieveModelMixin , DestroyModelMixin","title":"RetrieveDestroyAPIView"},{"location":"api-guide/generic-views/#retrieveupdatedestroyapiview","text":"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","title":"RetrieveUpdateDestroyAPIView"},{"location":"api-guide/generic-views/#customizing-the-generic-views","text":"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.","title":"Customizing the generic views"},{"location":"api-guide/generic-views/#creating-custom-mixins","text":"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(object): \"\"\" 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.","title":"Creating custom mixins"},{"location":"api-guide/generic-views/#creating-custom-base-classes","text":"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.","title":"Creating custom base classes"},{"location":"api-guide/generic-views/#put-as-create","text":"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.","title":"PUT as create"},{"location":"api-guide/generic-views/#third-party-packages","text":"The following third party packages provide additional generic view implementations.","title":"Third party packages"},{"location":"api-guide/generic-views/#django-rest-framework-bulk","text":"The django-rest-framework-bulk package implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.","title":"Django REST Framework bulk"},{"location":"api-guide/generic-views/#django-rest-multiple-models","text":"Django Rest Multiple Models provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.","title":"Django Rest Multiple Models"},{"location":"api-guide/metadata/","text":"Metadata [The OPTIONS ] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. \u2014 RFC7231, Section 4.3.7. REST framework includes a configurable mechanism for determining how your API should respond to OPTIONS requests. This allows you to return API schema or other resource information. There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP OPTIONS requests, so we provide an ad-hoc style that returns some useful information. Here's an example response that demonstrates the information that is returned by default. HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json { \"name\": \"To Do List\", \"description\": \"List existing 'To Do' items, or create a new item.\", \"renders\": [ \"application/json\", \"text/html\" ], \"parses\": [ \"application/json\", \"application/x-www-form-urlencoded\", \"multipart/form-data\" ], \"actions\": { \"POST\": { \"note\": { \"type\": \"string\", \"required\": false, \"read_only\": false, \"label\": \"title\", \"max_length\": 100 } } } } Setting the metadata scheme You can set the metadata class globally using the 'DEFAULT_METADATA_CLASS' settings key: REST_FRAMEWORK = { 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata' } Or you can set the metadata class individually for a view: class APIRoot(APIView): metadata_class = APIRootMetadata def get(self, request, format=None): return Response({ ... }) The REST framework package only includes a single metadata class implementation, named SimpleMetadata . If you want to use an alternative style you'll need to implement a custom metadata class. Creating schema endpoints If you have specific requirements for creating schema endpoints that are accessed with regular GET requests, you might consider re-using the metadata API for doing so. For example, the following additional route could be used on a viewset to provide a linkable schema endpoint. @action(methods=['GET'], detail=False) def schema(self, request): meta = self.metadata_class() data = meta.determine_metadata(request, self) return Response(data) There are a couple of reasons that you might choose to take this approach, including that OPTIONS responses are not cacheable . Custom metadata classes If you want to provide a custom metadata class you should override BaseMetadata and implement the determine_metadata(self, request, view) method. Useful things that you might want to do could include returning schema information, using a format such as JSON schema , or returning debug information to admin users. Example The following class could be used to limit the information that is returned to OPTIONS requests. class MinimalMetadata(BaseMetadata): \"\"\" Don't include field and other information for `OPTIONS` requests. Just return the name and description. \"\"\" def determine_metadata(self, request, view): return { 'name': view.get_view_name(), 'description': view.get_view_description() } Then configure your settings to use this custom class: REST_FRAMEWORK = { 'DEFAULT_METADATA_CLASS': 'myproject.apps.core.MinimalMetadata' } Third party packages The following third party packages provide additional metadata implementations. DRF-schema-adapter drf-schema-adapter is a set of tools that makes it easier to provide schema information to frontend frameworks and libraries. It provides a metadata mixin as well as 2 metadata classes and several adapters suitable to generate json-schema as well as schema information readable by various libraries. You can also write your own adapter to work with your specific frontend. If you wish to do so, it also provides an exporter that can export those schema information to json files.","title":"Metadata"},{"location":"api-guide/metadata/#metadata","text":"[The OPTIONS ] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. \u2014 RFC7231, Section 4.3.7. REST framework includes a configurable mechanism for determining how your API should respond to OPTIONS requests. This allows you to return API schema or other resource information. There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP OPTIONS requests, so we provide an ad-hoc style that returns some useful information. Here's an example response that demonstrates the information that is returned by default. HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json { \"name\": \"To Do List\", \"description\": \"List existing 'To Do' items, or create a new item.\", \"renders\": [ \"application/json\", \"text/html\" ], \"parses\": [ \"application/json\", \"application/x-www-form-urlencoded\", \"multipart/form-data\" ], \"actions\": { \"POST\": { \"note\": { \"type\": \"string\", \"required\": false, \"read_only\": false, \"label\": \"title\", \"max_length\": 100 } } } }","title":"Metadata"},{"location":"api-guide/metadata/#setting-the-metadata-scheme","text":"You can set the metadata class globally using the 'DEFAULT_METADATA_CLASS' settings key: REST_FRAMEWORK = { 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata' } Or you can set the metadata class individually for a view: class APIRoot(APIView): metadata_class = APIRootMetadata def get(self, request, format=None): return Response({ ... }) The REST framework package only includes a single metadata class implementation, named SimpleMetadata . If you want to use an alternative style you'll need to implement a custom metadata class.","title":"Setting the metadata scheme"},{"location":"api-guide/metadata/#creating-schema-endpoints","text":"If you have specific requirements for creating schema endpoints that are accessed with regular GET requests, you might consider re-using the metadata API for doing so. For example, the following additional route could be used on a viewset to provide a linkable schema endpoint. @action(methods=['GET'], detail=False) def schema(self, request): meta = self.metadata_class() data = meta.determine_metadata(request, self) return Response(data) There are a couple of reasons that you might choose to take this approach, including that OPTIONS responses are not cacheable .","title":"Creating schema endpoints"},{"location":"api-guide/metadata/#custom-metadata-classes","text":"If you want to provide a custom metadata class you should override BaseMetadata and implement the determine_metadata(self, request, view) method. Useful things that you might want to do could include returning schema information, using a format such as JSON schema , or returning debug information to admin users.","title":"Custom metadata classes"},{"location":"api-guide/metadata/#example","text":"The following class could be used to limit the information that is returned to OPTIONS requests. class MinimalMetadata(BaseMetadata): \"\"\" Don't include field and other information for `OPTIONS` requests. Just return the name and description. \"\"\" def determine_metadata(self, request, view): return { 'name': view.get_view_name(), 'description': view.get_view_description() } Then configure your settings to use this custom class: REST_FRAMEWORK = { 'DEFAULT_METADATA_CLASS': 'myproject.apps.core.MinimalMetadata' }","title":"Example"},{"location":"api-guide/metadata/#third-party-packages","text":"The following third party packages provide additional metadata implementations.","title":"Third party packages"},{"location":"api-guide/metadata/#drf-schema-adapter","text":"drf-schema-adapter is a set of tools that makes it easier to provide schema information to frontend frameworks and libraries. It provides a metadata mixin as well as 2 metadata classes and several adapters suitable to generate json-schema as well as schema information readable by various libraries. You can also write your own adapter to work with your specific frontend. If you wish to do so, it also provides an exporter that can export those schema information to json files.","title":"DRF-schema-adapter"},{"location":"api-guide/pagination/","text":"Pagination Django provides a few classes that help you manage paginated data \u2013 that is, data that\u2019s split across several pages, with \u201cPrevious/Next\u201d links. \u2014 Django documentation REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data. The pagination API can support either: Pagination links that are provided as part of the content of the response. Pagination links that are included in response headers, such as Content-Range or Link . The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API. Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView , you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the mixins.ListModelMixin and generics.GenericAPIView classes for an example. Pagination can be turned off by setting the pagination class to None . Setting the pagination style The pagination style may be set globally, using the DEFAULT_PAGINATION_CLASS and PAGE_SIZE setting keys. For example, to use the built-in limit/offset pagination, you would do something like this: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 } Note that you need to set both the pagination class, and the page size that should be used. Both DEFAULT_PAGINATION_CLASS and PAGE_SIZE are None by default. You can also set the pagination class on an individual view by using the pagination_class attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis. Modifying the pagination style If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change. class LargeResultsSetPagination(PageNumberPagination): page_size = 1000 page_size_query_param = 'page_size' max_page_size = 10000 class StandardResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 You can then apply your new style to a view using the pagination_class attribute: class BillingRecordsView(generics.ListAPIView): queryset = Billing.objects.all() serializer_class = BillingRecordsSerializer pagination_class = LargeResultsSetPagination Or apply the style globally, using the DEFAULT_PAGINATION_CLASS settings key. For example: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination' } API Reference PageNumberPagination This pagination style accepts a single number page number in the request query parameters. Request : GET https://api.example.org/accounts/?page=4 Response : HTTP 200 OK { \"count\": 1023 \"next\": \"https://api.example.org/accounts/?page=5\", \"previous\": \"https://api.example.org/accounts/?page=3\", \"results\": [ \u2026 ] } Setup To enable the PageNumberPagination style globally, use the following configuration, and set the PAGE_SIZE as desired: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } On GenericAPIView subclasses you may also set the pagination_class attribute to select PageNumberPagination on a per-view basis. Configuration The PageNumberPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the PageNumberPagination class, and then enable your custom pagination class as above. django_paginator_class - The Django Paginator class to use. Default is django.core.paginator.Paginator , which should be fine for most use cases. page_size - A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key. page_query_param - A string value indicating the name of the query parameter to use for the pagination control. page_size_query_param - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to None , indicating that the client may not control the requested page size. max_page_size - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if page_size_query_param is also set. last_page_strings - A list or tuple of string values indicating values that may be used with the page_query_param to request the final page in the set. Defaults to ('last',) template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/numbers.html\" . LimitOffsetPagination This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a \"limit\" and an \"offset\" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the page_size in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items. Request : GET https://api.example.org/accounts/?limit=100&offset=400 Response : HTTP 200 OK { \"count\": 1023 \"next\": \"https://api.example.org/accounts/?limit=100&offset=500\", \"previous\": \"https://api.example.org/accounts/?limit=100&offset=300\", \"results\": [ \u2026 ] } Setup To enable the LimitOffsetPagination style globally, use the following configuration: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' } Optionally, you may also set a PAGE_SIZE key. If the PAGE_SIZE parameter is also used then the limit query parameter will be optional, and may be omitted by the client. On GenericAPIView subclasses you may also set the pagination_class attribute to select LimitOffsetPagination on a per-view basis. Configuration The LimitOffsetPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the LimitOffsetPagination class, and then enable your custom pagination class as above. default_limit - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the PAGE_SIZE settings key. limit_query_param - A string value indicating the name of the \"limit\" query parameter. Defaults to 'limit' . offset_query_param - A string value indicating the name of the \"offset\" query parameter. Defaults to 'offset' . max_limit - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to None . template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/numbers.html\" . CursorPagination The cursor-based pagination presents an opaque \"cursor\" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions. Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against. Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits: Provides a consistent pagination view. When used properly CursorPagination ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process. Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases. Details and limitations Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by \"-created\" . This assumes that there must be a 'created' timestamp field on the model instances, and will present a \"timeline\" style paginated view, with the most recently added items first. You can modify the ordering by overriding the 'ordering' attribute on the pagination class, or by using the OrderingFilter filter class together with CursorPagination . When used with OrderingFilter you should strongly consider restricting the fields that the user may order by. Proper usage of cursor pagination should have an ordering field that satisfies the following: Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation. Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart \"position plus offset\" style that allows it to properly support not-strictly-unique values as the ordering. Should be a non-nullable value that can be coerced to a string. Should not be a float. Precision errors easily lead to incorrect results. Hint: use decimals instead. (If you already have a float field and must paginate on that, an example CursorPagination subclass that uses decimals to limit precision is available here .) The field should have a database index. Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination. For more technical details on the implementation we use for cursor pagination, the \"Building cursors for the Disqus API\" blog post gives a good overview of the basic approach. Setup To enable the CursorPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', 'PAGE_SIZE': 100 } On GenericAPIView subclasses you may also set the pagination_class attribute to select CursorPagination on a per-view basis. Configuration The CursorPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the CursorPagination class, and then enable your custom pagination class as above. page_size = A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key. cursor_query_param = A string value indicating the name of the \"cursor\" query parameter. Defaults to 'cursor' . ordering = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: ordering = 'slug' . Defaults to -created . This value may also be overridden by using OrderingFilter on the view. template = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/previous_and_next.html\" . Custom pagination styles To create a custom pagination serializer class you should subclass pagination.BasePagination and override the paginate_queryset(self, queryset, request, view=None) and get_paginated_response(self, data) methods: The paginate_queryset method is passed the initial queryset and should return an iterable object that contains only the data in the requested page. The get_paginated_response method is passed the serialized page data and should return a Response instance. Note that the paginate_queryset method may set state on the pagination instance, that may later be used by the get_paginated_response method. Example Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so: class CustomPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'results': data }) We'd then need to setup the custom class in our configuration: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination', 'PAGE_SIZE': 100 } Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an OrderedDict when constructing the body of paginated responses, but this is optional. Using your custom pagination class To have your custom pagination class be used by default, use the DEFAULT_PAGINATION_CLASS setting: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination', 'PAGE_SIZE': 100 } API responses for list endpoints will now include a Link header, instead of including the pagination links as part of the body of the response, for example: A custom pagination style, using the 'Link' header' Pagination & schemas You can also make the pagination 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. HTML pagination controls By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The PageNumberPagination and LimitOffsetPagination classes display a list of page numbers with previous and next controls. The CursorPagination class displays a simpler style that only displays a previous and next control. Customizing the controls You can override the templates that render the HTML pagination controls. The two built-in styles are: rest_framework/pagination/numbers.html rest_framework/pagination/previous_and_next.html Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes. Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting template = None as an attribute on the class. You'll then need to configure your DEFAULT_PAGINATION_CLASS settings key to use your custom class as the default pagination style. Low-level API The low-level API for determining if a pagination class should display the controls or not is exposed as a display_page_controls attribute on the pagination instance. Custom pagination classes should be set to True in the paginate_queryset method if they require the HTML pagination controls to be displayed. The .to_html() and .get_html_context() methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered. Third party packages The following third party packages are also available. DRF-extensions The DRF-extensions package includes a PaginateByMaxMixin mixin class that allows your API clients to specify ?page_size=max to obtain the maximum allowed page size. drf-proxy-pagination The drf-proxy-pagination package includes a ProxyPagination class which allows to choose pagination class with a query parameter. link-header-pagination The django-rest-framework-link-header-pagination package includes a LinkHeaderPagination class which provides pagination via an HTTP Link header as described in Github's developer documentation .","title":"Pagination"},{"location":"api-guide/pagination/#pagination","text":"Django provides a few classes that help you manage paginated data \u2013 that is, data that\u2019s split across several pages, with \u201cPrevious/Next\u201d links. \u2014 Django documentation REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data. The pagination API can support either: Pagination links that are provided as part of the content of the response. Pagination links that are included in response headers, such as Content-Range or Link . The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API. Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView , you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the mixins.ListModelMixin and generics.GenericAPIView classes for an example. Pagination can be turned off by setting the pagination class to None .","title":"Pagination"},{"location":"api-guide/pagination/#setting-the-pagination-style","text":"The pagination style may be set globally, using the DEFAULT_PAGINATION_CLASS and PAGE_SIZE setting keys. For example, to use the built-in limit/offset pagination, you would do something like this: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 } Note that you need to set both the pagination class, and the page size that should be used. Both DEFAULT_PAGINATION_CLASS and PAGE_SIZE are None by default. You can also set the pagination class on an individual view by using the pagination_class attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis.","title":"Setting the pagination style"},{"location":"api-guide/pagination/#modifying-the-pagination-style","text":"If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change. class LargeResultsSetPagination(PageNumberPagination): page_size = 1000 page_size_query_param = 'page_size' max_page_size = 10000 class StandardResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 You can then apply your new style to a view using the pagination_class attribute: class BillingRecordsView(generics.ListAPIView): queryset = Billing.objects.all() serializer_class = BillingRecordsSerializer pagination_class = LargeResultsSetPagination Or apply the style globally, using the DEFAULT_PAGINATION_CLASS settings key. For example: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination' }","title":"Modifying the pagination style"},{"location":"api-guide/pagination/#api-reference","text":"","title":"API Reference"},{"location":"api-guide/pagination/#pagenumberpagination","text":"This pagination style accepts a single number page number in the request query parameters. Request : GET https://api.example.org/accounts/?page=4 Response : HTTP 200 OK { \"count\": 1023 \"next\": \"https://api.example.org/accounts/?page=5\", \"previous\": \"https://api.example.org/accounts/?page=3\", \"results\": [ \u2026 ] }","title":"PageNumberPagination"},{"location":"api-guide/pagination/#setup","text":"To enable the PageNumberPagination style globally, use the following configuration, and set the PAGE_SIZE as desired: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } On GenericAPIView subclasses you may also set the pagination_class attribute to select PageNumberPagination on a per-view basis.","title":"Setup"},{"location":"api-guide/pagination/#configuration","text":"The PageNumberPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the PageNumberPagination class, and then enable your custom pagination class as above. django_paginator_class - The Django Paginator class to use. Default is django.core.paginator.Paginator , which should be fine for most use cases. page_size - A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key. page_query_param - A string value indicating the name of the query parameter to use for the pagination control. page_size_query_param - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to None , indicating that the client may not control the requested page size. max_page_size - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if page_size_query_param is also set. last_page_strings - A list or tuple of string values indicating values that may be used with the page_query_param to request the final page in the set. Defaults to ('last',) template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/numbers.html\" .","title":"Configuration"},{"location":"api-guide/pagination/#limitoffsetpagination","text":"This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a \"limit\" and an \"offset\" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the page_size in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items. Request : GET https://api.example.org/accounts/?limit=100&offset=400 Response : HTTP 200 OK { \"count\": 1023 \"next\": \"https://api.example.org/accounts/?limit=100&offset=500\", \"previous\": \"https://api.example.org/accounts/?limit=100&offset=300\", \"results\": [ \u2026 ] }","title":"LimitOffsetPagination"},{"location":"api-guide/pagination/#setup_1","text":"To enable the LimitOffsetPagination style globally, use the following configuration: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' } Optionally, you may also set a PAGE_SIZE key. If the PAGE_SIZE parameter is also used then the limit query parameter will be optional, and may be omitted by the client. On GenericAPIView subclasses you may also set the pagination_class attribute to select LimitOffsetPagination on a per-view basis.","title":"Setup"},{"location":"api-guide/pagination/#configuration_1","text":"The LimitOffsetPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the LimitOffsetPagination class, and then enable your custom pagination class as above. default_limit - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the PAGE_SIZE settings key. limit_query_param - A string value indicating the name of the \"limit\" query parameter. Defaults to 'limit' . offset_query_param - A string value indicating the name of the \"offset\" query parameter. Defaults to 'offset' . max_limit - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to None . template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/numbers.html\" .","title":"Configuration"},{"location":"api-guide/pagination/#cursorpagination","text":"The cursor-based pagination presents an opaque \"cursor\" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions. Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against. Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits: Provides a consistent pagination view. When used properly CursorPagination ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process. Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases.","title":"CursorPagination"},{"location":"api-guide/pagination/#details-and-limitations","text":"Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by \"-created\" . This assumes that there must be a 'created' timestamp field on the model instances, and will present a \"timeline\" style paginated view, with the most recently added items first. You can modify the ordering by overriding the 'ordering' attribute on the pagination class, or by using the OrderingFilter filter class together with CursorPagination . When used with OrderingFilter you should strongly consider restricting the fields that the user may order by. Proper usage of cursor pagination should have an ordering field that satisfies the following: Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation. Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart \"position plus offset\" style that allows it to properly support not-strictly-unique values as the ordering. Should be a non-nullable value that can be coerced to a string. Should not be a float. Precision errors easily lead to incorrect results. Hint: use decimals instead. (If you already have a float field and must paginate on that, an example CursorPagination subclass that uses decimals to limit precision is available here .) The field should have a database index. Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination. For more technical details on the implementation we use for cursor pagination, the \"Building cursors for the Disqus API\" blog post gives a good overview of the basic approach.","title":"Details and limitations"},{"location":"api-guide/pagination/#setup_2","text":"To enable the CursorPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', 'PAGE_SIZE': 100 } On GenericAPIView subclasses you may also set the pagination_class attribute to select CursorPagination on a per-view basis.","title":"Setup"},{"location":"api-guide/pagination/#configuration_2","text":"The CursorPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the CursorPagination class, and then enable your custom pagination class as above. page_size = A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key. cursor_query_param = A string value indicating the name of the \"cursor\" query parameter. Defaults to 'cursor' . ordering = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: ordering = 'slug' . Defaults to -created . This value may also be overridden by using OrderingFilter on the view. template = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/previous_and_next.html\" .","title":"Configuration"},{"location":"api-guide/pagination/#custom-pagination-styles","text":"To create a custom pagination serializer class you should subclass pagination.BasePagination and override the paginate_queryset(self, queryset, request, view=None) and get_paginated_response(self, data) methods: The paginate_queryset method is passed the initial queryset and should return an iterable object that contains only the data in the requested page. The get_paginated_response method is passed the serialized page data and should return a Response instance. Note that the paginate_queryset method may set state on the pagination instance, that may later be used by the get_paginated_response method.","title":"Custom pagination styles"},{"location":"api-guide/pagination/#example","text":"Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so: class CustomPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'results': data }) We'd then need to setup the custom class in our configuration: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination', 'PAGE_SIZE': 100 } Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an OrderedDict when constructing the body of paginated responses, but this is optional.","title":"Example"},{"location":"api-guide/pagination/#using-your-custom-pagination-class","text":"To have your custom pagination class be used by default, use the DEFAULT_PAGINATION_CLASS setting: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination', 'PAGE_SIZE': 100 } API responses for list endpoints will now include a Link header, instead of including the pagination links as part of the body of the response, for example: A custom pagination style, using the 'Link' header'","title":"Using your custom pagination class"},{"location":"api-guide/pagination/#pagination-schemas","text":"You can also make the pagination 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.","title":"Pagination & schemas"},{"location":"api-guide/pagination/#html-pagination-controls","text":"By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The PageNumberPagination and LimitOffsetPagination classes display a list of page numbers with previous and next controls. The CursorPagination class displays a simpler style that only displays a previous and next control.","title":"HTML pagination controls"},{"location":"api-guide/pagination/#customizing-the-controls","text":"You can override the templates that render the HTML pagination controls. The two built-in styles are: rest_framework/pagination/numbers.html rest_framework/pagination/previous_and_next.html Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes. Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting template = None as an attribute on the class. You'll then need to configure your DEFAULT_PAGINATION_CLASS settings key to use your custom class as the default pagination style.","title":"Customizing the controls"},{"location":"api-guide/pagination/#low-level-api","text":"The low-level API for determining if a pagination class should display the controls or not is exposed as a display_page_controls attribute on the pagination instance. Custom pagination classes should be set to True in the paginate_queryset method if they require the HTML pagination controls to be displayed. The .to_html() and .get_html_context() methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered.","title":"Low-level API"},{"location":"api-guide/pagination/#third-party-packages","text":"The following third party packages are also available.","title":"Third party packages"},{"location":"api-guide/pagination/#drf-extensions","text":"The DRF-extensions package includes a PaginateByMaxMixin mixin class that allows your API clients to specify ?page_size=max to obtain the maximum allowed page size.","title":"DRF-extensions"},{"location":"api-guide/pagination/#drf-proxy-pagination","text":"The drf-proxy-pagination package includes a ProxyPagination class which allows to choose pagination class with a query parameter.","title":"drf-proxy-pagination"},{"location":"api-guide/pagination/#link-header-pagination","text":"The django-rest-framework-link-header-pagination package includes a LinkHeaderPagination class which provides pagination via an HTTP Link header as described in Github's developer documentation .","title":"link-header-pagination"},{"location":"api-guide/parsers/","text":"Parsers Machine interacting web services tend to use more structured formats for sending data than form-encoded, since they're sending more complex data than simple forms \u2014 Malcom Tredinnick, Django developers group REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts. How the parser is determined The set of valid parsers for a view is always defined as a list of classes. When request.data is accessed, REST framework will examine the Content-Type header on the incoming request, and determine which parser to use to parse the request content. Note : When developing client applications always remember to make sure you're setting the Content-Type header when sending data in an HTTP request. If you don't set the content type, most clients will default to using 'application/x-www-form-urlencoded' , which may not be what you wanted. As an example, if you are sending json encoded data using jQuery with the .ajax() method , you should make sure to include the contentType: 'application/json' setting. Setting the parsers The default set of parsers may be set globally, using the DEFAULT_PARSER_CLASSES setting. For example, the following settings would allow only requests with JSON content, instead of the default of JSON or form data. REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ] } You can also set the parsers used for an individual view, or viewset, using the APIView class-based views. from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): \"\"\" A view that can accept POST requests with JSON content. \"\"\" parser_classes = [JSONParser] def post(self, request, format=None): return Response({'received data': request.data}) Or, if you're using the @api_view decorator with function based views. from rest_framework.decorators import api_view from rest_framework.decorators import parser_classes from rest_framework.parsers import JSONParser @api_view(['POST']) @parser_classes([JSONParser]) def example_view(request, format=None): \"\"\" A view that can accept POST requests with JSON content. \"\"\" return Response({'received data': request.data}) API Reference JSONParser Parses JSON request content. .media_type : application/json FormParser Parses HTML form content. request.data will be populated with a QueryDict of data. You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data. .media_type : application/x-www-form-urlencoded MultiPartParser Parses multipart HTML form content, which supports file uploads. Both request.data will be populated with a QueryDict . You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data. .media_type : multipart/form-data FileUploadParser Parses raw file upload content. The request.data property will be a dictionary with a single key 'file' containing the uploaded file. If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg . .media_type : */* Notes: The FileUploadParser is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the MultiPartParser instead. Since this parser's media_type matches any content type, FileUploadParser should generally be the only parser set on an API view. FileUploadParser respects Django's standard FILE_UPLOAD_HANDLERS setting, and the request.upload_handlers attribute. See the Django documentation for more details. Basic usage example: # views.py class FileUploadView(views.APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) # urls.py urlpatterns = [ # ... url(r'^upload/(?P[^/]+)$', FileUploadView.as_view()) ] Custom parsers To implement a custom parser, you should override BaseParser , set the .media_type property, and implement the .parse(self, stream, media_type, parser_context) method. The method should return the data that will be used to populate the request.data property. The arguments passed to .parse() are: stream A stream-like object representing the body of the request. media_type Optional. If provided, this is the media type of the incoming request content. Depending on the request's Content-Type: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example \"text/plain; charset=utf-8\" . parser_context Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content. By default this will include the following keys: view , request , args , kwargs . Example The following is an example plaintext parser that will populate the request.data property with a string representing the body of the request. class PlainTextParser(BaseParser): \"\"\" Plain text parser. \"\"\" media_type = 'text/plain' def parse(self, stream, media_type=None, parser_context=None): \"\"\" Simply return a string representing the body of the request. \"\"\" return stream.read() 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', ], } 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. 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 .","title":"Parsers"},{"location":"api-guide/parsers/#parsers","text":"Machine interacting web services tend to use more structured formats for sending data than form-encoded, since they're sending more complex data than simple forms \u2014 Malcom Tredinnick, Django developers group REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.","title":"Parsers"},{"location":"api-guide/parsers/#how-the-parser-is-determined","text":"The set of valid parsers for a view is always defined as a list of classes. When request.data is accessed, REST framework will examine the Content-Type header on the incoming request, and determine which parser to use to parse the request content. Note : When developing client applications always remember to make sure you're setting the Content-Type header when sending data in an HTTP request. If you don't set the content type, most clients will default to using 'application/x-www-form-urlencoded' , which may not be what you wanted. As an example, if you are sending json encoded data using jQuery with the .ajax() method , you should make sure to include the contentType: 'application/json' setting.","title":"How the parser is determined"},{"location":"api-guide/parsers/#setting-the-parsers","text":"The default set of parsers may be set globally, using the DEFAULT_PARSER_CLASSES setting. For example, the following settings would allow only requests with JSON content, instead of the default of JSON or form data. REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ] } You can also set the parsers used for an individual view, or viewset, using the APIView class-based views. from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): \"\"\" A view that can accept POST requests with JSON content. \"\"\" parser_classes = [JSONParser] def post(self, request, format=None): return Response({'received data': request.data}) Or, if you're using the @api_view decorator with function based views. from rest_framework.decorators import api_view from rest_framework.decorators import parser_classes from rest_framework.parsers import JSONParser @api_view(['POST']) @parser_classes([JSONParser]) def example_view(request, format=None): \"\"\" A view that can accept POST requests with JSON content. \"\"\" return Response({'received data': request.data})","title":"Setting the parsers"},{"location":"api-guide/parsers/#api-reference","text":"","title":"API Reference"},{"location":"api-guide/parsers/#jsonparser","text":"Parses JSON request content. .media_type : application/json","title":"JSONParser"},{"location":"api-guide/parsers/#formparser","text":"Parses HTML form content. request.data will be populated with a QueryDict of data. You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data. .media_type : application/x-www-form-urlencoded","title":"FormParser"},{"location":"api-guide/parsers/#multipartparser","text":"Parses multipart HTML form content, which supports file uploads. Both request.data will be populated with a QueryDict . You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data. .media_type : multipart/form-data","title":"MultiPartParser"},{"location":"api-guide/parsers/#fileuploadparser","text":"Parses raw file upload content. The request.data property will be a dictionary with a single key 'file' containing the uploaded file. If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg . .media_type : */*","title":"FileUploadParser"},{"location":"api-guide/parsers/#notes","text":"The FileUploadParser is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the MultiPartParser instead. Since this parser's media_type matches any content type, FileUploadParser should generally be the only parser set on an API view. FileUploadParser respects Django's standard FILE_UPLOAD_HANDLERS setting, and the request.upload_handlers attribute. See the Django documentation for more details.","title":"Notes:"},{"location":"api-guide/parsers/#basic-usage-example","text":"# views.py class FileUploadView(views.APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) # urls.py urlpatterns = [ # ... url(r'^upload/(?P[^/]+)$', FileUploadView.as_view()) ]","title":"Basic usage example:"},{"location":"api-guide/parsers/#custom-parsers","text":"To implement a custom parser, you should override BaseParser , set the .media_type property, and implement the .parse(self, stream, media_type, parser_context) method. The method should return the data that will be used to populate the request.data property. The arguments passed to .parse() are:","title":"Custom parsers"},{"location":"api-guide/parsers/#stream","text":"A stream-like object representing the body of the request.","title":"stream"},{"location":"api-guide/parsers/#media_type","text":"Optional. If provided, this is the media type of the incoming request content. Depending on the request's Content-Type: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example \"text/plain; charset=utf-8\" .","title":"media_type"},{"location":"api-guide/parsers/#parser_context","text":"Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content. By default this will include the following keys: view , request , args , kwargs .","title":"parser_context"},{"location":"api-guide/parsers/#example","text":"The following is an example plaintext parser that will populate the request.data property with a string representing the body of the request. class PlainTextParser(BaseParser): \"\"\" Plain text parser. \"\"\" media_type = 'text/plain' def parse(self, stream, media_type=None, parser_context=None): \"\"\" Simply return a string representing the body of the request. \"\"\" return stream.read()","title":"Example"},{"location":"api-guide/parsers/#third-party-packages","text":"The following third party packages are also available.","title":"Third party packages"},{"location":"api-guide/parsers/#yaml","text":"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.","title":"YAML"},{"location":"api-guide/parsers/#installation-configuration","text":"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', ], }","title":"Installation & configuration"},{"location":"api-guide/parsers/#xml","text":"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.","title":"XML"},{"location":"api-guide/parsers/#installation-configuration_1","text":"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', ], }","title":"Installation & configuration"},{"location":"api-guide/parsers/#messagepack","text":"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.","title":"MessagePack"},{"location":"api-guide/parsers/#camelcase-json","text":"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 .","title":"CamelCase JSON"},{"location":"api-guide/permissions/","text":"Permissions Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization. \u2014 Apple Developer Documentation Together with authentication and throttling , permissions determine whether a request should be granted or denied access. Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the request.user and request.auth properties to determine if the incoming request should be permitted. Permissions are used to grant or deny access for different classes of users to different parts of the API. The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework. A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the IsAuthenticatedOrReadOnly class in REST framework. How permissions are determined Permissions in REST framework are always defined as a list of permission classes. Before running the main body of the view each permission in the list is checked. If any permission check fails an exceptions.PermissionDenied or exceptions.NotAuthenticated exception will be raised, and the main body of the view will not run. When the permissions checks fail either a \"403 Forbidden\" or a \"401 Unauthorized\" response will be returned, according to the following rules: The request was successfully authenticated, but permission was denied. \u2014 An HTTP 403 Forbidden response will be returned. The request was not successfully authenticated, and the highest priority authentication class does not use WWW-Authenticate headers. \u2014 An HTTP 403 Forbidden response will be returned. The request was not successfully authenticated, and the highest priority authentication class does use WWW-Authenticate headers. \u2014 An HTTP 401 Unauthorized response, with an appropriate WWW-Authenticate header will be returned. Object level permissions REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance. Object level permissions are run by REST framework's generic views when .get_object() is called. As with view level permissions, an exceptions.PermissionDenied exception will be raised if the user is not allowed to act on the given object. If you're writing your own views and want to enforce object level permissions, or if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object. This will either raise a PermissionDenied or NotAuthenticated exception, or simply return if the view has the appropriate permissions. For example: def get_object(self): obj = get_object_or_404(self.get_queryset(), pk=self.kwargs[\"pk\"]) self.check_object_permissions(self.request, obj) return obj Note : With the exception of DjangoObjectPermissions , the provided permission classes in rest_framework.permissions do not implement the methods necessary to check object permissions. If you wish to use the provided permission classes in order to check object permissions, you must subclass them and implement the has_object_permission() method described in the Custom permissions section (below). Limitations of object level permissions For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects. Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view. Setting the permission policy The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting. For example. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } If not specified, this setting defaults to allowing unrestricted access: 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] You can also set the authentication policy on a per-view, or per-viewset basis, using the APIView class-based views. from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) Or, if you're using the @api_view decorator with function based views. from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response @api_view(['GET']) @permission_classes([IsAuthenticated]) def example_view(request, format=None): content = { 'status': 'request was permitted' } return Response(content) Note: when you set new permission classes through class attribute or decorators you're telling the view to ignore the default list set over the settings.py file. Provided they inherit from rest_framework.permissions.BasePermission , permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written: from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS from rest_framework.response import Response from rest_framework.views import APIView class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS class ExampleView(APIView): permission_classes = [IsAuthenticated|ReadOnly] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) Note: it supports & (and), | (or) and ~ (not). API Reference AllowAny The AllowAny permission class will allow unrestricted access, regardless of if the request was authenticated or unauthenticated . This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit. IsAuthenticated The IsAuthenticated permission class will deny permission to any unauthenticated user, and allow permission otherwise. This permission is suitable if you want your API to only be accessible to registered users. IsAdminUser The IsAdminUser permission class will deny permission to any user, unless user.is_staff is True in which case permission will be allowed. This permission is suitable if you want your API to only be accessible to a subset of trusted administrators. IsAuthenticatedOrReadOnly The IsAuthenticatedOrReadOnly will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the \"safe\" methods; GET , HEAD or OPTIONS . This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users. DjangoModelPermissions This permission class ties into Django's standard django.contrib.auth model permissions . This permission must only be applied to views that have a .queryset property set. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned. POST requests require the user to have the add permission on the model. PUT and PATCH requests require the user to have the change permission on the model. DELETE requests require the user to have the delete permission on the model. The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a view model permission for GET requests. To use custom model permissions, override DjangoModelPermissions and set the .perms_map property. Refer to the source code for details. Using with views that do not include a queryset attribute. If you're using this permission with a view that uses an overridden get_queryset() method there may not be a queryset attribute on the view. In this case we suggest also marking the view with a sentinel queryset, so that this class can determine the required permissions. For example: queryset = User.objects.none() # Required for DjangoModelPermissions DjangoModelPermissionsOrAnonReadOnly Similar to DjangoModelPermissions , but also allows unauthenticated users to have read-only access to the API. DjangoObjectPermissions This permission class ties into Django's standard object permissions framework that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as django-guardian . As with DjangoModelPermissions , this permission must only be applied to views that have a .queryset property or .get_queryset() method. Authorization will only be granted if the user is authenticated and has the relevant per-object permissions and relevant model permissions assigned. POST requests require the user to have the add permission on the model instance. PUT and PATCH requests require the user to have the change permission on the model instance. DELETE requests require the user to have the delete permission on the model instance. Note that DjangoObjectPermissions does not require the django-guardian package, and should support other object-level backends equally well. As with DjangoModelPermissions you can use custom model permissions by overriding DjangoObjectPermissions and setting the .perms_map property. Refer to the source code for details. Note : If you need object level view permissions for GET , HEAD and OPTIONS requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the DjangoObjectPermissionsFilter class provided by the djangorestframework-guardian package . It ensures that list endpoints only return results including objects for which the user has appropriate view permissions. Custom permissions To implement a custom permission, override BasePermission and implement either, or both, of the following methods: .has_permission(self, request, view) .has_object_permission(self, request, view, obj) The methods should return True if the request should be granted access, and False otherwise. If you need to test if a request is a read operation or a write operation, you should check the request method against the constant SAFE_METHODS , which is a tuple containing 'GET' , 'OPTIONS' and 'HEAD' . For example: if request.method in permissions.SAFE_METHODS: # Check permissions for read-only request else: # Check permissions for write request Note : The instance-level has_object_permission method will only be called if the view-level has_permission checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call .check_object_permissions(request, obj) . If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising PermissionDenied on failure.) Custom permissions will raise a PermissionDenied exception if the test fails. To change the error message associated with the exception, implement a message attribute directly on your custom permission. Otherwise the default_detail attribute from PermissionDenied will be used. from rest_framework import permissions class CustomerAccessPermission(permissions.BasePermission): message = 'Adding customers not allowed.' def has_permission(self, request, view): ... Examples The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted. from rest_framework import permissions class BlacklistPermission(permissions.BasePermission): \"\"\" Global permission check for blacklisted IPs. \"\"\" def has_permission(self, request, view): ip_addr = request.META['REMOTE_ADDR'] blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists() return not blacklisted As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example: class IsOwnerOrReadOnly(permissions.BasePermission): \"\"\" Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. \"\"\" def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Instance must have an attribute named `owner`. return obj.owner == request.user Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling self.check_object_permissions(request, obj) from the view once you have the object instance. This call will raise an appropriate APIException if any object-level permission checks fail, and will otherwise simply return. Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details. Third party packages The following third party packages are also available. DRF - Access Policy The Django REST - Access Policy package provides a way to define complex access rules in declarative policy classes that are attached to view sets or function-based views. The policies are defined in JSON in a format similar to AWS' Identity & Access Management policies. Composed Permissions The Composed Permissions package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components. REST Condition The REST Condition package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators. DRY Rest Permissions The DRY Rest Permissions package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user. Django Rest Framework Roles The Django Rest Framework Roles package makes it easier to parameterize your API over multiple types of users. Django REST Framework API Key The Django REST Framework API Key package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. machines ) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin. Django Rest Framework Role Filters The Django Rest Framework Role Filters package provides simple filtering over multiple types of roles.","title":"Permissions"},{"location":"api-guide/permissions/#permissions","text":"Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization. \u2014 Apple Developer Documentation Together with authentication and throttling , permissions determine whether a request should be granted or denied access. Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the request.user and request.auth properties to determine if the incoming request should be permitted. Permissions are used to grant or deny access for different classes of users to different parts of the API. The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework. A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the IsAuthenticatedOrReadOnly class in REST framework.","title":"Permissions"},{"location":"api-guide/permissions/#how-permissions-are-determined","text":"Permissions in REST framework are always defined as a list of permission classes. Before running the main body of the view each permission in the list is checked. If any permission check fails an exceptions.PermissionDenied or exceptions.NotAuthenticated exception will be raised, and the main body of the view will not run. When the permissions checks fail either a \"403 Forbidden\" or a \"401 Unauthorized\" response will be returned, according to the following rules: The request was successfully authenticated, but permission was denied. \u2014 An HTTP 403 Forbidden response will be returned. The request was not successfully authenticated, and the highest priority authentication class does not use WWW-Authenticate headers. \u2014 An HTTP 403 Forbidden response will be returned. The request was not successfully authenticated, and the highest priority authentication class does use WWW-Authenticate headers. \u2014 An HTTP 401 Unauthorized response, with an appropriate WWW-Authenticate header will be returned.","title":"How permissions are determined"},{"location":"api-guide/permissions/#object-level-permissions","text":"REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance. Object level permissions are run by REST framework's generic views when .get_object() is called. As with view level permissions, an exceptions.PermissionDenied exception will be raised if the user is not allowed to act on the given object. If you're writing your own views and want to enforce object level permissions, or if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object. This will either raise a PermissionDenied or NotAuthenticated exception, or simply return if the view has the appropriate permissions. For example: def get_object(self): obj = get_object_or_404(self.get_queryset(), pk=self.kwargs[\"pk\"]) self.check_object_permissions(self.request, obj) return obj Note : With the exception of DjangoObjectPermissions , the provided permission classes in rest_framework.permissions do not implement the methods necessary to check object permissions. If you wish to use the provided permission classes in order to check object permissions, you must subclass them and implement the has_object_permission() method described in the Custom permissions section (below).","title":"Object level permissions"},{"location":"api-guide/permissions/#limitations-of-object-level-permissions","text":"For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects. Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view.","title":"Limitations of object level permissions"},{"location":"api-guide/permissions/#setting-the-permission-policy","text":"The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting. For example. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } If not specified, this setting defaults to allowing unrestricted access: 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] You can also set the authentication policy on a per-view, or per-viewset basis, using the APIView class-based views. from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) Or, if you're using the @api_view decorator with function based views. from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response @api_view(['GET']) @permission_classes([IsAuthenticated]) def example_view(request, format=None): content = { 'status': 'request was permitted' } return Response(content) Note: when you set new permission classes through class attribute or decorators you're telling the view to ignore the default list set over the settings.py file. Provided they inherit from rest_framework.permissions.BasePermission , permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written: from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS from rest_framework.response import Response from rest_framework.views import APIView class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS class ExampleView(APIView): permission_classes = [IsAuthenticated|ReadOnly] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) Note: it supports & (and), | (or) and ~ (not).","title":"Setting the permission policy"},{"location":"api-guide/permissions/#api-reference","text":"","title":"API Reference"},{"location":"api-guide/permissions/#allowany","text":"The AllowAny permission class will allow unrestricted access, regardless of if the request was authenticated or unauthenticated . This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.","title":"AllowAny"},{"location":"api-guide/permissions/#isauthenticated","text":"The IsAuthenticated permission class will deny permission to any unauthenticated user, and allow permission otherwise. This permission is suitable if you want your API to only be accessible to registered users.","title":"IsAuthenticated"},{"location":"api-guide/permissions/#isadminuser","text":"The IsAdminUser permission class will deny permission to any user, unless user.is_staff is True in which case permission will be allowed. This permission is suitable if you want your API to only be accessible to a subset of trusted administrators.","title":"IsAdminUser"},{"location":"api-guide/permissions/#isauthenticatedorreadonly","text":"The IsAuthenticatedOrReadOnly will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the \"safe\" methods; GET , HEAD or OPTIONS . This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.","title":"IsAuthenticatedOrReadOnly"},{"location":"api-guide/permissions/#djangomodelpermissions","text":"This permission class ties into Django's standard django.contrib.auth model permissions . This permission must only be applied to views that have a .queryset property set. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned. POST requests require the user to have the add permission on the model. PUT and PATCH requests require the user to have the change permission on the model. DELETE requests require the user to have the delete permission on the model. The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a view model permission for GET requests. To use custom model permissions, override DjangoModelPermissions and set the .perms_map property. Refer to the source code for details.","title":"DjangoModelPermissions"},{"location":"api-guide/permissions/#using-with-views-that-do-not-include-a-queryset-attribute","text":"If you're using this permission with a view that uses an overridden get_queryset() method there may not be a queryset attribute on the view. In this case we suggest also marking the view with a sentinel queryset, so that this class can determine the required permissions. For example: queryset = User.objects.none() # Required for DjangoModelPermissions","title":"Using with views that do not include a queryset attribute."},{"location":"api-guide/permissions/#djangomodelpermissionsoranonreadonly","text":"Similar to DjangoModelPermissions , but also allows unauthenticated users to have read-only access to the API.","title":"DjangoModelPermissionsOrAnonReadOnly"},{"location":"api-guide/permissions/#djangoobjectpermissions","text":"This permission class ties into Django's standard object permissions framework that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as django-guardian . As with DjangoModelPermissions , this permission must only be applied to views that have a .queryset property or .get_queryset() method. Authorization will only be granted if the user is authenticated and has the relevant per-object permissions and relevant model permissions assigned. POST requests require the user to have the add permission on the model instance. PUT and PATCH requests require the user to have the change permission on the model instance. DELETE requests require the user to have the delete permission on the model instance. Note that DjangoObjectPermissions does not require the django-guardian package, and should support other object-level backends equally well. As with DjangoModelPermissions you can use custom model permissions by overriding DjangoObjectPermissions and setting the .perms_map property. Refer to the source code for details. Note : If you need object level view permissions for GET , HEAD and OPTIONS requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the DjangoObjectPermissionsFilter class provided by the djangorestframework-guardian package . It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.","title":"DjangoObjectPermissions"},{"location":"api-guide/permissions/#custom-permissions","text":"To implement a custom permission, override BasePermission and implement either, or both, of the following methods: .has_permission(self, request, view) .has_object_permission(self, request, view, obj) The methods should return True if the request should be granted access, and False otherwise. If you need to test if a request is a read operation or a write operation, you should check the request method against the constant SAFE_METHODS , which is a tuple containing 'GET' , 'OPTIONS' and 'HEAD' . For example: if request.method in permissions.SAFE_METHODS: # Check permissions for read-only request else: # Check permissions for write request Note : The instance-level has_object_permission method will only be called if the view-level has_permission checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call .check_object_permissions(request, obj) . If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising PermissionDenied on failure.) Custom permissions will raise a PermissionDenied exception if the test fails. To change the error message associated with the exception, implement a message attribute directly on your custom permission. Otherwise the default_detail attribute from PermissionDenied will be used. from rest_framework import permissions class CustomerAccessPermission(permissions.BasePermission): message = 'Adding customers not allowed.' def has_permission(self, request, view): ...","title":"Custom permissions"},{"location":"api-guide/permissions/#examples","text":"The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted. from rest_framework import permissions class BlacklistPermission(permissions.BasePermission): \"\"\" Global permission check for blacklisted IPs. \"\"\" def has_permission(self, request, view): ip_addr = request.META['REMOTE_ADDR'] blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists() return not blacklisted As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example: class IsOwnerOrReadOnly(permissions.BasePermission): \"\"\" Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. \"\"\" def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Instance must have an attribute named `owner`. return obj.owner == request.user Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling self.check_object_permissions(request, obj) from the view once you have the object instance. This call will raise an appropriate APIException if any object-level permission checks fail, and will otherwise simply return. Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details.","title":"Examples"},{"location":"api-guide/permissions/#third-party-packages","text":"The following third party packages are also available.","title":"Third party packages"},{"location":"api-guide/permissions/#drf-access-policy","text":"The Django REST - Access Policy package provides a way to define complex access rules in declarative policy classes that are attached to view sets or function-based views. The policies are defined in JSON in a format similar to AWS' Identity & Access Management policies.","title":"DRF - Access Policy"},{"location":"api-guide/permissions/#composed-permissions","text":"The Composed Permissions package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.","title":"Composed Permissions"},{"location":"api-guide/permissions/#rest-condition","text":"The REST Condition package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.","title":"REST Condition"},{"location":"api-guide/permissions/#dry-rest-permissions","text":"The DRY Rest Permissions package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user.","title":"DRY Rest Permissions"},{"location":"api-guide/permissions/#django-rest-framework-roles","text":"The Django Rest Framework Roles package makes it easier to parameterize your API over multiple types of users.","title":"Django Rest Framework Roles"},{"location":"api-guide/permissions/#django-rest-framework-api-key","text":"The Django REST Framework API Key package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. machines ) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.","title":"Django REST Framework API Key"},{"location":"api-guide/permissions/#django-rest-framework-role-filters","text":"The Django Rest Framework Role Filters package provides simple filtering over multiple types of roles.","title":"Django Rest Framework Role Filters"},{"location":"api-guide/relations/","text":"Serializer relations Data structures, not algorithms, are central to programming. \u2014 Rob Pike Relational fields are used to represent model relationships. They can be applied to ForeignKey , ManyToManyField and OneToOneField relationships, as well as to reverse relationships, and custom relationships such as GenericForeignKey . Note: The relational fields are declared in relations.py , but by convention you should import them from the serializers module, using from rest_framework import serializers and refer to fields as serializers. . Inspecting relationships. When using the ModelSerializer class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style. To do so, open the Django shell, using python manage.py shell , then import the serializer class, instantiate it, and print the object representation\u2026 >>> from myapp.serializers import AccountSerializer >>> serializer = AccountSerializer() >>> print(repr(serializer)) AccountSerializer(): id = IntegerField(label='ID', read_only=True) name = CharField(allow_blank=True, max_length=100, required=False) owner = PrimaryKeyRelatedField(queryset=User.objects.all()) API Reference In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album. class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Meta: unique_together = ['album', 'order'] ordering = ['order'] def __str__(self): return '%d: %s' % (self.order, self.title) StringRelatedField StringRelatedField may be used to represent the target of the relationship using its __str__ method. For example, the following serializer. class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.StringRelatedField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to the following representation. { 'album_name': 'Things We Lost In The Fire', 'artist': 'Low', 'tracks': [ '1: Sunflower', '2: Whitetail', '3: Dinosaur Act', ... ] } This field is read only. Arguments : many - If applied to a to-many relationship, you should set this argument to True . PrimaryKeyRelatedField PrimaryKeyRelatedField may be used to represent the target of the relationship using its primary key. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a representation like this: { 'album_name': 'Undun', 'artist': 'The Roots', 'tracks': [ 89, 90, 91, ... ] } By default this field is read-write, although you can change this behavior using the read_only flag. Arguments : queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True . allow_null - If set to True , the field will accept values of None or the empty string for nullable relationships. Defaults to False . pk_field - Set to a field to control serialization/deserialization of the primary key's value. For example, pk_field=UUIDField(format='hex') would serialize a UUID primary key into its compact hex representation. HyperlinkedRelatedField HyperlinkedRelatedField may be used to represent the target of the relationship using a hyperlink. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='track-detail' ) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a representation like this: { 'album_name': 'Graceland', 'artist': 'Paul Simon', 'tracks': [ 'http://www.example.com/api/tracks/45/', 'http://www.example.com/api/tracks/46/', 'http://www.example.com/api/tracks/47/', ... ] } By default this field is read-write, although you can change this behavior using the read_only flag. Note : This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the lookup_field and lookup_url_kwarg arguments. This is suitable for URLs that contain a single primary key or slug argument as part of the URL. If you require more complex hyperlinked representation you'll need to customize the field, as described in the custom hyperlinked fields section, below. Arguments : view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format -detail . required . queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True . allow_null - If set to True , the field will accept values of None or the empty string for nullable relationships. Defaults to False . lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk' . lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field . format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument. SlugRelatedField SlugRelatedField may be used to represent the target of the relationship using a field on the target. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.SlugRelatedField( many=True, read_only=True, slug_field='title' ) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a representation like this: { 'album_name': 'Dear John', 'artist': 'Loney Dear', 'tracks': [ 'Airport Surroundings', 'Everything Turns to You', 'I Was Only Going Out', ... ] } By default this field is read-write, although you can change this behavior using the read_only flag. When using SlugRelatedField as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with unique=True . Arguments : slug_field - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, username . required queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True . allow_null - If set to True , the field will accept values of None or the empty string for nullable relationships. Defaults to False . HyperlinkedIdentityField This field can be applied as an identity relationship, such as the 'url' field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: class AlbumSerializer(serializers.HyperlinkedModelSerializer): track_listing = serializers.HyperlinkedIdentityField(view_name='track-list') class Meta: model = Album fields = ['album_name', 'artist', 'track_listing'] Would serialize to a representation like this: { 'album_name': 'The Eraser', 'artist': 'Thom Yorke', 'track_listing': 'http://www.example.com/api/track_list/12/', } This field is always read-only. Arguments : view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format -detail . required . lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk' . lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field . format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument. Nested relationships Nested relationships can be expressed by using serializers as fields. If the field is used to represent a to-many relationship, you should add the many=True flag to the serializer field. Example For example, the following serializer: class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a nested representation like this: >>> album = Album.objects.create(album_name=\"The Grey Album\", artist='Danger Mouse') >>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245) >>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264) >>> Track.objects.create(album=album, order=3, title='Encore', duration=159) >>> serializer = AlbumSerializer(instance=album) >>> serializer.data { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ... ], } Writable nested serializers By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create create() and/or update() methods in order to explicitly specify how the child relationships should be saved. class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] def create(self, validated_data): tracks_data = validated_data.pop('tracks') album = Album.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(album=album, **track_data) return album >>> data = { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ], } >>> serializer = AlbumSerializer(data=data) >>> serializer.is_valid() True >>> serializer.save() Custom relational fields In rare cases where none of the existing relational styles fit the representation you need, you can implement a completely custom relational field, that describes exactly how the output representation should be generated from the model instance. To implement a custom relational field, you should override RelatedField , and implement the .to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance. If you want to implement a read-write relational field, you must also implement the .to_internal_value(self, data) method. To provide a dynamic queryset based on the context , you can also override .get_queryset(self) instead of specifying .queryset on the class or when initializing the field. Example For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration. import time class TrackListingField(serializers.RelatedField): def to_representation(self, value): duration = time.strftime('%M:%S', time.gmtime(value.duration)) return 'Track %d: %s (%s)' % (value.order, value.name, duration) class AlbumSerializer(serializers.ModelSerializer): tracks = TrackListingField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] This custom field would then serialize to the following representation. { 'album_name': 'Sometimes I Wish We Were an Eagle', 'artist': 'Bill Callahan', 'tracks': [ 'Track 1: Jim Cain (04:39)', 'Track 2: Eid Ma Clack Shaw (04:19)', 'Track 3: The Wind and the Dove (04:34)', ... ] } Custom hyperlinked fields In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field. You can achieve this by overriding HyperlinkedRelatedField . There are two methods that may be overridden: get_url(self, obj, view_name, request, format) The get_url method is used to map the object instance to its URL representation. May raise a NoReverseMatch if the view_name and lookup_field attributes are not configured to correctly match the URL conf. get_object(self, view_name, view_args, view_kwargs) If you want to support a writable hyperlinked field then you'll also want to override get_object , in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method. The return value of this method should the object that corresponds to the matched URL conf arguments. May raise an ObjectDoesNotExist exception. Example Say we have a URL for a customer object that takes two keyword arguments, like so: /api//customers// This cannot be represented with the default implementation, which accepts only a single lookup field. In this case we'd need to override HyperlinkedRelatedField to get the behavior we want: from rest_framework import serializers from rest_framework.reverse import reverse class CustomerHyperlink(serializers.HyperlinkedRelatedField): # We define these as class attributes, so we don't need to pass them as arguments. view_name = 'customer-detail' queryset = Customer.objects.all() def get_url(self, obj, view_name, request, format): url_kwargs = { 'organization_slug': obj.organization.slug, 'customer_pk': obj.pk } return reverse(view_name, kwargs=url_kwargs, request=request, format=format) def get_object(self, view_name, view_args, view_kwargs): lookup_kwargs = { 'organization__slug': view_kwargs['organization_slug'], 'pk': view_kwargs['customer_pk'] } return self.get_queryset().get(**lookup_kwargs) Note that if you wanted to use this style together with the generic views then you'd also need to override .get_object on the view in order to get the correct lookup behavior. Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation. Further notes The queryset argument The queryset argument is only ever required for writable relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance. In version 2.x a serializer class could sometimes automatically determine the queryset argument if a ModelSerializer class was being used. This behavior is now replaced with always using an explicit queryset argument for writable relational fields. Doing so reduces the amount of hidden 'magic' that ModelSerializer provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the ModelSerializer shortcut, or using fully explicit Serializer classes. Customizing the HTML display The built-in __str__ method of the model will be used to generate string representations of the objects used to populate the choices property. These choices are used to populate select HTML inputs in the browsable API. To provide customized representations for such inputs, override display_value() of a RelatedField subclass. This method will receive a model object, and should return a string suitable for representing it. For example: class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def display_value(self, instance): return 'Track: %s' % (instance.title) Select field cutoffs When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with \"More than 1000 items\u2026\" will be displayed. This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed. There are two keyword arguments you can use to control this behavior: html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to None to disable any limiting. Defaults to 1000 . html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \"More than {count} items\u2026\" You can also control these globally using the settings HTML_SELECT_CUTOFF and HTML_SELECT_CUTOFF_TEXT . In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the style keyword argument. For example: assigned_to = serializers.SlugRelatedField( queryset=User.objects.all(), slug_field='username', style={'base_template': 'input.html'} ) Reverse relations Note that reverse relationships are not automatically included by the ModelSerializer and HyperlinkedModelSerializer classes. To include a reverse relationship, you must explicitly add it to the fields list. For example: class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = ['tracks', ...] You'll normally want to ensure that you've set an appropriate related_name argument on the relationship, that you can use as the field name. For example: class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) ... If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the fields argument. For example: class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = ['track_set', ...] See the Django documentation on reverse relationships for more details. Generic relationships If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship. For example, given the following model for a tag, which has a generic relationship with other arbitrary models: class TaggedItem(models.Model): \"\"\" Tags arbitrary model instances using a generic relation. See: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/ \"\"\" tag_name = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() tagged_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.tag_name And the following two models, which may have associated tags: class Bookmark(models.Model): \"\"\" A bookmark consists of a URL, and 0 or more descriptive tags. \"\"\" url = models.URLField() tags = GenericRelation(TaggedItem) class Note(models.Model): \"\"\" A note consists of some text, and 0 or more descriptive tags. \"\"\" text = models.CharField(max_length=1000) tags = GenericRelation(TaggedItem) We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized. class TaggedObjectRelatedField(serializers.RelatedField): \"\"\" A custom field to use for the `tagged_object` generic relationship. \"\"\" def to_representation(self, value): \"\"\" Serialize tagged objects to a simple textual representation. \"\"\" if isinstance(value, Bookmark): return 'Bookmark: ' + value.url elif isinstance(value, Note): return 'Note: ' + value.text raise Exception('Unexpected type of tagged object') If you need the target of the relationship to have a nested representation, you can use the required serializers inside the .to_representation() method: def to_representation(self, value): \"\"\" Serialize bookmark instances using a bookmark serializer, and note instances using a note serializer. \"\"\" if isinstance(value, Bookmark): serializer = BookmarkSerializer(value) elif isinstance(value, Note): serializer = NoteSerializer(value) else: raise Exception('Unexpected type of tagged object') return serializer.data Note that reverse generic keys, expressed using the GenericRelation field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known. For more information see the Django documentation on generic relations . ManyToManyFields with a Through Model By default, relational fields that target a ManyToManyField with a through model specified are set to read-only. If you explicitly specify a relational field pointing to a ManyToManyField with a through model, be sure to set read_only to True . If you wish to represent extra fields on a through model then you may serialize the through model as a nested object . 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. Rest Framework Generic Relations The rest-framework-generic-relations library provides read/write serialization for generic foreign keys.","title":"Serializer relations"},{"location":"api-guide/relations/#serializer-relations","text":"Data structures, not algorithms, are central to programming. \u2014 Rob Pike Relational fields are used to represent model relationships. They can be applied to ForeignKey , ManyToManyField and OneToOneField relationships, as well as to reverse relationships, and custom relationships such as GenericForeignKey . Note: The relational fields are declared in relations.py , but by convention you should import them from the serializers module, using from rest_framework import serializers and refer to fields as serializers. .","title":"Serializer relations"},{"location":"api-guide/relations/#inspecting-relationships","text":"When using the ModelSerializer class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style. To do so, open the Django shell, using python manage.py shell , then import the serializer class, instantiate it, and print the object representation\u2026 >>> from myapp.serializers import AccountSerializer >>> serializer = AccountSerializer() >>> print(repr(serializer)) AccountSerializer(): id = IntegerField(label='ID', read_only=True) name = CharField(allow_blank=True, max_length=100, required=False) owner = PrimaryKeyRelatedField(queryset=User.objects.all())","title":"Inspecting relationships."},{"location":"api-guide/relations/#api-reference","text":"In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album. class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Meta: unique_together = ['album', 'order'] ordering = ['order'] def __str__(self): return '%d: %s' % (self.order, self.title)","title":"API Reference"},{"location":"api-guide/relations/#stringrelatedfield","text":"StringRelatedField may be used to represent the target of the relationship using its __str__ method. For example, the following serializer. class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.StringRelatedField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to the following representation. { 'album_name': 'Things We Lost In The Fire', 'artist': 'Low', 'tracks': [ '1: Sunflower', '2: Whitetail', '3: Dinosaur Act', ... ] } This field is read only. Arguments : many - If applied to a to-many relationship, you should set this argument to True .","title":"StringRelatedField"},{"location":"api-guide/relations/#primarykeyrelatedfield","text":"PrimaryKeyRelatedField may be used to represent the target of the relationship using its primary key. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a representation like this: { 'album_name': 'Undun', 'artist': 'The Roots', 'tracks': [ 89, 90, 91, ... ] } By default this field is read-write, although you can change this behavior using the read_only flag. Arguments : queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True . allow_null - If set to True , the field will accept values of None or the empty string for nullable relationships. Defaults to False . pk_field - Set to a field to control serialization/deserialization of the primary key's value. For example, pk_field=UUIDField(format='hex') would serialize a UUID primary key into its compact hex representation.","title":"PrimaryKeyRelatedField"},{"location":"api-guide/relations/#hyperlinkedrelatedfield","text":"HyperlinkedRelatedField may be used to represent the target of the relationship using a hyperlink. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='track-detail' ) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a representation like this: { 'album_name': 'Graceland', 'artist': 'Paul Simon', 'tracks': [ 'http://www.example.com/api/tracks/45/', 'http://www.example.com/api/tracks/46/', 'http://www.example.com/api/tracks/47/', ... ] } By default this field is read-write, although you can change this behavior using the read_only flag. Note : This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the lookup_field and lookup_url_kwarg arguments. This is suitable for URLs that contain a single primary key or slug argument as part of the URL. If you require more complex hyperlinked representation you'll need to customize the field, as described in the custom hyperlinked fields section, below. Arguments : view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format -detail . required . queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True . allow_null - If set to True , the field will accept values of None or the empty string for nullable relationships. Defaults to False . lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk' . lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field . format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument.","title":"HyperlinkedRelatedField"},{"location":"api-guide/relations/#slugrelatedfield","text":"SlugRelatedField may be used to represent the target of the relationship using a field on the target. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.SlugRelatedField( many=True, read_only=True, slug_field='title' ) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a representation like this: { 'album_name': 'Dear John', 'artist': 'Loney Dear', 'tracks': [ 'Airport Surroundings', 'Everything Turns to You', 'I Was Only Going Out', ... ] } By default this field is read-write, although you can change this behavior using the read_only flag. When using SlugRelatedField as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with unique=True . Arguments : slug_field - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, username . required queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True . many - If applied to a to-many relationship, you should set this argument to True . allow_null - If set to True , the field will accept values of None or the empty string for nullable relationships. Defaults to False .","title":"SlugRelatedField"},{"location":"api-guide/relations/#hyperlinkedidentityfield","text":"This field can be applied as an identity relationship, such as the 'url' field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: class AlbumSerializer(serializers.HyperlinkedModelSerializer): track_listing = serializers.HyperlinkedIdentityField(view_name='track-list') class Meta: model = Album fields = ['album_name', 'artist', 'track_listing'] Would serialize to a representation like this: { 'album_name': 'The Eraser', 'artist': 'Thom Yorke', 'track_listing': 'http://www.example.com/api/track_list/12/', } This field is always read-only. Arguments : view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format -detail . required . lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk' . lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field . format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument.","title":"HyperlinkedIdentityField"},{"location":"api-guide/relations/#nested-relationships","text":"Nested relationships can be expressed by using serializers as fields. If the field is used to represent a to-many relationship, you should add the many=True flag to the serializer field.","title":"Nested relationships"},{"location":"api-guide/relations/#example","text":"For example, the following serializer: class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a nested representation like this: >>> album = Album.objects.create(album_name=\"The Grey Album\", artist='Danger Mouse') >>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245) >>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264) >>> Track.objects.create(album=album, order=3, title='Encore', duration=159) >>> serializer = AlbumSerializer(instance=album) >>> serializer.data { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ... ], }","title":"Example"},{"location":"api-guide/relations/#writable-nested-serializers","text":"By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create create() and/or update() methods in order to explicitly specify how the child relationships should be saved. class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] def create(self, validated_data): tracks_data = validated_data.pop('tracks') album = Album.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(album=album, **track_data) return album >>> data = { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ], } >>> serializer = AlbumSerializer(data=data) >>> serializer.is_valid() True >>> serializer.save() ","title":"Writable nested serializers"},{"location":"api-guide/relations/#custom-relational-fields","text":"In rare cases where none of the existing relational styles fit the representation you need, you can implement a completely custom relational field, that describes exactly how the output representation should be generated from the model instance. To implement a custom relational field, you should override RelatedField , and implement the .to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance. If you want to implement a read-write relational field, you must also implement the .to_internal_value(self, data) method. To provide a dynamic queryset based on the context , you can also override .get_queryset(self) instead of specifying .queryset on the class or when initializing the field.","title":"Custom relational fields"},{"location":"api-guide/relations/#example_1","text":"For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration. import time class TrackListingField(serializers.RelatedField): def to_representation(self, value): duration = time.strftime('%M:%S', time.gmtime(value.duration)) return 'Track %d: %s (%s)' % (value.order, value.name, duration) class AlbumSerializer(serializers.ModelSerializer): tracks = TrackListingField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] This custom field would then serialize to the following representation. { 'album_name': 'Sometimes I Wish We Were an Eagle', 'artist': 'Bill Callahan', 'tracks': [ 'Track 1: Jim Cain (04:39)', 'Track 2: Eid Ma Clack Shaw (04:19)', 'Track 3: The Wind and the Dove (04:34)', ... ] }","title":"Example"},{"location":"api-guide/relations/#custom-hyperlinked-fields","text":"In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field. You can achieve this by overriding HyperlinkedRelatedField . There are two methods that may be overridden: get_url(self, obj, view_name, request, format) The get_url method is used to map the object instance to its URL representation. May raise a NoReverseMatch if the view_name and lookup_field attributes are not configured to correctly match the URL conf. get_object(self, view_name, view_args, view_kwargs) If you want to support a writable hyperlinked field then you'll also want to override get_object , in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method. The return value of this method should the object that corresponds to the matched URL conf arguments. May raise an ObjectDoesNotExist exception.","title":"Custom hyperlinked fields"},{"location":"api-guide/relations/#example_2","text":"Say we have a URL for a customer object that takes two keyword arguments, like so: /api//customers// This cannot be represented with the default implementation, which accepts only a single lookup field. In this case we'd need to override HyperlinkedRelatedField to get the behavior we want: from rest_framework import serializers from rest_framework.reverse import reverse class CustomerHyperlink(serializers.HyperlinkedRelatedField): # We define these as class attributes, so we don't need to pass them as arguments. view_name = 'customer-detail' queryset = Customer.objects.all() def get_url(self, obj, view_name, request, format): url_kwargs = { 'organization_slug': obj.organization.slug, 'customer_pk': obj.pk } return reverse(view_name, kwargs=url_kwargs, request=request, format=format) def get_object(self, view_name, view_args, view_kwargs): lookup_kwargs = { 'organization__slug': view_kwargs['organization_slug'], 'pk': view_kwargs['customer_pk'] } return self.get_queryset().get(**lookup_kwargs) Note that if you wanted to use this style together with the generic views then you'd also need to override .get_object on the view in order to get the correct lookup behavior. Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.","title":"Example"},{"location":"api-guide/relations/#further-notes","text":"","title":"Further notes"},{"location":"api-guide/relations/#the-queryset-argument","text":"The queryset argument is only ever required for writable relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance. In version 2.x a serializer class could sometimes automatically determine the queryset argument if a ModelSerializer class was being used. This behavior is now replaced with always using an explicit queryset argument for writable relational fields. Doing so reduces the amount of hidden 'magic' that ModelSerializer provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the ModelSerializer shortcut, or using fully explicit Serializer classes.","title":"The queryset argument"},{"location":"api-guide/relations/#customizing-the-html-display","text":"The built-in __str__ method of the model will be used to generate string representations of the objects used to populate the choices property. These choices are used to populate select HTML inputs in the browsable API. To provide customized representations for such inputs, override display_value() of a RelatedField subclass. This method will receive a model object, and should return a string suitable for representing it. For example: class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def display_value(self, instance): return 'Track: %s' % (instance.title)","title":"Customizing the HTML display"},{"location":"api-guide/relations/#select-field-cutoffs","text":"When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with \"More than 1000 items\u2026\" will be displayed. This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed. There are two keyword arguments you can use to control this behavior: html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to None to disable any limiting. Defaults to 1000 . html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \"More than {count} items\u2026\" You can also control these globally using the settings HTML_SELECT_CUTOFF and HTML_SELECT_CUTOFF_TEXT . In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the style keyword argument. For example: assigned_to = serializers.SlugRelatedField( queryset=User.objects.all(), slug_field='username', style={'base_template': 'input.html'} )","title":"Select field cutoffs"},{"location":"api-guide/relations/#reverse-relations","text":"Note that reverse relationships are not automatically included by the ModelSerializer and HyperlinkedModelSerializer classes. To include a reverse relationship, you must explicitly add it to the fields list. For example: class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = ['tracks', ...] You'll normally want to ensure that you've set an appropriate related_name argument on the relationship, that you can use as the field name. For example: class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) ... If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the fields argument. For example: class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = ['track_set', ...] See the Django documentation on reverse relationships for more details.","title":"Reverse relations"},{"location":"api-guide/relations/#generic-relationships","text":"If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship. For example, given the following model for a tag, which has a generic relationship with other arbitrary models: class TaggedItem(models.Model): \"\"\" Tags arbitrary model instances using a generic relation. See: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/ \"\"\" tag_name = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() tagged_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.tag_name And the following two models, which may have associated tags: class Bookmark(models.Model): \"\"\" A bookmark consists of a URL, and 0 or more descriptive tags. \"\"\" url = models.URLField() tags = GenericRelation(TaggedItem) class Note(models.Model): \"\"\" A note consists of some text, and 0 or more descriptive tags. \"\"\" text = models.CharField(max_length=1000) tags = GenericRelation(TaggedItem) We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized. class TaggedObjectRelatedField(serializers.RelatedField): \"\"\" A custom field to use for the `tagged_object` generic relationship. \"\"\" def to_representation(self, value): \"\"\" Serialize tagged objects to a simple textual representation. \"\"\" if isinstance(value, Bookmark): return 'Bookmark: ' + value.url elif isinstance(value, Note): return 'Note: ' + value.text raise Exception('Unexpected type of tagged object') If you need the target of the relationship to have a nested representation, you can use the required serializers inside the .to_representation() method: def to_representation(self, value): \"\"\" Serialize bookmark instances using a bookmark serializer, and note instances using a note serializer. \"\"\" if isinstance(value, Bookmark): serializer = BookmarkSerializer(value) elif isinstance(value, Note): serializer = NoteSerializer(value) else: raise Exception('Unexpected type of tagged object') return serializer.data Note that reverse generic keys, expressed using the GenericRelation field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known. For more information see the Django documentation on generic relations .","title":"Generic relationships"},{"location":"api-guide/relations/#manytomanyfields-with-a-through-model","text":"By default, relational fields that target a ManyToManyField with a through model specified are set to read-only. If you explicitly specify a relational field pointing to a ManyToManyField with a through model, be sure to set read_only to True . If you wish to represent extra fields on a through model then you may serialize the through model as a nested object .","title":"ManyToManyFields with a Through Model"},{"location":"api-guide/relations/#third-party-packages","text":"The following third party packages are also available.","title":"Third Party Packages"},{"location":"api-guide/relations/#drf-nested-routers","text":"The drf-nested-routers package provides routers and relationship fields for working with nested resources.","title":"DRF Nested Routers"},{"location":"api-guide/relations/#rest-framework-generic-relations","text":"The rest-framework-generic-relations library provides read/write serialization for generic foreign keys.","title":"Rest Framework Generic Relations"},{"location":"api-guide/renderers/","text":"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. \u2014 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\":\"\u2605\",\"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\": \"\u2605\", \"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. 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 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_unicode 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 data.encode(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. Jacob Haslehurst maintains the drf-ujson-renderer package 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) .","title":"Renderers"},{"location":"api-guide/renderers/#renderers","text":"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. \u2014 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.","title":"Renderers"},{"location":"api-guide/renderers/#how-the-renderer-is-determined","text":"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 .","title":"How the renderer is determined"},{"location":"api-guide/renderers/#setting-the-renderers","text":"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)","title":"Setting the renderers"},{"location":"api-guide/renderers/#ordering-of-renderer-classes","text":"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 .","title":"Ordering of renderer classes"},{"location":"api-guide/renderers/#api-reference","text":"","title":"API Reference"},{"location":"api-guide/renderers/#jsonrenderer","text":"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\":\"\u2605\",\"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\": \"\u2605\", \"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","title":"JSONRenderer"},{"location":"api-guide/renderers/#templatehtmlrenderer","text":"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. 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","title":"TemplateHTMLRenderer"},{"location":"api-guide/renderers/#statichtmlrenderer","text":"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","title":"StaticHTMLRenderer"},{"location":"api-guide/renderers/#browsableapirenderer","text":"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'","title":"BrowsableAPIRenderer"},{"location":"api-guide/renderers/#customizing-browsableapirenderer","text":"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()","title":"Customizing BrowsableAPIRenderer"},{"location":"api-guide/renderers/#adminrenderer","text":"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'","title":"AdminRenderer"},{"location":"api-guide/renderers/#htmlformrenderer","text":"Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing For more information see the HTML & Forms documentation. .media_type : text/html .format : 'form' .charset : utf-8 .template : 'rest_framework/horizontal/form.html'","title":"HTMLFormRenderer"},{"location":"api-guide/renderers/#multipartrenderer","text":"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","title":"MultiPartRenderer"},{"location":"api-guide/renderers/#custom-renderers","text":"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:","title":"Custom renderers"},{"location":"api-guide/renderers/#data","text":"The request data, as set by the Response() instantiation.","title":"data"},{"location":"api-guide/renderers/#media_typenone","text":"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\" .","title":"media_type=None"},{"location":"api-guide/renderers/#renderer_contextnone","text":"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 .","title":"renderer_context=None"},{"location":"api-guide/renderers/#example","text":"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_unicode 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 data.encode(self.charset)","title":"Example"},{"location":"api-guide/renderers/#setting-the-character-set","text":"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","title":"Setting the character set"},{"location":"api-guide/renderers/#advanced-renderer-usage","text":"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.","title":"Advanced renderer usage"},{"location":"api-guide/renderers/#varying-behaviour-by-media-type","text":"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)","title":"Varying behaviour by media type"},{"location":"api-guide/renderers/#underspecifying-the-media-type","text":"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')","title":"Underspecifying the media type"},{"location":"api-guide/renderers/#designing-your-media-types","text":"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.","title":"Designing your media types"},{"location":"api-guide/renderers/#html-error-views","text":"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.","title":"HTML error views"},{"location":"api-guide/renderers/#third-party-packages","text":"The following third party packages are also available.","title":"Third party packages"},{"location":"api-guide/renderers/#yaml","text":"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.","title":"YAML"},{"location":"api-guide/renderers/#installation-configuration","text":"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', ], }","title":"Installation & configuration"},{"location":"api-guide/renderers/#xml","text":"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.","title":"XML"},{"location":"api-guide/renderers/#installation-configuration_1","text":"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', ], }","title":"Installation & configuration"},{"location":"api-guide/renderers/#jsonp","text":"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.","title":"JSONP"},{"location":"api-guide/renderers/#installation-configuration_2","text":"Install using pip. $ pip install djangorestframework-jsonp Modify your REST framework settings. REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework_jsonp.renderers.JSONPRenderer', ], }","title":"Installation & configuration"},{"location":"api-guide/renderers/#messagepack","text":"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.","title":"MessagePack"},{"location":"api-guide/renderers/#xlsx-binary-spreadsheet-endpoints","text":"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.","title":"XLSX (Binary Spreadsheet Endpoints)"},{"location":"api-guide/renderers/#installation-configuration_3","text":"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'","title":"Installation & configuration"},{"location":"api-guide/renderers/#csv","text":"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.","title":"CSV"},{"location":"api-guide/renderers/#ultrajson","text":"UltraJSON is an optimized C JSON encoder which can give significantly faster JSON rendering. Jacob Haslehurst maintains the drf-ujson-renderer package which implements JSON rendering using the UJSON package.","title":"UltraJSON"},{"location":"api-guide/renderers/#camelcase-json","text":"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 .","title":"CamelCase JSON"},{"location":"api-guide/renderers/#pandas-csv-excel-png","text":"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 .","title":"Pandas (CSV, Excel, PNG)"},{"location":"api-guide/renderers/#latex","text":"Rest Framework Latex provides a renderer that outputs PDFs using Laulatex. It is maintained by Pebble (S/F Software) .","title":"LaTeX"},{"location":"api-guide/requests/","text":"Requests If you're doing REST-based web service stuff ... you should ignore request.POST. \u2014 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 in the same way that 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 serialisation 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.","title":"Requests"},{"location":"api-guide/requests/#requests","text":"If you're doing REST-based web service stuff ... you should ignore request.POST. \u2014 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.","title":"Requests"},{"location":"api-guide/requests/#request-parsing","text":"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.","title":"Request parsing"},{"location":"api-guide/requests/#data","text":"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 in the same way that you handle incoming form data. For more details see the parsers documentation .","title":".data"},{"location":"api-guide/requests/#query_params","text":"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.","title":".query_params"},{"location":"api-guide/requests/#parsers","text":"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.","title":".parsers"},{"location":"api-guide/requests/#content-negotiation","text":"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 serialisation schemes for different media types.","title":"Content negotiation"},{"location":"api-guide/requests/#accepted_renderer","text":"The renderer instance that was selected by the content negotiation stage.","title":".accepted_renderer"},{"location":"api-guide/requests/#accepted_media_type","text":"A string representing the media type that was accepted by the content negotiation stage.","title":".accepted_media_type"},{"location":"api-guide/requests/#authentication","text":"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.","title":"Authentication"},{"location":"api-guide/requests/#user","text":"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 .","title":".user"},{"location":"api-guide/requests/#auth","text":"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 .","title":".auth"},{"location":"api-guide/requests/#authenticators","text":"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.","title":".authenticators"},{"location":"api-guide/requests/#browser-enhancements","text":"REST framework supports a few browser enhancements such as browser-based PUT , PATCH and DELETE forms.","title":"Browser enhancements"},{"location":"api-guide/requests/#method","text":"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 .","title":".method"},{"location":"api-guide/requests/#content_type","text":"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 .","title":".content_type"},{"location":"api-guide/requests/#stream","text":"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.","title":".stream"},{"location":"api-guide/requests/#standard-httprequest-attributes","text":"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.","title":"Standard HttpRequest attributes"},{"location":"api-guide/responses/","text":"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. \u2014 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.","title":"Responses"},{"location":"api-guide/responses/#responses","text":"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. \u2014 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.","title":"Responses"},{"location":"api-guide/responses/#creating-responses","text":"","title":"Creating responses"},{"location":"api-guide/responses/#response","text":"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.","title":"Response()"},{"location":"api-guide/responses/#attributes","text":"","title":"Attributes"},{"location":"api-guide/responses/#data","text":"The unrendered, serialized data of the response.","title":".data"},{"location":"api-guide/responses/#status_code","text":"The numeric status code of the HTTP response.","title":".status_code"},{"location":"api-guide/responses/#content","text":"The rendered content of the response. The .render() method must have been called before .content can be accessed.","title":".content"},{"location":"api-guide/responses/#template_name","text":"The template_name , if supplied. Only required if HTMLRenderer or some other custom template renderer is the accepted renderer for the response.","title":".template_name"},{"location":"api-guide/responses/#accepted_renderer","text":"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.","title":".accepted_renderer"},{"location":"api-guide/responses/#accepted_media_type","text":"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.","title":".accepted_media_type"},{"location":"api-guide/responses/#renderer_context","text":"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.","title":".renderer_context"},{"location":"api-guide/responses/#standard-httpresponse-attributes","text":"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'","title":"Standard HttpResponse attributes"},{"location":"api-guide/responses/#render","text":"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.","title":".render()"},{"location":"api-guide/reverse/","text":"Returning URLs The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components. \u2014 Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures As a rule, it's probably better practice to return absolute URIs from your Web APIs, such as http://example.com/foobar , rather than returning relative URIs, such as /foobar . The advantages of doing so are: It's more explicit. It leaves less work for your API clients. There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type. It makes it easy to do things like markup HTML representations with hyperlinks. REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API. There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier. reverse Signature: reverse(viewname, *args, **kwargs) Has the same behavior as django.urls.reverse , except that it returns a fully qualified URL, using the request to determine the host and port. You should include the request as a keyword argument to the function, for example: from rest_framework.reverse import reverse from rest_framework.views import APIView from django.utils.timezone import now class APIRootView(APIView): def get(self, request): year = now().year data = { ... 'year-summary-url': reverse('year-summary', args=[year], request=request) } return Response(data) reverse_lazy Signature: reverse_lazy(viewname, *args, **kwargs) Has the same behavior as django.urls.reverse_lazy , except that it returns a fully qualified URL, using the request to determine the host and port. As with the reverse function, you should include the request as a keyword argument to the function, for example: api_root = reverse_lazy('api-root', request=request)","title":"Returning URLs"},{"location":"api-guide/reverse/#returning-urls","text":"The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components. \u2014 Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures As a rule, it's probably better practice to return absolute URIs from your Web APIs, such as http://example.com/foobar , rather than returning relative URIs, such as /foobar . The advantages of doing so are: It's more explicit. It leaves less work for your API clients. There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type. It makes it easy to do things like markup HTML representations with hyperlinks. REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API. There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier.","title":"Returning URLs"},{"location":"api-guide/reverse/#reverse","text":"Signature: reverse(viewname, *args, **kwargs) Has the same behavior as django.urls.reverse , except that it returns a fully qualified URL, using the request to determine the host and port. You should include the request as a keyword argument to the function, for example: from rest_framework.reverse import reverse from rest_framework.views import APIView from django.utils.timezone import now class APIRootView(APIView): def get(self, request): year = now().year data = { ... 'year-summary-url': reverse('year-summary', args=[year], request=request) } return Response(data)","title":"reverse"},{"location":"api-guide/reverse/#reverse_lazy","text":"Signature: reverse_lazy(viewname, *args, **kwargs) Has the same behavior as django.urls.reverse_lazy , except that it returns a fully qualified URL, using the request to determine the host and port. As with the reverse function, you should include the request as a keyword argument to the function, for example: api_root = reverse_lazy('api-root', request=request)","title":"reverse_lazy"},{"location":"api-guide/routers/","text":"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. \u2014 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 = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), ] urlpatterns += router.urls Alternatively you can use Django's include function, like so... urlpatterns = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), url(r'^', include(router.urls)), ] You may use include with an application namespace: urlpatterns = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), url(r'^api/', include((router.urls, 'app_name'))), ] Or both an application and instance namespace: urlpatterns = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), url(r'^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 .","title":"Routers"},{"location":"api-guide/routers/#routers","text":"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. \u2014 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.","title":"Routers"},{"location":"api-guide/routers/#usage","text":"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.","title":"Usage"},{"location":"api-guide/routers/#using-include-with-routers","text":"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 = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), ] urlpatterns += router.urls Alternatively you can use Django's include function, like so... urlpatterns = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), url(r'^', include(router.urls)), ] You may use include with an application namespace: urlpatterns = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), url(r'^api/', include((router.urls, 'app_name'))), ] Or both an application and instance namespace: urlpatterns = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), url(r'^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.","title":"Using include with routers"},{"location":"api-guide/routers/#routing-for-extra-actions","text":"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'","title":"Routing for extra actions"},{"location":"api-guide/routers/#api-guide","text":"","title":"API Guide"},{"location":"api-guide/routers/#simplerouter","text":"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}'","title":"SimpleRouter"},{"location":"api-guide/routers/#defaultrouter","text":"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)","title":"DefaultRouter"},{"location":"api-guide/routers/#custom-routers","text":"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.","title":"Custom Routers"},{"location":"api-guide/routers/#customizing-dynamic-routes","text":"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.","title":"Customizing dynamic routes"},{"location":"api-guide/routers/#example","text":"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.","title":"Example"},{"location":"api-guide/routers/#advanced-custom-routers","text":"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.","title":"Advanced custom routers"},{"location":"api-guide/routers/#third-party-packages","text":"The following third party packages are also available.","title":"Third Party Packages"},{"location":"api-guide/routers/#drf-nested-routers","text":"The drf-nested-routers package provides routers and relationship fields for working with nested resources.","title":"DRF Nested Routers"},{"location":"api-guide/routers/#modelrouter-wqdbrest","text":"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)","title":"ModelRouter (wq.db.rest)"},{"location":"api-guide/routers/#drf-extensions","text":"The DRF-extensions package provides routers for creating nested viewsets , collection level controllers with customizable endpoint names .","title":"DRF-extensions"},{"location":"api-guide/schemas/","text":"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. \u2014 Heroku, [JSON Schema for the Heroku Platform API][cite] 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. Generating an OpenAPI Schema Install pyyaml You'll need to install pyyaml , so that you can render your generated schema into the commonly used YAML-based OpenAPI format. pip install pyyaml Generating a static schema with the generateschema management command If your schema is static, you can use the generateschema management command: ./manage.py generateschema > 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 \u2026\", 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. Defaults to 0.1.0 . 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 = [ url(r'^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. Customizing Schema Generation You may customize schema generation at the level of the schema as a whole, or on a per-view basis. Schema Level Customization In order to customize the top-level schema sublass rest_framework.schemas.openapi.SchemaGenerator and provide it as an argument to the generateschema command or get_schema_view() helper function. SchemaGenerator A class that walks a list of routed URL patterns, requests the schema for each view and collates the resulting OpenAPI schema. Typically you'll instantiate SchemaGenerator with a title argument, 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 . 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 customise the generated dictionary, for example to add custom specification extensions . Per-View Customization By default, view introspection is performed by an AutoSchema instance accessible via the schema attribute on APIView . This provides the appropriate Open API operation object for the view, request method and path: auto_schema = view.schema operation = auto_schema.get_operation(...) In compiling the schema, SchemaGenerator calls view.schema.get_operation() for each view, allowed method, and path. Note : For basic APIView subclasses, default introspection is essentially limited to the URL kwarg path parameters. For GenericAPIView subclasses, which includes all the provided class based views, AutoSchema will attempt to introspect serialiser, pagination and filter fields, as well as provide richer path field descriptions. (The key hooks here are the relevant GenericAPIView attributes and methods: get_serializer , pagination_class , filter_backends and so on.) In order to customise the operation generation, you should provide an AutoSchema subclass, overriding get_operation() as you need: from rest_framework.views import APIView from rest_framework.schemas.openapi import AutoSchema class CustomSchema(AutoSchema): def get_link(...): # Implement custom introspection here (or in other sub-methods) class CustomView(APIView): \"\"\"APIView subclass with custom schema introspection.\"\"\" schema = CustomSchema() This provides complete control over view introspection. You may disable schema generation for a view by setting schema to None : class CustomView(APIView): ... schema = None # Will not appear in schema This also applies to extra actions for ViewSet s: class CustomViewSet(viewsets.ModelViewSet): @action(detail=True, schema=None) def extra_action(self, request, pk=None): ... If you wish to provide a base AutoSchema subclass to be used throughout your project you may adjust settings.DEFAULT_SCHEMA_CLASS appropriately.","title":"Schemas"},{"location":"api-guide/schemas/#schema","text":"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. \u2014 Heroku, [JSON Schema for the Heroku Platform API][cite] 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.","title":"Schema"},{"location":"api-guide/schemas/#generating-an-openapi-schema","text":"","title":"Generating an OpenAPI Schema"},{"location":"api-guide/schemas/#install-pyyaml","text":"You'll need to install pyyaml , so that you can render your generated schema into the commonly used YAML-based OpenAPI format. pip install pyyaml","title":"Install pyyaml"},{"location":"api-guide/schemas/#generating-a-static-schema-with-the-generateschema-management-command","text":"If your schema is static, you can use the generateschema management command: ./manage.py generateschema > 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.","title":"Generating a static schema with the generateschema management command"},{"location":"api-guide/schemas/#generating-a-dynamic-schema-with-schemaview","text":"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 \u2026\", version=\"1.0.0\" ), name='openapi-schema'), # ... ]","title":"Generating a dynamic schema with SchemaView"},{"location":"api-guide/schemas/#get_schema_view","text":"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. Defaults to 0.1.0 . 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 = [ url(r'^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.","title":"get_schema_view()"},{"location":"api-guide/schemas/#customizing-schema-generation","text":"You may customize schema generation at the level of the schema as a whole, or on a per-view basis.","title":"Customizing Schema Generation"},{"location":"api-guide/schemas/#schema-level-customization","text":"In order to customize the top-level schema sublass rest_framework.schemas.openapi.SchemaGenerator and provide it as an argument to the generateschema command or get_schema_view() helper function.","title":"Schema Level Customization"},{"location":"api-guide/schemas/#schemagenerator","text":"A class that walks a list of routed URL patterns, requests the schema for each view and collates the resulting OpenAPI schema. Typically you'll instantiate SchemaGenerator with a title argument, 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 .","title":"SchemaGenerator"},{"location":"api-guide/schemas/#get_schemaself-request","text":"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 customise the generated dictionary, for example to add custom specification extensions .","title":"get_schema(self, request)"},{"location":"api-guide/schemas/#per-view-customization","text":"By default, view introspection is performed by an AutoSchema instance accessible via the schema attribute on APIView . This provides the appropriate Open API operation object for the view, request method and path: auto_schema = view.schema operation = auto_schema.get_operation(...) In compiling the schema, SchemaGenerator calls view.schema.get_operation() for each view, allowed method, and path. Note : For basic APIView subclasses, default introspection is essentially limited to the URL kwarg path parameters. For GenericAPIView subclasses, which includes all the provided class based views, AutoSchema will attempt to introspect serialiser, pagination and filter fields, as well as provide richer path field descriptions. (The key hooks here are the relevant GenericAPIView attributes and methods: get_serializer , pagination_class , filter_backends and so on.) In order to customise the operation generation, you should provide an AutoSchema subclass, overriding get_operation() as you need: from rest_framework.views import APIView from rest_framework.schemas.openapi import AutoSchema class CustomSchema(AutoSchema): def get_link(...): # Implement custom introspection here (or in other sub-methods) class CustomView(APIView): \"\"\"APIView subclass with custom schema introspection.\"\"\" schema = CustomSchema() This provides complete control over view introspection. You may disable schema generation for a view by setting schema to None : class CustomView(APIView): ... schema = None # Will not appear in schema This also applies to extra actions for ViewSet s: class CustomViewSet(viewsets.ModelViewSet): @action(detail=True, schema=None) def extra_action(self, request, pk=None): ... If you wish to provide a base AutoSchema subclass to be used throughout your project you may adjust settings.DEFAULT_SCHEMA_CLASS appropriately.","title":"Per-View Customization"},{"location":"api-guide/serializers/","text":"Serializers Expanding the usefulness of the serializers is something that we would like to address. However, it's not a trivial problem, and it will take some serious design work. \u2014 Russell Keith-Magee, Django users group Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. The serializers in REST framework work very similarly to Django's Form and ModelForm classes. We provide a Serializer class which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets. Declaring Serializers Let's start by creating a simple object we can use for example purposes: from datetime import datetime class Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.now() comment = Comment(email='leila@example.com', content='foo bar') We'll declare a serializer that we can use to serialize and deserialize data that corresponds to Comment objects. Declaring a serializer looks very similar to declaring a form: from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() Serializing objects We can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class. serializer = CommentSerializer(comment) serializer.data # {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'} At this point we've translated the model instance into Python native datatypes. To finalise the serialization process we render the data into json . from rest_framework.renderers import JSONRenderer json = JSONRenderer().render(serializer.data) json # b'{\"email\":\"leila@example.com\",\"content\":\"foo bar\",\"created\":\"2016-01-27T15:17:10.375877\"}' Deserializing objects Deserialization is similar. First we parse a stream into Python native datatypes... import io from rest_framework.parsers import JSONParser stream = io.BytesIO(json) data = JSONParser().parse(stream) ...then we restore those native datatypes into a dictionary of validated data. serializer = CommentSerializer(data=data) serializer.is_valid() # True serializer.validated_data # {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)} Saving instances If we want to be able to return complete object instances based on the validated data we need to implement one or both of the .create() and .update() methods. For example: class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() def create(self, validated_data): return Comment(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) return instance If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if Comment was a Django model, the methods might look like this: def create(self, validated_data): return Comment.objects.create(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) instance.save() return instance Now when deserializing data, we can call .save() to return an object instance, based on the validated data. comment = serializer.save() Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class: # .save() will create a new instance. serializer = CommentSerializer(data=data) # .save() will update the existing `comment` instance. serializer = CommentSerializer(comment, data=data) Both the .create() and .update() methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class. Passing additional attributes to .save() Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data. You can do so by including additional keyword arguments when calling .save() . For example: serializer.save(owner=request.user) Any additional keyword arguments will be included in the validated_data argument when .create() or .update() are called. Overriding .save() directly. In some cases the .create() and .update() method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message. In these cases you might instead choose to override .save() directly, as being more readable and meaningful. For example: class ContactForm(serializers.Serializer): email = serializers.EmailField() message = serializers.CharField() def save(self): email = self.validated_data['email'] message = self.validated_data['message'] send_email(from=email, message=message) Note that in the case above we're now having to access the serializer .validated_data property directly. Validation When deserializing data, you always need to call is_valid() before attempting to access the validated data, or save an object instance. If any validation errors occur, the .errors property will contain a dictionary representing the resulting error messages. For example: serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'}) serializer.is_valid() # False serializer.errors # {'email': ['Enter a valid e-mail address.'], 'created': ['This field is required.']} Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The non_field_errors key may also be present, and will list any general validation errors. The name of the non_field_errors key may be customized using the NON_FIELD_ERRORS_KEY REST framework setting. When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items. Raising an exception on invalid data The .is_valid() method takes an optional raise_exception flag that will cause it to raise a serializers.ValidationError exception if there are validation errors. These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return HTTP 400 Bad Request responses by default. # Return a 400 response if the data was invalid. serializer.is_valid(raise_exception=True) Field-level validation You can specify custom field-level validation by adding .validate_ methods to your Serializer subclass. These are similar to the .clean_ methods on Django forms. These methods take a single argument, which is the field value that requires validation. Your validate_ methods should return the validated value or raise a serializers.ValidationError . For example: from rest_framework import serializers class BlogPostSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) content = serializers.CharField() def validate_title(self, value): \"\"\" Check that the blog post is about Django. \"\"\" if 'django' not in value.lower(): raise serializers.ValidationError(\"Blog post is not about Django\") return value Note: If your is declared on your serializer with the parameter required=False then this validation step will not take place if the field is not included. Object-level validation To do any other validation that requires access to multiple fields, add a method called .validate() to your Serializer subclass. This method takes a single argument, which is a dictionary of field values. It should raise a serializers.ValidationError if necessary, or just return the validated values. For example: from rest_framework import serializers class EventSerializer(serializers.Serializer): description = serializers.CharField(max_length=100) start = serializers.DateTimeField() finish = serializers.DateTimeField() def validate(self, data): \"\"\" Check that start is before finish. \"\"\" if data['start'] > data['finish']: raise serializers.ValidationError(\"finish must occur after start\") return data Validators Individual fields on a serializer can include validators, by declaring them on the field instance, for example: def multiple_of_ten(value): if value % 10 != 0: raise serializers.ValidationError('Not a multiple of ten') class GameRecord(serializers.Serializer): score = IntegerField(validators=[multiple_of_ten]) ... Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner Meta class, like so: class EventSerializer(serializers.Serializer): name = serializers.CharField() room_number = serializers.IntegerField(choices=[101, 102, 103, 201]) date = serializers.DateField() class Meta: # Each room only has one event per day. validators = UniqueTogetherValidator( queryset=Event.objects.all(), fields=['room_number', 'date'] ) For more information see the validators documentation . Accessing the initial data and instance When passing an initial object or queryset to a serializer instance, the object will be made available as .instance . If no initial object is passed then the .instance attribute will be None . When passing data to a serializer instance, the unmodified data will be made available as .initial_data . If the data keyword argument is not passed then the .initial_data attribute will not exist. Partial updates By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the partial argument in order to allow partial updates. # Update `comment` with partial data serializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True) Dealing with nested objects The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers. The Serializer class is itself a type of Field , and can be used to represent relationships where one object type is nested inside another. class UserSerializer(serializers.Serializer): email = serializers.EmailField() username = serializers.CharField(max_length=100) class CommentSerializer(serializers.Serializer): user = UserSerializer() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() If a nested representation may optionally accept the None value you should pass the required=False flag to the nested serializer. class CommentSerializer(serializers.Serializer): user = UserSerializer(required=False) # May be an anonymous user. content = serializers.CharField(max_length=200) created = serializers.DateTimeField() Similarly if a nested representation should be a list of items, you should pass the many=True flag to the nested serialized. class CommentSerializer(serializers.Serializer): user = UserSerializer(required=False) edits = EditItemSerializer(many=True) # A nested list of 'edit' items. content = serializers.CharField(max_length=200) created = serializers.DateTimeField() Writable nested representations When dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object. serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'}) serializer.is_valid() # False serializer.errors # {'user': {'email': ['Enter a valid e-mail address.']}, 'created': ['This field is required.']} Similarly, the .validated_data property will include nested data structures. Writing .create() methods for nested representations If you're supporting writable nested representations you'll need to write .create() or .update() methods that handle saving multiple objects. The following example demonstrates how you might handle creating a user with a nested profile object. class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ['username', 'email', 'profile'] def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user Writing .update() methods for nested representations For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is None , or not provided, which of the following should occur? Set the relationship to NULL in the database. Delete the associated instance. Ignore the data and leave the instance as it is. Raise a validation error. Here's an example for an .update() method on our previous UserSerializer class. def update(self, instance, validated_data): profile_data = validated_data.pop('profile') # Unless the application properly enforces that this field is # always set, the follow could raise a `DoesNotExist`, which # would need to be handled. profile = instance.profile instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.email) instance.save() profile.is_premium_member = profile_data.get( 'is_premium_member', profile.is_premium_member ) profile.has_support_contract = profile_data.get( 'has_support_contract', profile.has_support_contract ) profile.save() return instance Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default ModelSerializer .create() and .update() methods do not include support for writable nested representations. There are however, third-party packages available such as DRF Writable Nested that support automatic writable nested representations. Handling saving related instances in model manager classes An alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances. For example, suppose we wanted to ensure that User instances and Profile instances are always created together as a pair. We might write a custom manager class that looks something like this: class UserManager(models.Manager): ... def create(self, username, email, is_premium_member=False, has_support_contract=False): user = User(username=username, email=email) user.save() profile = Profile( user=user, is_premium_member=is_premium_member, has_support_contract=has_support_contract ) profile.save() return user This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our .create() method on the serializer class can now be re-written to use the new manager method. def create(self, validated_data): return User.objects.create( username=validated_data['username'], email=validated_data['email'] is_premium_member=validated_data['profile']['is_premium_member'] has_support_contract=validated_data['profile']['has_support_contract'] ) For more details on this approach see the Django documentation on model managers , and this blogpost on using model and manager classes . Dealing with multiple objects The Serializer class can also handle serializing or deserializing lists of objects. Serializing multiple objects To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized. queryset = Book.objects.all() serializer = BookSerializer(queryset, many=True) serializer.data # [ # {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'}, # {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'}, # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'} # ] Deserializing multiple objects The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the ListSerializer documentation below. Including extra context There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs. You can provide arbitrary additional context by passing a context argument when instantiating the serializer. For example: serializer = AccountSerializer(account, context={'request': request}) serializer.data # {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'} The context dictionary can be used within any serializer field logic, such as a custom .to_representation() method, by accessing the self.context attribute. ModelSerializer Often you'll want serializer classes that map closely to Django model definitions. The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields. The ModelSerializer class is the same as a regular Serializer class, except that : It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .create() and .update() . Declaring a ModelSerializer looks like this: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] By default, all the model fields on the class will be mapped to a corresponding serializer fields. Any relationships such as foreign keys on the model will be mapped to PrimaryKeyRelatedField . Reverse relationships are not included by default unless explicitly included as specified in the serializer relations documentation. Inspecting a ModelSerializer Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with ModelSerializers where you want to determine what set of fields and validators are being automatically created for you. To do so, open the Django shell, using python manage.py shell , then import the serializer class, instantiate it, and print the object representation\u2026 >>> from myapp.serializers import AccountSerializer >>> serializer = AccountSerializer() >>> print(repr(serializer)) AccountSerializer(): id = IntegerField(label='ID', read_only=True) name = CharField(allow_blank=True, max_length=100, required=False) owner = PrimaryKeyRelatedField(queryset=User.objects.all()) Specifying which fields to include If you only want a subset of the default fields to be used in a model serializer, you can do so using fields or exclude options, just as you would with a ModelForm . It is strongly recommended that you explicitly set all fields that should be serialized using the fields attribute. This will make it less likely to result in unintentionally exposing data when your models change. For example: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] You can also set the fields attribute to the special value '__all__' to indicate that all fields in the model should be used. For example: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = '__all__' You can set the exclude attribute to a list of fields to be excluded from the serializer. For example: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account exclude = ['users'] In the example above, if the Account model had 3 fields account_name , users , and created , this will result in the fields account_name and created to be serialized. The names in the fields and exclude attributes will normally map to model fields on the model class. Alternatively names in the fields options can map to properties or methods which take no arguments that exist on the model class. Since version 3.3.0, it is mandatory to provide one of the attributes fields or exclude . Specifying nested serialization The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] depth = 1 The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. If you want to customize the way the serialization is done you'll need to define the field yourself. Specifying fields explicitly You can add extra fields to a ModelSerializer or override the default fields by declaring fields on the class, just as you would for a Serializer class. class AccountSerializer(serializers.ModelSerializer): url = serializers.CharField(source='get_absolute_url', read_only=True) groups = serializers.PrimaryKeyRelatedField(many=True) class Meta: model = Account Extra fields can correspond to any property or callable on the model. Specifying read only fields You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the read_only=True attribute, you may use the shortcut Meta option, read_only_fields . This option should be a list or tuple of field names, and is declared as follows: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] read_only_fields = ['account_name'] Model fields which have editable=False set, and AutoField fields will be set to read-only by default, and do not need to be added to the read_only_fields option. Note : There is a special-case where a read-only field is part of a unique_together constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user. The right way to deal with this is to specify the field explicitly on the serializer, providing both the read_only=True and default=\u2026 keyword arguments. One example of this is a read-only relation to the currently authenticated User which is unique_together with another identifier. In this case you would declare the user field like so: user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) Please review the Validators Documentation for details on the UniqueTogetherValidator and CurrentUserDefault classes. Additional keyword arguments There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the extra_kwargs option. As in the case of read_only_fields , this means you do not need to explicitly declare the field on the serializer. This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example: class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email', 'username', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user Please keep in mind that, if the field has already been explicitly declared on the serializer class, then the extra_kwargs option will be ignored. Relational fields When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for ModelSerializer is to use the primary keys of the related instances. Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation. For full details see the serializer relations documentation. Customizing field mappings The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer. Normally if a ModelSerializer does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular Serializer class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model. .serializer_field_mapping A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class. .serializer_related_field This property should be the serializer field class, that is used for relational fields by default. For ModelSerializer this defaults to PrimaryKeyRelatedField . For HyperlinkedModelSerializer this defaults to serializers.HyperlinkedRelatedField . serializer_url_field The serializer field class that should be used for any url field on the serializer. Defaults to serializers.HyperlinkedIdentityField serializer_choice_field The serializer field class that should be used for any choice fields on the serializer. Defaults to serializers.ChoiceField The field_class and field_kwargs API The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of (field_class, field_kwargs) . .build_standard_field(self, field_name, model_field) Called to generate a serializer field that maps to a standard model field. The default implementation returns a serializer class based on the serializer_field_mapping attribute. .build_relational_field(self, field_name, relation_info) Called to generate a serializer field that maps to a relational model field. The default implementation returns a serializer class based on the serializer_related_field attribute. The relation_info argument is a named tuple, that contains model_field , related_model , to_many and has_through_model properties. .build_nested_field(self, field_name, relation_info, nested_depth) Called to generate a serializer field that maps to a relational model field, when the depth option has been set. The default implementation dynamically creates a nested serializer class based on either ModelSerializer or HyperlinkedModelSerializer . The nested_depth will be the value of the depth option, minus one. The relation_info argument is a named tuple, that contains model_field , related_model , to_many and has_through_model properties. .build_property_field(self, field_name, model_class) Called to generate a serializer field that maps to a property or zero-argument method on the model class. The default implementation returns a ReadOnlyField class. .build_url_field(self, field_name, model_class) Called to generate a serializer field for the serializer's own url field. The default implementation returns a HyperlinkedIdentityField class. .build_unknown_field(self, field_name, model_class) Called when the field name did not map to any model field or model property. The default implementation raises an error, although subclasses may customize this behavior. HyperlinkedModelSerializer The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field. The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field. You can explicitly include the primary key by adding it to the fields option, for example: class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account fields = ['url', 'id', 'account_name', 'users', 'created'] Absolute and relative URLs When instantiating a HyperlinkedModelSerializer you must include the current request in the serializer context, for example: serializer = AccountSerializer(queryset, context={'request': request}) Doing so will ensure that the hyperlinks can include an appropriate hostname, so that the resulting representation uses fully qualified URLs, such as: http://api.example.com/accounts/1/ Rather than relative URLs, such as: /accounts/1/ If you do want to use relative URLs, you should explicitly pass {'request': None} in the serializer context. How hyperlinked views are determined There needs to be a way of determining which views should be used for hyperlinking to model instances. By default hyperlinks are expected to correspond to a view name that matches the style '{model_name}-detail' , and looks up the instance by a pk keyword argument. You can override a URL field view name and lookup field by using either, or both of, the view_name and lookup_field options in the extra_kwargs setting, like so: class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account fields = ['account_url', 'account_name', 'users', 'created'] extra_kwargs = { 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'}, 'users': {'lookup_field': 'username'} } Alternatively you can set the fields on the serializer explicitly. For example: class AccountSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='accounts', lookup_field='slug' ) users = serializers.HyperlinkedRelatedField( view_name='user-detail', lookup_field='username', many=True, read_only=True ) class Meta: model = Account fields = ['url', 'account_name', 'users', 'created'] Tip : Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the repr of a HyperlinkedModelSerializer instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too. Changing the URL field name The name of the URL field defaults to 'url'. You can override this globally, by using the URL_FIELD_NAME setting. ListSerializer The ListSerializer class provides the behavior for serializing and validating multiple objects at once. You won't typically need to use ListSerializer directly, but should instead simply pass many=True when instantiating a serializer. When a serializer is instantiated and many=True is passed, a ListSerializer instance will be created. The serializer class then becomes a child of the parent ListSerializer The following argument can also be passed to a ListSerializer field or a serializer that is passed many=True : allow_empty This is True by default, but can be set to False if you want to disallow empty lists as valid input. Customizing ListSerializer behavior There are a few use cases when you might want to customize the ListSerializer behavior. For example: You want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list. You want to customize the create or update behavior of multiple objects. For these cases you can modify the class that is used when many=True is passed, by using the list_serializer_class option on the serializer Meta class. For example: class CustomListSerializer(serializers.ListSerializer): ... class CustomSerializer(serializers.Serializer): ... class Meta: list_serializer_class = CustomListSerializer Customizing multiple create The default implementation for multiple object creation is to simply call .create() for each item in the list. If you want to customize this behavior, you'll need to customize the .create() method on ListSerializer class that is used when many=True is passed. For example: class BookListSerializer(serializers.ListSerializer): def create(self, validated_data): books = [Book(**item) for item in validated_data] return Book.objects.bulk_create(books) class BookSerializer(serializers.Serializer): ... class Meta: list_serializer_class = BookListSerializer Customizing multiple update By default the ListSerializer class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous. To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind: How do you determine which instance should be updated for each item in the list of data? How should insertions be handled? Are they invalid, or do they create new objects? How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid? How should ordering be handled? Does changing the position of two items imply any state change or is it ignored? You will need to add an explicit id field to the instance serializer. The default implicitly-generated id field is marked as read_only . This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's update method. Here's an example of how you might choose to implement multiple updates: class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} # Perform creations and updates. ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) if book is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(book, data)) # Perform deletions. for book_id, book in book_mapping.items(): if book_id not in data_mapping: book.delete() return ret class BookSerializer(serializers.Serializer): # We need to identify elements in the list using their primary key, # so use a writable field here, rather than the default which would be read-only. id = serializers.IntegerField() ... class Meta: list_serializer_class = BookListSerializer It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the allow_add_remove behavior that was present in REST framework 2. Customizing ListSerializer initialization When a serializer with many=True is instantiated, we need to determine which arguments and keyword arguments should be passed to the .__init__() method for both the child Serializer class, and for the parent ListSerializer class. The default implementation is to pass all arguments to both classes, except for validators , and any custom keyword arguments, both of which are assumed to be intended for the child serializer class. Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when many=True is passed. You can do so by using the many_init class method. @classmethod def many_init(cls, *args, **kwargs): # Instantiate the child serializer. kwargs['child'] = cls() # Instantiate the parent list serializer. return CustomListSerializer(*args, **kwargs) BaseSerializer BaseSerializer class that can be used to easily support alternative serialization and deserialization styles. This class implements the same basic API as the Serializer class: .data - Returns the outgoing primitive representation. .is_valid() - Deserializes and validates incoming data. .validated_data - Returns the validated incoming data. .errors - Returns any errors during validation. .save() - Persists the validated data into an object instance. There are four methods that can be overridden, depending on what functionality you want the serializer class to support: .to_representation() - Override this to support serialization, for read operations. .to_internal_value() - Override this to support deserialization, for write operations. .create() and .update() - Override either or both of these to support saving instances. Because this class provides the same interface as the Serializer class, you can use it with the existing generic class-based views exactly as you would for a regular Serializer or ModelSerializer . The only difference you'll notice when doing so is the BaseSerializer classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input. Read-only BaseSerializer classes To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation() method. Let's take a look at an example using a simple Django model: class HighScore(models.Model): created = models.DateTimeField(auto_now_add=True) player_name = models.CharField(max_length=10) score = models.IntegerField() It's simple to create a read-only serializer for converting HighScore instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer): def to_representation(self, obj): return { 'score': obj.score, 'player_name': obj.player_name } We can now use this class to serialize single HighScore instances: @api_view(['GET']) def high_score(request, pk): instance = HighScore.objects.get(pk=pk) serializer = HighScoreSerializer(instance) return Response(serializer.data) Or use it to serialize multiple instances: @api_view(['GET']) def all_high_scores(request): queryset = HighScore.objects.order_by('-score') serializer = HighScoreSerializer(queryset, many=True) return Response(serializer.data) Read-write BaseSerializer classes To create a read-write serializer we first need to implement a .to_internal_value() method. This method returns the validated values that will be used to construct the object instance, and may raise a serializers.ValidationError if the supplied data is in an incorrect format. Once you've implemented .to_internal_value() , the basic validation API will be available on the serializer, and you will be able to use .is_valid() , .validated_data and .errors . If you want to also support .save() you'll need to also implement either or both of the .create() and .update() methods. Here's a complete example of our previous HighScoreSerializer , that's been updated to support both read and write operations. class HighScoreSerializer(serializers.BaseSerializer): def to_internal_value(self, data): score = data.get('score') player_name = data.get('player_name') # Perform the data validation. if not score: raise serializers.ValidationError({ 'score': 'This field is required.' }) if not player_name: raise serializers.ValidationError({ 'player_name': 'This field is required.' }) if len(player_name) > 10: raise serializers.ValidationError({ 'player_name': 'May not be more than 10 characters.' }) # Return the validated values. This will be available as # the `.validated_data` property. return { 'score': int(score), 'player_name': player_name } def to_representation(self, obj): return { 'score': obj.score, 'player_name': obj.player_name } def create(self, validated_data): return HighScore.objects.create(**validated_data) Creating new base classes The BaseSerializer class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends. The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. class ObjectSerializer(serializers.BaseSerializer): \"\"\" A read-only serializer that coerces arbitrary complex objects into primitive representations. \"\"\" def to_representation(self, obj): output = {} for attribute_name in dir(obj): attribute = getattr(obj, attribute_name) if attribute_name.startswith('_'): # Ignore private attributes. pass elif hasattr(attribute, '__call__'): # Ignore methods and other callables. pass elif isinstance(attribute, (str, int, bool, float, type(None))): # Primitive types can be passed through unmodified. output[attribute_name] = attribute elif isinstance(attribute, list): # Recursively deal with items in lists. output[attribute_name] = [ self.to_representation(item) for item in attribute ] elif isinstance(attribute, dict): # Recursively deal with items in dictionaries. output[attribute_name] = { str(key): self.to_representation(value) for key, value in attribute.items() } else: # Force anything else to its string representation. output[attribute_name] = str(attribute) return output Advanced serializer usage Overriding serialization and deserialization behavior If you need to alter the serialization or deserialization behavior of a serializer class, you can do so by overriding the .to_representation() or .to_internal_value() methods. Some reasons this might be useful include... Adding new behavior for new serializer base classes. Modifying the behavior slightly for an existing class. Improving serialization performance for a frequently accessed API endpoint that returns lots of data. The signatures for these methods are as follows: .to_representation(self, obj) Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API. May be overridden in order modify the representation style. For example: def to_representation(self, instance): \"\"\"Convert `username` to lowercase.\"\"\" ret = super().to_representation(instance) ret['username'] = ret['username'].lower() return ret .to_internal_value(self, data) Takes the unvalidated incoming data as input and should return the validated data that will be made available as serializer.validated_data . The return value will also be passed to the .create() or .update() methods if .save() is called on the serializer class. If any of the validation fails, then the method should raise a serializers.ValidationError(errors) . The errors argument should be a dictionary mapping field names (or settings.NON_FIELD_ERRORS_KEY ) to a list of error messages. If you don't need to alter deserialization behavior and instead want to provide object-level validation, it's recommended that you instead override the .validate() method. The data argument passed to this method will normally be the value of request.data , so the datatype it provides will depend on the parser classes you have configured for your API. Serializer Inheritance Similar to Django forms, you can extend and reuse serializers through inheritance. This allows you to declare a common set of fields or methods on a parent class that can then be used in a number of serializers. For example, class MyBaseSerializer(Serializer): my_field = serializers.CharField() def validate_my_field(self, value): ... class MySerializer(MyBaseSerializer): ... Like Django's Model and ModelForm classes, the inner Meta class on serializers does not implicitly inherit from it's parents' inner Meta classes. If you want the Meta class to inherit from a parent class you must do so explicitly. For example: class AccountSerializer(MyBaseSerializer): class Meta(MyBaseSerializer.Meta): model = Account Typically we would recommend not using inheritance on inner Meta classes, but instead declaring all options explicitly. Additionally, the following caveats apply to serializer inheritance: Normal Python name resolution rules apply. If you have multiple base classes that declare a Meta inner class, only the first one will be used. This means the child\u2019s Meta , if it exists, otherwise the Meta of the first parent, etc. It\u2019s possible to declaratively remove a Field inherited from a parent class by setting the name to be None on the subclass. class MyBaseSerializer(ModelSerializer): my_field = serializers.CharField() class MySerializer(MyBaseSerializer): my_field = None However, you can only use this technique to opt out from a field defined declaratively by a parent class; it won\u2019t prevent the ModelSerializer from generating a default field. To opt-out from default fields, see Specifying which fields to include . Dynamically modifying fields Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the .fields attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer. Modifying the fields argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer. Example For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so: class DynamicFieldsModelSerializer(serializers.ModelSerializer): \"\"\" A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. \"\"\" def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) This would then allow you to do the following: >>> class UserSerializer(DynamicFieldsModelSerializer): >>> class Meta: >>> model = User >>> fields = ['id', 'username', 'email'] >>> >>> print(UserSerializer(user)) {'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'} >>> >>> print(UserSerializer(user, fields=('id', 'email'))) {'id': 2, 'email': 'jon@example.com'} Customizing the default fields REST framework 2 provided an API to allow developers to override how a ModelSerializer class would automatically generate the default set of fields. This API included the .get_field() , .get_pk_field() and other methods. Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change. Third party packages The following third party packages are also available. Django REST marshmallow The django-rest-marshmallow package provides an alternative implementation for serializers, using the python marshmallow library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases. Serpy The serpy package is an alternative implementation for serializers that is built for speed. Serpy serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed. MongoengineModelSerializer The django-rest-framework-mongoengine package provides a MongoEngineModelSerializer serializer class that supports using MongoDB as the storage layer for Django REST framework. GeoFeatureModelSerializer The django-rest-framework-gis package provides a GeoFeatureModelSerializer serializer class that supports GeoJSON both for read and write operations. HStoreSerializer The django-rest-framework-hstore package provides an HStoreSerializer to support django-hstore DictionaryField model field and its schema-mode feature. Dynamic REST The dynamic-rest package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers. Dynamic Fields Mixin The drf-dynamic-fields package provides a mixin to dynamically limit the fields per serializer to a subset specified by an URL parameter. DRF FlexFields The drf-flex-fields package extends the ModelSerializer and ModelViewSet to provide commonly used functionality for dynamically setting fields and expanding primitive fields to nested models, both from URL parameters and your serializer class definitions. Serializer Extensions The django-rest-framework-serializer-extensions package provides a collection of tools to DRY up your serializers, by allowing fields to be defined on a per-view/request basis. Fields can be whitelisted, blacklisted and child serializers can be optionally expanded. HTML JSON Forms The html-json-forms package provides an algorithm and serializer for processing