From 842f82c77a6cbaf607c355c5571ed67448dad98d Mon Sep 17 00:00:00 2001 From: <> Date: Sun, 1 Mar 2026 19:09:33 +0000 Subject: [PATCH] Deployed 8d4c2d0 with MkDocs version: 1.6.1 --- api-guide/pagination/index.html | 9 +++++++++ search/search_index.json | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/api-guide/pagination/index.html b/api-guide/pagination/index.html index 8d1792eb6..fe406e17e 100644 --- a/api-guide/pagination/index.html +++ b/api-guide/pagination/index.html @@ -2734,6 +2734,15 @@ class StandardResultsSetPagination(PageNumberPagination): }
On GenericAPIView subclasses you may also set the pagination_class attribute to select PageNumberPagination on a per-view basis.
By default, the query parameter name used for pagination is page.
+This can be customized by subclassing PageNumberPagination and overriding the page_query_param attribute.
For example:
+from rest_framework.pagination import PageNumberPagination
+
+class CustomPagination(PageNumberPagination):
+ page_query_param = 'p'
+With this configuration, clients would request pages using ?p=2 instead of ?page=2.
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 REST framework is a powerful and flexible toolkit for building Web APIs.
Some reasons you might want to use REST framework:
REST framework requires the following:
We highly recommend and only officially support the latest patch release of each Python and Django series.
The following packages are optional:
Install using pip, including any optional packages you want...
pip install djangorestframework\npip install markdown # Markdown support for the browsable API.\npip install django-filter # Filtering support\n ...or clone the project from github.
git clone https://github.com/encode/django-rest-framework\n Add 'rest_framework' to your INSTALLED_APPS setting.
INSTALLED_APPS = [\n # ...\n \"rest_framework\",\n]\n 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 = [\n # ...\n path(\"api-auth/\", include(\"rest_framework.urls\"))\n]\n Note that the URL path can be whatever you want.
"},{"location":"#example","title":"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 = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n \"DEFAULT_PERMISSION_CLASSES\": [\n \"rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly\"\n ]\n}\n 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.urls import path, include\nfrom django.contrib.auth.models import User\nfrom rest_framework import routers, serializers, viewsets\n\n\n# Serializers define the API representation.\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = [\"url\", \"username\", \"email\", \"is_staff\"]\n\n\n# ViewSets define the view behavior.\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\n# Routers provide an easy way of automatically determining the URL conf.\nrouter = routers.DefaultRouter()\nrouter.register(r\"users\", UserViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n path(\"\", include(router.urls)),\n path(\"api-auth/\", include(\"rest_framework.urls\", namespace=\"rest_framework\")),\n]\n 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.
"},{"location":"#quickstart","title":"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.
"},{"location":"#development","title":"Development","text":"See the Contribution guidelines for information on how to clone the repository, run the test suite and help maintain the code base of REST Framework.
"},{"location":"#support","title":"Support","text":"For support please see the REST framework discussion group, try the #restframework channel on irc.libera.chat, or raise a question on Stack Overflow, making sure to include the 'django-rest-framework' tag.
Please report security issues by emailing security@encode.io.
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
"},{"location":"#license","title":"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.
"},{"location":"api-guide/authentication/","title":"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 several authentication schemes out of the box, and also allows you to implement custom schemes.
Authentication always runs 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 set up the permission policies for your API please see the permissions documentation.
"},{"location":"api-guide/authentication/#how-authentication-is-determined","title":"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.
The default authentication schemes may be set globally, using the DEFAULT_AUTHENTICATION_CLASSES setting. For example.
REST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n ]\n}\n 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\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n authentication_classes = [SessionAuthentication, BasicAuthentication]\n permission_classes = [IsAuthenticated]\n\n def get(self, request, format=None):\n content = {\n 'user': str(request.user), # `django.contrib.auth.User` instance.\n 'auth': str(request.auth), # None\n }\n return Response(content)\n Or, if you're using the @api_view decorator with function based views.
@api_view(['GET'])\n@authentication_classes([SessionAuthentication, BasicAuthentication])\n@permission_classes([IsAuthenticated])\ndef example_view(request, format=None):\n content = {\n 'user': str(request.user), # `django.contrib.auth.User` instance.\n 'auth': str(request.auth), # None\n }\n return Response(content)\n"},{"location":"api-guide/authentication/#unauthorized-and-forbidden-responses","title":"Unauthorized and Forbidden responses","text":"When an unauthenticated request is denied permission there are two different error codes that may be appropriate.
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.
LoginRequiredMiddleware","text":"If you're running Django 5.1+ and use the LoginRequiredMiddleware, please note that all views from DRF are opted-out of this middleware. This is because the authentication in DRF is based on authentication and permissions classes, which may be determined after the middleware has been applied. Additionally, when the request is not authenticated, the middleware redirects the user to the login page, which is not suitable for API requests, where it's preferable to return a 401 status code.
REST framework offers an equivalent mechanism for DRF views via the global settings, DEFAULT_AUTHENTICATION_CLASSES and DEFAULT_PERMISSION_CLASSES. They should be changed accordingly if you need to enforce that API requests are logged in.
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\nWSGIPassAuthorization On\n"},{"location":"api-guide/authentication/#api-reference","title":"API Reference","text":""},{"location":"api-guide/authentication/#basicauthentication","title":"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\"\n 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.
Note
The token authentication provided by Django REST framework is a fairly simple implementation.
For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the Django REST Knox third party package.
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 = [\n ...\n 'rest_framework.authtoken'\n]\n 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\n\ntoken = Token.objects.create(user=...)\nprint(token.key)\n 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\n 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\n 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'\n Note
If you use TokenAuthentication in production you must ensure that your API is only available over https.
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\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom rest_framework.authtoken.models import Token\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n 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\nfrom rest_framework.authtoken.models import Token\n\nfor user in User.objects.all():\n Token.objects.get_or_create(user=user)\n"},{"location":"api-guide/authentication/#by-exposing-an-api-endpoint","title":"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\nurlpatterns += [\n path('api-token-auth/', views.obtain_auth_token)\n]\n 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' }\n 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\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\n\nclass CustomAuthToken(ObtainAuthToken):\n\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data,\n context={'request': request})\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data['user']\n token, created = Token.objects.get_or_create(user=user)\n return Response({\n 'token': token.key,\n 'user_id': user.pk,\n 'email': user.email\n })\n And in your urls.py:
urlpatterns += [\n path('api-token-auth/', CustomAuthToken.as_view())\n]\n"},{"location":"api-guide/authentication/#with-django-admin","title":"With Django admin","text":"It is also possible to create Tokens manually through the 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\n\nTokenAdmin.raw_id_fields = ['user']\n"},{"location":"api-guide/authentication/#using-django-managepy-command","title":"Using Django manage.py command","text":"Since version 3.6.4 it's possible to generate a user token using the following command:
./manage.py drf_create_token <username>\n this command will return the API token for the given user, creating it if it doesn't exist:
Generated token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b for user user1\n 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 <username>\n"},{"location":"api-guide/authentication/#sessionauthentication","title":"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 from 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 behavior is not suitable for login views, which should always have CSRF validation applied.
"},{"location":"api-guide/authentication/#remoteuserauthentication","title":"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 behavior, 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, for example:
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:
None. Any other authentication schemes also in use will still be checked.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.
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\nfrom rest_framework import authentication\nfrom rest_framework import exceptions\n\nclass ExampleAuthentication(authentication.BaseAuthentication):\n def authenticate(self, request):\n username = request.META.get('HTTP_X_USERNAME')\n if not username:\n return None\n\n try:\n user = User.objects.get(username=username)\n except User.DoesNotExist:\n raise exceptions.AuthenticationFailed('No such user')\n\n return (user, None)\n"},{"location":"api-guide/authentication/#third-party-packages","title":"Third party packages","text":"The following third-party packages are also available.
"},{"location":"api-guide/authentication/#django-rest-knox","title":"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).
"},{"location":"api-guide/authentication/#django-oauth-toolkit","title":"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 jazzband and uses the excellent OAuthLib. The package is well documented, and well supported and is currently our recommended package for OAuth 2.0 support.
"},{"location":"api-guide/authentication/#installation-configuration","title":"Installation & configuration","text":"Install using pip.
pip install django-oauth-toolkit\n Add the package to your INSTALLED_APPS and modify your REST framework settings.
INSTALLED_APPS = [\n ...\n 'oauth2_provider',\n]\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',\n ]\n}\n For more details see the Django REST framework - Getting started documentation.
"},{"location":"api-guide/authentication/#django-rest-framework-oauth","title":"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 the REST framework but is now supported and maintained as a third-party package.
"},{"location":"api-guide/authentication/#installation-configuration_1","title":"Installation & configuration","text":"Install the package using pip.
pip install djangorestframework-oauth\n For details on configuration and usage see the Django REST framework OAuth documentation for authentication and permissions.
"},{"location":"api-guide/authentication/#json-web-token-authentication","title":"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.
"},{"location":"api-guide/authentication/#hawk-http-authentication","title":"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).
"},{"location":"api-guide/authentication/#http-signature-authentication","title":"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.
"},{"location":"api-guide/authentication/#djoser","title":"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 uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
"},{"location":"api-guide/authentication/#drf-auth-kit","title":"DRF Auth Kit","text":"DRF Auth Kit library provides a modern REST authentication solution with JWT cookies, social login, multi-factor authentication, and comprehensive user management. The package offers full type safety, automatic OpenAPI schema generation with DRF Spectacular. It supports multiple authentication types (JWT, DRF Token, or Custom) and includes built-in internationalization for 50+ languages.
"},{"location":"api-guide/authentication/#django-rest-auth-dj-rest-auth","title":"django-rest-auth / dj-rest-auth","text":"This 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.
There are currently two forks of this project.
Drf-social-oauth2 is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup.
"},{"location":"api-guide/authentication/#drfpasswordless","title":"drfpasswordless","text":"drfpasswordless adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
"},{"location":"api-guide/authentication/#django-rest-authemail","title":"django-rest-authemail","text":"django-rest-authemail provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included.
"},{"location":"api-guide/authentication/#django-rest-durin","title":"Django-Rest-Durin","text":"Django-Rest-Durin is built with the idea to have one library that does token auth for multiple Web/CLI/Mobile API clients via one interface but allows different token configuration for each API Client that consumes the API. It provides support for multiple tokens per user via custom models, views, permissions that work with Django-Rest-Framework. The token expiration time can be different per API client and is customizable via the Django Admin Interface.
More information can be found in the Documentation.
"},{"location":"api-guide/authentication/#django-pyoidc","title":"django-pyoidc","text":"django_pyoidc adds support for OpenID Connect (OIDC) authentication. This allows you to delegate user management to an Identity Provider, which can be used to implement Single-Sign-On (SSO). It provides support for most uses-cases, such as customizing how token info are mapped to user models, using OIDC audiences for access control, etc.
More information can be found in the Documentation.
"},{"location":"api-guide/caching/","title":"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.
"},{"location":"api-guide/caching/#using-cache-with-apiview-and-viewsets","title":"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, vary_on_cookie and vary_on_headers.
from django.utils.decorators import method_decorator\nfrom django.views.decorators.cache import cache_page\nfrom django.views.decorators.vary import vary_on_cookie, vary_on_headers\n\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework import viewsets\n\n\nclass UserViewSet(viewsets.ViewSet):\n # With cookie: cache requested url for each user for 2 hours\n @method_decorator(cache_page(60 * 60 * 2))\n @method_decorator(vary_on_cookie)\n def list(self, request, format=None):\n content = {\n \"user_feed\": request.user.get_user_feed(),\n }\n return Response(content)\n\n\nclass ProfileView(APIView):\n # With auth: cache requested url for each user for 2 hours\n @method_decorator(cache_page(60 * 60 * 2))\n @method_decorator(vary_on_headers(\"Authorization\"))\n def get(self, request, format=None):\n content = {\n \"user_feed\": request.user.get_user_feed(),\n }\n return Response(content)\n\n\nclass PostView(APIView):\n # Cache page for the requested url\n @method_decorator(cache_page(60 * 60 * 2))\n def get(self, request, format=None):\n content = {\n \"title\": \"Post title\",\n \"body\": \"Post content\",\n }\n return Response(content)\n"},{"location":"api-guide/caching/#using-cache-with-api_view-decorator","title":"Using cache with @api_view decorator","text":"When using @api_view decorator, the Django-provided method-based cache decorators such as cache_page, vary_on_cookie and vary_on_headers can be called directly.
from django.views.decorators.cache import cache_page\nfrom django.views.decorators.vary import vary_on_cookie\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\n\n@cache_page(60 * 15)\n@vary_on_cookie\n@api_view([\"GET\"])\ndef get_user_list(request):\n content = {\"user_feed\": request.user.get_user_feed()}\n return Response(content)\n Note
The cache_page decorator only caches the GET and HEAD responses with status 200.
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.
"},{"location":"api-guide/content-negotiation/#determining-the-accepted-renderer","title":"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.
For example, given the following Accept header:
application/json; indent=4, application/json, application/yaml, text/html, */*\n The priorities for each of the given media types would be:
application/json; indent=4application/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.
"},{"location":"api-guide/content-negotiation/#custom-content-negotiation","title":"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.
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\n\nclass IgnoreClientContentNegotiation(BaseContentNegotiation):\n def select_parser(self, request, parsers):\n \"\"\"\n Select the first parser in the `.parser_classes` list.\n \"\"\"\n return parsers[0]\n\n def select_renderer(self, request, renderers, format_suffix):\n \"\"\"\n Select the first renderer in the `.renderer_classes` list.\n \"\"\"\n return (renderers[0], renderers[0].media_type)\n"},{"location":"api-guide/content-negotiation/#setting-the-content-negotiation","title":"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 = {\n 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation',\n}\n 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\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass NoNegotiationView(APIView):\n \"\"\"\n An example view that does not perform content negotiation.\n \"\"\"\n content_negotiation_class = IgnoreClientContentNegotiation\n\n def get(self, request, format=None):\n return Response({\n 'accepted media type': request.accepted_renderer.media_type\n })\n"},{"location":"api-guide/exceptions/","title":"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
"},{"location":"api-guide/exceptions/#exception-handling-in-rest-framework-views","title":"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:
APIException raised inside REST framework.Http404 exception.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\nAccept: application/json\n Might receive an error response indicating that the DELETE method is not allowed on that resource:
HTTP/1.1 405 Method Not Allowed\nContent-Type: application/json\nContent-Length: 42\n\n{\"detail\": \"Method 'DELETE' not allowed.\"}\n 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.
An example validation error might look like this:
HTTP/1.1 400 Bad Request\nContent-Type: application/json\nContent-Length: 94\n\n{\"amount\": [\"A valid integer is required.\"], \"description\": [\"This field may not be blank.\"]}\n"},{"location":"api-guide/exceptions/#custom-exception-handling","title":"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\nContent-Type: application/json\nContent-Length: 62\n\n{\"status_code\": 405, \"detail\": \"Method 'DELETE' not allowed.\"}\n In order to alter the style of the response, you could write the following custom exception handler:
from rest_framework.views import exception_handler\n\ndef custom_exception_handler(exc, context):\n # Call REST framework's default exception handler first,\n # to get the standard error response.\n response = exception_handler(exc, context)\n\n #\u00a0Now add the HTTP status code to the response.\n if response is not None:\n response.data['status_code'] = response.status_code\n\n return response\n 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 = {\n 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'\n}\n If not specified, the 'EXCEPTION_HANDLER' setting defaults to the standard exception handler provided by REST framework:
REST_FRAMEWORK = {\n 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'\n}\n 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.
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\n\nclass ServiceUnavailable(APIException):\n status_code = 503\n default_detail = 'Service temporarily unavailable, try again later.'\n default_code = 'service_unavailable'\n"},{"location":"api-guide/exceptions/#inspecting-api-exceptions","title":"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)\nYou do not have permission to perform this action.\n>>> print(exc.get_codes())\npermission_denied\n>>> print(exc.get_full_details())\n{'message':'You do not have permission to perform this action.','code':'permission_denied'}\n In the case of validation errors the error detail will be either a list or dictionary of items:
>>> print(exc.detail)\n{\"name\":\"This field is required.\",\"age\":\"A valid integer is required.\"}\n>>> print(exc.get_codes())\n{\"name\":\"required\",\"age\":\"invalid\"}\n>>> print(exc.get_full_details())\n{\"name\":{\"message\":\"This field is required.\",\"code\":\"required\"},\"age\":{\"message\":\"A valid integer is required.\",\"code\":\"invalid\"}}\n"},{"location":"api-guide/exceptions/#parseerror","title":"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\".
"},{"location":"api-guide/exceptions/#authenticationfailed","title":"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.
"},{"location":"api-guide/exceptions/#notauthenticated","title":"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.
"},{"location":"api-guide/exceptions/#permissiondenied","title":"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\".
"},{"location":"api-guide/exceptions/#notfound","title":"NotFound","text":"Signature: NotFound(detail=None, code=None)
Raised when a resource does not exist 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\".
"},{"location":"api-guide/exceptions/#methodnotallowed","title":"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\".
"},{"location":"api-guide/exceptions/#notacceptable","title":"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\".
"},{"location":"api-guide/exceptions/#unsupportedmediatype","title":"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\".
"},{"location":"api-guide/exceptions/#throttled","title":"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\".
"},{"location":"api-guide/exceptions/#validationerror","title":"ValidationError","text":"Signature: ValidationError(detail=None, code=None)
The ValidationError exception is slightly different from the other APIException classes:
detail argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the validate() method of a serializer. For example. raise serializers.ValidationError({'name': 'Please enter a valid name.'})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)\n 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\".
"},{"location":"api-guide/exceptions/#generic-error-views","title":"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.
"},{"location":"api-guide/exceptions/#rest_frameworkexceptionsserver_error","title":"rest_framework.exceptions.server_error","text":"Returns a response with status code 500 and application/json content type.
Set as handler500:
handler500 = 'rest_framework.exceptions.server_error'\n"},{"location":"api-guide/exceptions/#rest_frameworkexceptionsbad_request","title":"rest_framework.exceptions.bad_request","text":"Returns a response with status code 400 and application/json content type.
Set as handler400:
handler400 = 'rest_framework.exceptions.bad_request'\n"},{"location":"api-guide/exceptions/#third-party-packages","title":"Third party packages","text":"The following third-party packages are also available.
"},{"location":"api-guide/exceptions/#drf-standardized-errors","title":"DRF Standardized Errors","text":"The drf-standardized-errors package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.
"},{"location":"api-guide/fields/","title":"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.<FieldName>.
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:
"},{"location":"api-guide/fields/#read_only","title":"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
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
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. If you're using Model Serializer, the default value will be False when you have specified a default, or when the corresponding Model field has blank=True or null=True and is not part of a unique constraint at the same time. (Note that without a default value, unique constraints will cause the field to be required.)
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 behavior 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 requires_context = True attribute, then the serializer field will be passed as an argument.
For example:
class CurrentUserDefault:\n \"\"\"\n May be applied as a `default=...` value on a serializer field.\n Returns the current user.\n \"\"\"\n requires_context = True\n\n def __call__(self, serializer_field):\n return serializer_field.context['request'].user\n When serializing the instance, default will be used if 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","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
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. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example:
class CommentSerializer(serializers.Serializer):\n email = serializers.EmailField(source=\"user.email\")\n This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using prefetch_related and select_related methods appropriately. For more information about the methods refer to django documentation.
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.
"},{"location":"api-guide/fields/#validators","title":"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.
error_messages","text":"A dictionary of error codes to error messages.
"},{"location":"api-guide/fields/#label","title":"label","text":"A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
"},{"location":"api-guide/fields/#help_text","title":"help_text","text":"A text string that may be used as a description of the field in HTML form fields or other descriptive elements.
"},{"location":"api-guide/fields/#initial","title":"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\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n day = serializers.DateField(initial=datetime.date.today)\n"},{"location":"api-guide/fields/#style","title":"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 <input type=\"password\"> for the input.\npassword = serializers.CharField(\n style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'green', 'blue'],\n style={'base_template': 'radio.html'}\n)\n For more details see the HTML & Forms documentation.
"},{"location":"api-guide/fields/#boolean-fields","title":"Boolean fields","text":""},{"location":"api-guide/fields/#booleanfield","title":"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 behavior 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()
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.
A text representation, validates the text to be a valid email address.
Corresponds to django.db.models.fields.EmailField
Signature: EmailField(max_length=None, min_length=None, allow_blank=False)
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.
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)
A RegexField that validates the input against a URL matching pattern. Expects fully qualified URLs of the form http://<host>/<path>.
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)
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\"\n 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_valueA 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.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'.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.A biginteger representation.
Corresponds to django.db.models.fields.BigIntegerField.
Signature: BigIntegerField(max_value=None, min_value=None, coerce_to_string=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.coerce_to_string Set to True if string values should be returned for the representation, or False if BigInteger objects should be returned. Defaults to the same value as the COERCE_BIGINT_TO_STRING settings key, which will be False unless overridden. If BigInteger objects are returned by the serializer, then the final output format will be determined by the renderer.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.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. Should be an integer or Decimal object.min_value Validate that the number provided is no less than this value. Should be an integer or Decimal object.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 quantizing to the configured precision. Valid values are decimal module rounding modes. Defaults to None.normalize_output Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without losing data. Defaults to False.To validate numbers up to 999 with a resolution of 2 decimal places, you would use:
serializers.DecimalField(max_digits=5, decimal_places=2)\n 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)\n"},{"location":"api-guide/fields/#date-and-time-fields","title":"Date and time fields","text":""},{"location":"api-guide/fields/#datetimefield","title":"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 tzinfo subclass (zoneinfo or pytz) 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.","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 be determined by the renderer class.
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):\n created = serializers.DateTimeField()\n\n class Meta:\n model = Comment\n"},{"location":"api-guide/fields/#datefield","title":"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'].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')
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","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')
A Duration representation. Corresponds to django.db.models.fields.DurationField
The validated_data for these fields will contain a datetime.timedelta instance.
Signature: DurationField(format=api_settings.DURATION_FORMAT, max_value=None, min_value=None)
format - A string representing the output format. If not specified, this defaults to the same value as the DURATION_FORMAT settings key, which will be 'django' unless set. Formats are described below. Setting this value to None indicates that Python timedelta objects should be returned by to_representation. In this case the date encoding will be determined by the renderer.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.DurationField formats","text":"Format may either be the special string 'iso-8601', which indicates that ISO 8601 style intervals should be used (eg 'P4DT1H15M20S'), or 'django' which indicates that Django interval format '[DD] [HH:[MM:]]ss[.uuuuuu]' should be used (eg: '4 1:15:20').
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.
A field that can accept a list of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. to_internal_value returns a list containing the selected values, deduplicated.
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.
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.
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.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.
A field class that validates a list of objects.
Signature: ListField(child=<A_FIELD_INSTANCE>, 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(\n child=serializers.IntegerField(min_value=0, max_value=100)\n)\n The ListField class also supports a declarative style that allows you to write reusable list field classes.
class StringListField(serializers.ListField):\n child = serializers.CharField()\n We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it.
A field class that validates a dictionary of objects. The keys in DictField are always assumed to be string values.
Signature: DictField(child=<A_FIELD_INSTANCE>, 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())\n You can also use the declarative style, as with ListField. For example:
class DocumentField(DictField):\n child = CharField()\n"},{"location":"api-guide/fields/#hstorefield","title":"HStoreField","text":"A preconfigured DictField that is compatible with Django's postgres HStoreField.
Signature: HStoreField(child=<A_FIELD_INSTANCE>, 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.
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.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):\n class Meta:\n model = Account\n fields = ['id', 'account_name', 'has_expired']\n"},{"location":"api-guide/fields/#hiddenfield","title":"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)\n 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.
Note
HiddenField() does not appear in partial=True serializer (when making PATCH request).
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=<Django ModelField instance>)
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'))
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_<field_name>.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\nfrom django.utils.timezone import now\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.ModelSerializer):\n days_since_joined = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n fields = '__all__'\n\n def get_days_since_joined(self, obj):\n return (now() - obj.date_joined).days\n"},{"location":"api-guide/fields/#custom-fields","title":"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.
Let's look at an example of serializing a class that represents an RGB color value:
class Color:\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red >= 0 and green >= 0 and blue >= 0)\n assert(red < 256 and green < 256 and blue < 256)\n self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n \"\"\"\n Color objects are serialized into 'rgb(#, #, #)' notation.\n \"\"\"\n def to_representation(self, value):\n return \"rgb(%d, %d, %d)\" % (value.red, value.green, value.blue)\n\n def to_internal_value(self, data):\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n return Color(red, green, blue)\n 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):\n def get_attribute(self, instance):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return instance\n\n def to_representation(self, value):\n \"\"\"\n Serialize the value's class name.\n \"\"\"\n return value.__class__.__name__\n"},{"location":"api-guide/fields/#raising-validation-errors","title":"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):\n if not isinstance(data, str):\n msg = 'Incorrect type. Expected a string, but got %s'\n raise ValidationError(msg % type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col > 255 or col < 0 for col in (red, green, blue)]):\n raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n return Color(red, green, blue)\n The .fail() method is a shortcut for raising ValidationError that takes a message string from the error_messages dictionary. For example:
default_error_messages = {\n 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n 'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n if not isinstance(data, str):\n self.fail('incorrect_type', input_type=type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n self.fail('incorrect_format')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col > 255 or col < 0 for col in (red, green, blue)]):\n self.fail('out_of_range')\n\n return Color(red, green, blue)\n This style keeps your error messages cleaner and more separated from your code, and should be preferred.
"},{"location":"api-guide/fields/#using-source","title":"Usingsource='*'","text":"Here we'll take an example of a flat DataPoint model with x_coordinate and y_coordinate attributes.
class DataPoint(models.Model):\n label = models.CharField(max_length=50)\n x_coordinate = models.SmallIntegerField()\n y_coordinate = models.SmallIntegerField()\n Using a custom field and source='*' we can provide a nested representation of the coordinate pair:
class CoordinateField(serializers.Field):\n\n def to_representation(self, value):\n ret = {\n \"x\": value.x_coordinate,\n \"y\": value.y_coordinate\n }\n return ret\n\n def to_internal_value(self, data):\n ret = {\n \"x_coordinate\": data[\"x\"],\n \"y_coordinate\": data[\"y\"],\n }\n return ret\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = CoordinateField(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates']\n 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 serializer 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)\n>>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})])\n 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 = {\n... \"label\": \"Second Example\",\n... \"coordinates\": {\n... \"x\": 3,\n... \"y\": 4,\n... }\n... }\n>>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'Second Example'),\n ('y_coordinate', 4),\n ('x_coordinate', 3)])\n For completeness let's do the same thing again but with the nested serializer approach suggested above:
class NestedCoordinateSerializer(serializers.Serializer):\n x = serializers.IntegerField(source='x_coordinate')\n y = serializers.IntegerField(source='y_coordinate')\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = NestedCoordinateSerializer(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates']\n 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 behavior as the custom field approach.
Serializing:
>>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'testing'),\n ('coordinates', OrderedDict([('x', 1), ('y', 2)]))])\n Deserializing:
>>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'still testing'),\n ('x_coordinate', 3),\n ('y_coordinate', 4)])\n But we also get the built-in validation for free:
>>> invalid_data = {\n... \"label\": \"still testing\",\n... \"coordinates\": {\n... \"x\": 'a',\n... \"y\": 'b',\n... }\n... }\n>>> invalid_serializer = DataPointSerializer(data=invalid_data)\n>>> invalid_serializer.is_valid()\nFalse\n>>> invalid_serializer.errors\nReturnDict([('coordinates',\n {'x': ['A valid integer is required.'],\n 'y': ['A valid integer is required.']})])\n For this reason, the nested serializer approach would be the first to try. You would use the custom field approach when the nested serializer becomes infeasible or overly complex.
"},{"location":"api-guide/fields/#third-party-packages","title":"Third party packages","text":"The following third party packages are also available.
"},{"location":"api-guide/fields/#drf-compound-fields","title":"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.
The drf-extra-fields package provides extra serializer fields for REST framework, including Base64ImageField and PointField classes.
the djangorestframework-recursive package provides a RecursiveField for serializing and deserializing recursive structures
The django-rest-framework-gis package provides geographic addons for django rest framework like a GeometryField field and a GeoJSON serializer.
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.
"},{"location":"api-guide/filtering/#filtering-against-the-current-user","title":"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\nfrom myapp.serializers import PurchaseSerializer\nfrom rest_framework import generics\n\nclass PurchaseList(generics.ListAPIView):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the purchases\n for the currently authenticated user.\n \"\"\"\n user = self.request.user\n return Purchase.objects.filter(purchaser=user)\n"},{"location":"api-guide/filtering/#filtering-against-the-url","title":"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:
re_path('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),\n You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
class PurchaseList(generics.ListAPIView):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the purchases for\n the user as determined by the username portion of the URL.\n \"\"\"\n username = self.kwargs['username']\n return Purchase.objects.filter(purchaser__username=username)\n"},{"location":"api-guide/filtering/#filtering-against-query-parameters","title":"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):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n Optionally restricts the returned purchases to a given user,\n by filtering against a `username` query parameter in the URL.\n \"\"\"\n queryset = Purchase.objects.all()\n username = self.request.query_params.get('username')\n if username is not None:\n queryset = queryset.filter(purchaser__username=username)\n return queryset\n"},{"location":"api-guide/filtering/#generic-filtering","title":"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.
"},{"location":"api-guide/filtering/#setting-filter-backends","title":"Setting filter backends","text":"The default filter backends may be set globally, using the DEFAULT_FILTER_BACKENDS setting. For example.
REST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']\n}\n 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\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import generics\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = [django_filters.rest_framework.DjangoFilterBackend]\n"},{"location":"api-guide/filtering/#filtering-and-object-lookups","title":"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\n"},{"location":"api-guide/filtering/#overriding-the-initial-queryset","title":"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):\n \"\"\"\n Return a list of all the products that the authenticated\n user has ever purchased, with optional filtering.\n \"\"\"\n model = Product\n serializer_class = ProductSerializer\n filterset_class = ProductFilter\n\n def get_queryset(self):\n user = self.request.user\n return user.purchase_set.all()\n"},{"location":"api-guide/filtering/#api-guide","title":"API Guide","text":""},{"location":"api-guide/filtering/#djangofilterbackend","title":"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.
pip install django-filter\n Then add 'django_filters' to Django's INSTALLED_APPS:
INSTALLED_APPS = [\n ...\n 'django_filters',\n ...\n]\n You should now either add the filter backend to your settings:
REST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']\n}\n Or add the filter backend to an individual View or ViewSet.
from django_filters.rest_framework import DjangoFilterBackend\n\nclass UserListView(generics.ListAPIView):\n ...\n filter_backends = [DjangoFilterBackend]\n 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):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n filter_backends = [DjangoFilterBackend]\n filterset_fields = ['category', 'in_stock']\n 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\n For more advanced filtering requirements you can specify a FilterSet class that should be used by the view. You can read more about FilterSets in the django-filter documentation. It's also recommended that you read the section on DRF integration.
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\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = [filters.SearchFilter]\n search_fields = ['username', 'email']\n This will allow the client to filter the items in the list by making queries such as:
http://example.com/api/users?search=russell\n 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']\n For JSONField and HStoreField fields you can filter based on nested values within the data structure using the same double-underscore notation:
search_fields = ['data__breed', 'data__owner__other_pets__0__name']\n 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. Searches may contain quoted phrases with spaces, each phrase is considered as a single search term.
The search behavior may be specified by prefixing field names in search_fields with one of the following characters (which is equivalent to adding __<lookup> to the field):
^ istartswith Starts-with search. = iexact Exact matches. $ iregex Regex search. @ search Full-text search (Currently only supported Django's PostgreSQL backend). None icontains Contains search (Default). For example:
search_fields = ['=username', '=email']\n By default, the search parameter is named 'search', but this may be overridden with the SEARCH_PARAM setting in the REST_FRAMEWORK configuration.
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\n\nclass CustomSearchFilter(filters.SearchFilter):\n def get_search_fields(self, view, request):\n if request.query_params.get('title_only'):\n return ['title']\n return super().get_search_fields(view, request)\n For more details, see the Django documentation.
"},{"location":"api-guide/filtering/#orderingfilter","title":"OrderingFilter","text":"The OrderingFilter class supports simple query parameter controlled ordering of results.
By default, the query parameter is named 'ordering', but this may be overridden with the ORDERING_PARAM setting in the REST_FRAMEWORK configuration.
For example, to order users by username:
http://example.com/api/users?ordering=username\n The client may also specify reverse orderings by prefixing the field name with '-', like so:
http://example.com/api/users?ordering=-username\n Multiple orderings may also be specified:
http://example.com/api/users?ordering=account,username\n"},{"location":"api-guide/filtering/#specifying-which-fields-may-be-ordered-against","title":"Specifying which fields may be ordered against","text":"It's recommended that you explicitly specify which fields the API should allow in the ordering filter. You can do this by setting an ordering_fields attribute on the view, like so:
class UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = [filters.OrderingFilter]\n ordering_fields = ['username', 'email']\n 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):\n queryset = Booking.objects.all()\n serializer_class = BookingSerializer\n filter_backends = [filters.OrderingFilter]\n ordering_fields = '__all__'\n"},{"location":"api-guide/filtering/#specifying-a-default-ordering","title":"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):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = [filters.OrderingFilter]\n ordering_fields = ['username', 'email']\n ordering = ['username']\n The ordering attribute may be either a string or a list/tuple of strings.
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.
"},{"location":"api-guide/filtering/#example","title":"Example","text":"For example, you might need to restrict users to only being able to see objects they created.
class IsOwnerFilterBackend(filters.BaseFilterBackend):\n \"\"\"\n Filter that only allows users to see their own objects.\n \"\"\"\n def filter_queryset(self, request, queryset, view):\n return queryset.filter(owner=request.user)\n 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.
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.
"},{"location":"api-guide/filtering/#third-party-packages","title":"Third party packages","text":"The following third party packages provide additional filter implementations.
"},{"location":"api-guide/filtering/#django-rest-framework-filters-package","title":"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.
The djangorestframework-word-filter developed as alternative to filters.SearchFilter which will search full word in text, or exact match.
django-url-filter provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django QuerySets.
drf-url-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.
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.
"},{"location":"api-guide/format-suffixes/#format_suffix_patterns","title":"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:
False, meaning that suffixes are optional by default.Example:
from rest_framework.urlpatterns import format_suffix_patterns\nfrom blog import views\n\nurlpatterns = [\n path('', views.apt_root),\n path('comments/', views.comment_list),\n path('comments/<int:pk>/', views.comment_detail)\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])\n 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'])\ndef comment_list(request, format=None):\n # do stuff...\n Or with class-based views:
class CommentList(APIView):\n def get(self, request, format=None):\n # do stuff...\n\n def post(self, request, format=None):\n # do stuff...\n 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.
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:
urlpatterns = [\n \u2026\n]\n\nurlpatterns = i18n_patterns(\n format_suffix_patterns(urlpatterns, allowed=['json', 'html'])\n)\n"},{"location":"api-guide/format-suffixes/#query-parameter-formats","title":"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.
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.
"},{"location":"api-guide/generic-views/","title":"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.
Typically when using the generic views, you'll override the view, and set several class attributes.
from django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import generics\nfrom rest_framework.permissions import IsAdminUser\n\nclass UserList(generics.ListCreateAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = [IsAdminUser]\n For more complex cases you might also want to override various methods on the view class. For example.
class UserList(generics.ListCreateAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = [IsAdminUser]\n\n def list(self, request):\n # Note the use of `get_queryset()` instead of `self.queryset`\n queryset = self.get_queryset()\n serializer = UserSerializer(queryset, many=True)\n return Response(serializer.data)\n For very simple cases you might want to pass through any class attributes using the .as_view() method. For example, your URLconf might include something like the following entry:
path('users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')\n"},{"location":"api-guide/generic-views/#api-reference","title":"API Reference","text":""},{"location":"api-guide/generic-views/#genericapiview","title":"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.
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 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.Base methods:
"},{"location":"api-guide/generic-views/#get_querysetself","title":"get_queryset(self)","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):\n user = self.request.user\n return user.accounts.all()\n Tip
If the serializer_class used in the generic view spans ORM relations, leading to an N+1 problem, you could optimize your queryset in this method using select_related and prefetch_related. To get more information about N+1 problem and use cases of the mentioned methods refer to related section in django documentation.
When listing objects (e.g. using ListAPIView or ModelViewSet), serializers may trigger an N+1 query pattern if related objects are accessed individually for each item.
To prevent this, optimize the queryset in get_queryset() or by setting the queryset class attribute using select_related() and prefetch_related(), depending on the type of relationship.
For ForeignKey and OneToOneField:
Use select_related() to fetch related objects in the same query:
def get_queryset(self):\n return Order.objects.select_related(\"customer\", \"billing_address\")\n For reverse and many-to-many relationships:
Use prefetch_related() to efficiently load collections of related objects:
def get_queryset(self):\n return Book.objects.prefetch_related(\"categories\", \"reviews__user\")\n Combining both:
def get_queryset(self):\n return (\n Order.objects\n .select_related(\"customer\")\n .prefetch_related(\"items__product\")\n )\n These optimizations reduce repeated database access and improve list view performance.
"},{"location":"api-guide/generic-views/#get_objectself","title":"get_object(self)","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):\n queryset = self.get_queryset()\n filter = {}\n for field in self.multiple_lookup_fields:\n filter[field] = self.kwargs[field]\n\n obj = get_object_or_404(queryset, **filter)\n self.check_object_permissions(self.request, obj)\n return obj\n 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)","text":"Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
For example:
def filter_queryset(self, queryset):\n filter_backends = [CategoryFilter]\n\n if 'geo_route' in self.request.query_params:\n filter_backends = [GeoRouteFilter, CategoryFilter]\n elif 'geo_point' in self.request.query_params:\n filter_backends = [GeoPointFilter, CategoryFilter]\n\n for backend in list(filter_backends):\n queryset = backend().filter_queryset(self.request, queryset, view=self)\n\n return queryset\n"},{"location":"api-guide/generic-views/#get_serializer_classself","title":"get_serializer_class(self)","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):\n if self.request.user.is_staff:\n return FullAccountSerializer\n return BasicAccountSerializer\n 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):\n serializer.save(user=self.request.user)\n 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):\n instance = serializer.save()\n send_email_confirmation(user=self.request.user, modified=instance)\n 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):\n queryset = SignupRequest.objects.filter(user=self.request.user)\n if queryset.exists():\n raise ValidationError('You have already signed up')\n serializer.save(user=self.request.user)\n 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.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.
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.
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.
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.
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.
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.
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.
Used for create-only endpoints.
Provides a post method handler.
Extends: GenericAPIView, CreateModelMixin
"},{"location":"api-guide/generic-views/#listapiview","title":"ListAPIView","text":"Used for read-only endpoints to represent a collection of model instances.
Provides a get method handler.
Extends: GenericAPIView, ListModelMixin
"},{"location":"api-guide/generic-views/#retrieveapiview","title":"RetrieveAPIView","text":"Used for read-only endpoints to represent a single model instance.
Provides a get method handler.
Extends: GenericAPIView, RetrieveModelMixin
"},{"location":"api-guide/generic-views/#destroyapiview","title":"DestroyAPIView","text":"Used for delete-only endpoints for a single model instance.
Provides a delete method handler.
Extends: GenericAPIView, DestroyModelMixin
"},{"location":"api-guide/generic-views/#updateapiview","title":"UpdateAPIView","text":"Used for update-only endpoints for a single model instance.
Provides put and patch method handlers.
Extends: GenericAPIView, UpdateModelMixin
"},{"location":"api-guide/generic-views/#listcreateapiview","title":"ListCreateAPIView","text":"Used for read-write endpoints to represent a collection of model instances.
Provides get and post method handlers.
Extends: GenericAPIView, ListModelMixin, CreateModelMixin
"},{"location":"api-guide/generic-views/#retrieveupdateapiview","title":"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
"},{"location":"api-guide/generic-views/#retrievedestroyapiview","title":"RetrieveDestroyAPIView","text":"Used for read or delete endpoints to represent a single model instance.
Provides get and delete method handlers.
Extends: GenericAPIView, RetrieveModelMixin, DestroyModelMixin
"},{"location":"api-guide/generic-views/#retrieveupdatedestroyapiview","title":"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
"},{"location":"api-guide/generic-views/#customizing-the-generic-views","title":"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.
"},{"location":"api-guide/generic-views/#creating-custom-mixins","title":"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:\n \"\"\"\n Apply this mixin to any view or viewset to get multiple field filtering\n based on a `lookup_fields` attribute, instead of the default single field filtering.\n \"\"\"\n def get_object(self):\n queryset = self.get_queryset() # Get the base queryset\n queryset = self.filter_queryset(queryset) # Apply any filter backends\n filter = {}\n for field in self.lookup_fields:\n if self.kwargs.get(field): # Ignore empty fields.\n filter[field] = self.kwargs[field]\n obj = get_object_or_404(queryset, **filter) # Lookup the object\n self.check_object_permissions(self.request, obj)\n return obj\n 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):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n lookup_fields = ['account', 'username']\n Using custom mixins is a good option if you have custom behavior that needs to be used.
"},{"location":"api-guide/generic-views/#creating-custom-base-classes","title":"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,\n generics.RetrieveAPIView):\n pass\n\nclass BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,\n generics.RetrieveUpdateDestroyAPIView):\n pass\n 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.
"},{"location":"api-guide/generic-views/#put-as-create","title":"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.
The following third party packages provide additional generic view implementations.
"},{"location":"api-guide/generic-views/#django-rest-multiple-models","title":"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.
"},{"location":"api-guide/metadata/","title":"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\nAllow: GET, POST, HEAD, OPTIONS\nContent-Type: application/json\n\n{\n \"name\": \"To Do List\",\n \"description\": \"List existing 'To Do' items, or create a new item.\",\n \"renders\": [\n \"application/json\",\n \"text/html\"\n ],\n \"parses\": [\n \"application/json\",\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\"\n ],\n \"actions\": {\n \"POST\": {\n \"note\": {\n \"type\": \"string\",\n \"required\": false,\n \"read_only\": false,\n \"label\": \"title\",\n \"max_length\": 100\n }\n }\n }\n}\n"},{"location":"api-guide/metadata/#setting-the-metadata-scheme","title":"Setting the metadata scheme","text":"You can set the metadata class globally using the 'DEFAULT_METADATA_CLASS' settings key:
REST_FRAMEWORK = {\n 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata'\n}\n Or you can set the metadata class individually for a view:
class APIRoot(APIView):\n metadata_class = APIRootMetadata\n\n def get(self, request, format=None):\n return Response({\n ...\n })\n 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.
If you have specific requirements for creating schema endpoints that are accessed with regular GET requests, you might consider reusing 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)\ndef api_schema(self, request):\n meta = self.metadata_class()\n data = meta.determine_metadata(request, self)\n return Response(data)\n There are a couple of reasons that you might choose to take this approach, including that OPTIONS responses are not cacheable.
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.
"},{"location":"api-guide/metadata/#example","title":"Example","text":"The following class could be used to limit the information that is returned to OPTIONS requests.
class MinimalMetadata(BaseMetadata):\n \"\"\"\n Don't include field and other information for `OPTIONS` requests.\n Just return the name and description.\n \"\"\"\n def determine_metadata(self, request, view):\n return {\n 'name': view.get_view_name(),\n 'description': view.get_view_description()\n }\n Then configure your settings to use this custom class:
REST_FRAMEWORK = {\n 'DEFAULT_METADATA_CLASS': 'myproject.apps.core.MinimalMetadata'\n}\n"},{"location":"api-guide/metadata/#third-party-packages","title":"Third party packages","text":"The following third party packages provide additional metadata implementations.
"},{"location":"api-guide/metadata/#drf-schema-adapter","title":"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.
"},{"location":"api-guide/pagination/","title":"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:
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.
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 = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',\n 'PAGE_SIZE': 100\n}\n 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.
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):\n page_size = 1000\n page_size_query_param = 'page_size'\n max_page_size = 10000\n\nclass StandardResultsSetPagination(PageNumberPagination):\n page_size = 100\n page_size_query_param = 'page_size'\n max_page_size = 1000\n You can then apply your new style to a view using the pagination_class attribute:
class BillingRecordsView(generics.ListAPIView):\n queryset = Billing.objects.all()\n serializer_class = BillingRecordsSerializer\n pagination_class = LargeResultsSetPagination\n Or apply the style globally, using the DEFAULT_PAGINATION_CLASS settings key. For example:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination'\n}\n"},{"location":"api-guide/pagination/#api-reference","title":"API Reference","text":""},{"location":"api-guide/pagination/#pagenumberpagination","title":"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\n Response:
HTTP 200 OK\n{\n \"count\": 1023,\n \"next\": \"https://api.example.org/accounts/?page=5\",\n \"previous\": \"https://api.example.org/accounts/?page=3\",\n \"results\": [\n \u2026\n ]\n}\n"},{"location":"api-guide/pagination/#setup","title":"Setup","text":"To enable the PageNumberPagination style globally, use the following configuration, and set the PAGE_SIZE as desired:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n}\n On GenericAPIView subclasses you may also set the pagination_class attribute to select PageNumberPagination on a per-view basis.
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',). For example, use ?page=last to go directly to the last page.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\".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\n Response:
HTTP 200 OK\n{\n \"count\": 1023,\n \"next\": \"https://api.example.org/accounts/?limit=100&offset=500\",\n \"previous\": \"https://api.example.org/accounts/?limit=100&offset=300\",\n \"results\": [\n \u2026\n ]\n}\n"},{"location":"api-guide/pagination/#setup_1","title":"Setup","text":"To enable the LimitOffsetPagination style globally, use the following configuration:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'\n}\n 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.
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\".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:
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.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:
CursorPagination subclass that uses decimals to limit precision is available here.)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.
"},{"location":"api-guide/pagination/#setup_2","title":"Setup","text":"To enable the CursorPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',\n 'PAGE_SIZE': 100\n}\n On GenericAPIView subclasses you may also set the pagination_class attribute to select CursorPagination on a per-view basis.
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\".To create a custom pagination serializer class, you should inherit the subclass pagination.BasePagination, override the paginate_queryset(self, queryset, request, view=None), and get_paginated_response(self, data) methods:
paginate_queryset method is passed to the initial queryset and should return an iterable object. That object contains only the data in the requested page.get_paginated_response method is passed to 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.
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):\n def get_paginated_response(self, data):\n return Response({\n 'links': {\n 'next': self.get_next_link(),\n 'previous': self.get_previous_link()\n },\n 'count': self.page.paginator.count,\n 'results': data\n })\n We'd then need to set up the custom class in our configuration:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination',\n 'PAGE_SIZE': 100\n}\n 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.
To have your custom pagination class be used by default, use the DEFAULT_PAGINATION_CLASS setting:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',\n 'PAGE_SIZE': 100\n}\n 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
"},{"location":"api-guide/pagination/#html-pagination-controls","title":"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.
You can override the templates that render the HTML pagination controls. The two built-in styles are:
rest_framework/pagination/numbers.htmlrest_framework/pagination/previous_and_next.htmlProviding 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.
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.
The following third party packages are also available.
"},{"location":"api-guide/pagination/#drf-extensions","title":"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.
The drf-proxy-pagination package includes a ProxyPagination class which allows to choose pagination class with a query parameter.
The django-rest-framework-link-header-pagination package includes a LinkHeaderPagination class which provides pagination via an HTTP Link header as described in GitHub REST API documentation.
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.
"},{"location":"api-guide/parsers/#how-the-parser-is-determined","title":"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 want.
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.
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 = {\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework.parsers.JSONParser',\n ]\n}\n 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\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n \"\"\"\n A view that can accept POST requests with JSON content.\n \"\"\"\n parser_classes = [JSONParser]\n\n def post(self, request, format=None):\n return Response({'received data': request.data})\n Or, if you're using the @api_view decorator with function based views.
from rest_framework.decorators import api_view\nfrom rest_framework.decorators import parser_classes\nfrom rest_framework.parsers import JSONParser\n\n@api_view(['POST'])\n@parser_classes([JSONParser])\ndef example_view(request, format=None):\n \"\"\"\n A view that can accept POST requests with JSON content.\n \"\"\"\n return Response({'received data': request.data})\n"},{"location":"api-guide/parsers/#api-reference","title":"API Reference","text":""},{"location":"api-guide/parsers/#jsonparser","title":"JSONParser","text":"Parses JSON request content. request.data will be populated with a dictionary of data.
.media_type: application/json
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
Parses multipart HTML form content, which supports file uploads. request.data and request.FILES will be populated with a QueryDict and MultiValueDict respectively.
You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data.
.media_type: multipart/form-data
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: */*
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.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.# views.py\nclass FileUploadView(views.APIView):\n parser_classes = [FileUploadParser]\n\n def put(self, request, filename, format=None):\n file_obj = request.data['file']\n # ...\n # do some stuff with uploaded file\n # ...\n return Response(status=204)\n\n# urls.py\nurlpatterns = [\n # ...\n re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())\n]\n"},{"location":"api-guide/parsers/#custom-parsers","title":"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:
A stream-like object representing the body of the request.
"},{"location":"api-guide/parsers/#media_type","title":"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\".
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.
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):\n \"\"\"\n Plain text parser.\n \"\"\"\n media_type = 'text/plain'\n\n def parse(self, stream, media_type=None, parser_context=None):\n \"\"\"\n Simply return a string representing the body of the request.\n \"\"\"\n return stream.read()\n"},{"location":"api-guide/parsers/#third-party-packages","title":"Third party packages","text":"The following third party packages are also available.
"},{"location":"api-guide/parsers/#yaml","title":"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.
"},{"location":"api-guide/parsers/#installation-configuration","title":"Installation & configuration","text":"Install using pip.
$ pip install djangorestframework-yaml\n Modify your REST framework settings.
REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework_yaml.parsers.YAMLParser',\n ],\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ],\n}\n"},{"location":"api-guide/parsers/#xml","title":"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.
"},{"location":"api-guide/parsers/#installation-configuration_1","title":"Installation & configuration","text":"Install using pip.
$ pip install djangorestframework-xml\n Modify your REST framework settings.
REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework_xml.parsers.XMLParser',\n ],\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework_xml.renderers.XMLRenderer',\n ],\n}\n"},{"location":"api-guide/parsers/#messagepack","title":"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.
"},{"location":"api-guide/parsers/#camelcase-json","title":"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.
"},{"location":"api-guide/permissions/","title":"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.
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 permission checks fail, either a \"403 Forbidden\" or a \"401 Unauthorized\" response will be returned, according to the following rules:
WWW-Authenticate headers. \u2014 An HTTP 403 Forbidden response will be returned.WWW-Authenticate headers. \u2014 An HTTP 401 Unauthorized response, with an appropriate WWW-Authenticate header will be returned.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):\n obj = get_object_or_404(self.get_queryset(), pk=self.kwargs[\"pk\"])\n self.check_object_permissions(self.request, obj)\n return obj\n 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).
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.
Because the get_object() method is not called, object level permissions from the has_object_permission() method are not applied when creating objects. In order to restrict object creation you need to implement the permission check either in your Serializer class or override the perform_create() method of your ViewSet class.
The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting. For example.
REST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.IsAuthenticated',\n ]\n}\n If not specified, this setting defaults to allowing unrestricted access:
'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.AllowAny',\n]\n 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\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n permission_classes = [IsAuthenticated]\n\n def get(self, request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n Or, if you're using the @api_view decorator with function based views.
from rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef example_view(request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n Note
When you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in 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\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ReadOnly(BasePermission):\n def has_permission(self, request, view):\n return request.method in SAFE_METHODS\n\nclass ExampleView(APIView):\n permission_classes = [IsAuthenticated | ReadOnly]\n\n def get(self, request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n Note
Composition of permissions supports the & (and), | (or) and ~ (not) operators, and also allows the use of brackets ( ) to group expressions.
Operators follow the same precedence and associativity rules as standard logical operators (~ highest, then &, then |).
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.
"},{"location":"api-guide/permissions/#isauthenticated","title":"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.
"},{"location":"api-guide/permissions/#isadminuser","title":"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.
"},{"location":"api-guide/permissions/#isauthenticatedorreadonly","title":"IsAuthenticatedOrReadOnly","text":"The IsAuthenticatedOrReadOnly will allow authenticated users to perform any request. Requests for unauthenticated 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.
"},{"location":"api-guide/permissions/#djangomodelpermissions","title":"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 or get_queryset() method. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned. The appropriate model is determined by checking get_queryset().model or queryset.model.
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 behavior 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.
Similar to DjangoModelPermissions, but also allows unauthenticated users to have read-only access to the API.
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.
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:\n # Check permissions for read-only request\nelse:\n # Check permissions for write request\n 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. Similarly, to change the code identifier associated with the exception, implement a code attribute directly on your custom permission - otherwise the default_code attribute from PermissionDenied will be used.
from rest_framework import permissions\n\nclass CustomerAccessPermission(permissions.BasePermission):\n message = 'Adding customers not allowed.'\n\n def has_permission(self, request, view):\n ...\n"},{"location":"api-guide/permissions/#examples","title":"Examples","text":"The following is an example of a permission class that checks the incoming request's IP address against a blocklist, and denies the request if the IP has been blocked.
from rest_framework import permissions\n\nclass BlocklistPermission(permissions.BasePermission):\n \"\"\"\n Global permission check for blocked IPs.\n \"\"\"\n\n def has_permission(self, request, view):\n ip_addr = request.META['REMOTE_ADDR']\n blocked = Blocklist.objects.filter(ip_addr=ip_addr).exists()\n return not blocked\n 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):\n \"\"\"\n Object-level permission to only allow owners of an object to edit it.\n Assumes the model instance has an `owner` attribute.\n \"\"\"\n\n def has_object_permission(self, request, view, obj):\n # Read permissions are allowed to any request,\n # so we'll always allow GET, HEAD or OPTIONS requests.\n if request.method in permissions.SAFE_METHODS:\n return True\n\n # Instance must have an attribute named `owner`.\n return obj.owner == request.user\n 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.
"},{"location":"api-guide/permissions/#overview-of-access-restriction-methods","title":"Overview of access restriction methods","text":"REST framework offers three different methods to customize access restrictions on a case-by-case basis. These apply in different scenarios and have different effects and limitations.
queryset/get_queryset(): Limits the general visibility of existing objects from the database. The queryset limits which objects will be listed and which objects can be modified or deleted. The get_queryset() method can apply different querysets based on the current action.permission_classes/get_permissions(): General permission checks based on the current action, request and targeted object. Object level permissions can only be applied to retrieve, modify and deletion actions. Permission checks for list and create will be applied to the entire object type. (In case of list: subject to restrictions in the queryset.)serializer_class/get_serializer(): Instance level restrictions that apply to all objects on input and output. The serializer may have access to the request context. The get_serializer() method can apply different serializers based on the current action.The following table lists the access restriction methods and the level of control they offer over which actions.
queryset permission_classes serializer_class Action: list global global object-level* Action: create no global object-level Action: retrieve global object-level object-level Action: update global object-level object-level Action: partial_update global object-level object-level Action: destroy global object-level no Can reference action in decision no** yes no** Can reference request in decision no** yes yes * A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned. ** The get_*() methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action.
The following third party packages are also available.
"},{"location":"api-guide/permissions/#drf-access-policy","title":"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.
"},{"location":"api-guide/permissions/#composed-permissions","title":"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.
"},{"location":"api-guide/permissions/#rest-condition","title":"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.
"},{"location":"api-guide/permissions/#dry-rest-permissions","title":"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.
"},{"location":"api-guide/permissions/#django-rest-framework-roles","title":"Django Rest Framework Roles","text":"The Django Rest Framework Roles package makes it easier to parameterize your API over multiple types of users.
"},{"location":"api-guide/permissions/#rest-framework-roles","title":"Rest Framework Roles","text":"The Rest Framework Roles makes it super easy to protect views based on roles. Most importantly allows you to decouple accessibility logic from models and views in a clean human-readable way.
"},{"location":"api-guide/permissions/#django-rest-framework-api-key","title":"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.
"},{"location":"api-guide/permissions/#django-rest-framework-role-filters","title":"Django Rest Framework Role Filters","text":"The Django Rest Framework Role Filters package provides simple filtering over multiple types of roles.
"},{"location":"api-guide/permissions/#django-rest-framework-psq","title":"Django Rest Framework PSQ","text":"The Django Rest Framework PSQ package is an extension that gives support for having action-based permission_classes, serializer_class, and queryset dependent on permission-based rules.
"},{"location":"api-guide/permissions/#axioms-drf-py","title":"Axioms DRF PY","text":"The Axioms DRF PY package is an extension that provides support for authentication and claim-based fine-grained authorization (scopes, roles, groups, permissions, etc. including object-level checks) using JWT tokens issued by an OAuth2/OIDC Authorization Server including AWS Cognito, Auth0, Okta, Microsoft Entra, etc.
"},{"location":"api-guide/relations/","title":"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.<FieldName>.
Note
REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of select_related and prefetch_related since it would be too much magic. A serializer with a field spanning an ORM relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
class AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.SlugRelatedField(\n many=True,\n read_only=True,\n slug_field='title'\n )\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n\n# For each album object, tracks should be fetched from database\nqs = Album.objects.all()\nprint(AlbumSerializer(qs, many=True).data)\n If AlbumSerializer is used to serialize a fairly large queryset with many=True then it could be a serious performance problem. Optimizing the queryset passed to AlbumSerializer with:
qs = Album.objects.prefetch_related('tracks')\n# No additional database hits required\nprint(AlbumSerializer(qs, many=True).data)\n would solve the issue.
"},{"location":"api-guide/relations/#inspecting-relationships","title":"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\n>>> serializer = AccountSerializer()\n>>> print(repr(serializer))\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n"},{"location":"api-guide/relations/#api-reference","title":"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):\n album_name = models.CharField(max_length=100)\n artist = models.CharField(max_length=100)\n\nclass Track(models.Model):\n album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)\n order = models.IntegerField()\n title = models.CharField(max_length=100)\n duration = models.IntegerField()\n\n class Meta:\n unique_together = ['album', 'order']\n ordering = ['order']\n\n def __str__(self):\n return '%d: %s' % (self.order, self.title)\n"},{"location":"api-guide/relations/#stringrelatedfield","title":"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):\n tracks = serializers.StringRelatedField(many=True)\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n Would serialize to the following representation:
{\n 'album_name': 'Things We Lost In The Fire',\n 'artist': 'Low',\n 'tracks': [\n '1: Sunflower',\n '2: Whitetail',\n '3: Dinosaur Act',\n ...\n ]\n}\n This field is read only.
Arguments:
many - If applied to a to-many relationship, you should set this argument to True.PrimaryKeyRelatedField may be used to represent the target of the relationship using its primary key.
For example, the following serializer:
class AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n Would serialize to a representation like this:
{\n 'album_name': 'Undun',\n 'artist': 'The Roots',\n 'tracks': [\n 89,\n 90,\n 91,\n ...\n ]\n}\n 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 may be used to represent the target of the relationship using a hyperlink.
For example, the following serializer:
class AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.HyperlinkedRelatedField(\n many=True,\n read_only=True,\n view_name='track-detail'\n )\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n Would serialize to a representation like this:
{\n 'album_name': 'Graceland',\n 'artist': 'Paul Simon',\n 'tracks': [\n 'http://www.example.com/api/tracks/45/',\n 'http://www.example.com/api/tracks/46/',\n 'http://www.example.com/api/tracks/47/',\n ...\n ]\n}\n 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 <modelname>-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 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):\n tracks = serializers.SlugRelatedField(\n many=True,\n read_only=True,\n slug_field='title'\n )\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n Would serialize to a representation like this:
{\n 'album_name': 'Dear John',\n 'artist': 'Loney Dear',\n 'tracks': [\n 'Airport Surroundings',\n 'Everything Turns to You',\n 'I Was Only Going Out',\n ...\n ]\n}\n 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. requiredqueryset - 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.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):\n track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'track_listing']\n Would serialize to a representation like this:
{\n 'album_name': 'The Eraser',\n 'artist': 'Thom Yorke',\n 'track_listing': 'http://www.example.com/api/track_list/12/',\n}\n 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 <model_name>-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.As opposed to previously discussed references to another entity, the referred entity can instead also be embedded or nested in the representation of the object that refers to it. Such 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.
For example, the following serializer:
class TrackSerializer(serializers.ModelSerializer):\n class Meta:\n model = Track\n fields = ['order', 'title', 'duration']\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackSerializer(many=True, read_only=True)\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n Would serialize to a nested representation like this:
>>> album = Album.objects.create(album_name=\"The Gray Album\", artist='Danger Mouse')\n>>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)\n<Track: Track object>\n>>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)\n<Track: Track object>\n>>> Track.objects.create(album=album, order=3, title='Encore', duration=159)\n<Track: Track object>\n>>> serializer = AlbumSerializer(instance=album)\n>>> serializer.data\n{\n 'album_name': 'The Gray Album',\n 'artist': 'Danger Mouse',\n 'tracks': [\n {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n {'order': 3, 'title': 'Encore', 'duration': 159},\n ...\n ],\n}\n"},{"location":"api-guide/relations/#writable-nested-serializers","title":"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):\n class Meta:\n model = Track\n fields = ['order', 'title', 'duration']\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackSerializer(many=True)\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n\n def create(self, validated_data):\n tracks_data = validated_data.pop('tracks')\n album = Album.objects.create(**validated_data)\n for track_data in tracks_data:\n Track.objects.create(album=album, **track_data)\n return album\n\n>>> data = {\n 'album_name': 'The Gray Album',\n 'artist': 'Danger Mouse',\n 'tracks': [\n {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n {'order': 3, 'title': 'Encore', 'duration': 159},\n ],\n}\n>>> serializer = AlbumSerializer(data=data)\n>>> serializer.is_valid()\nTrue\n>>> serializer.save()\n<Album: Album object>\n"},{"location":"api-guide/relations/#custom-relational-fields","title":"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.
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\n\nclass TrackListingField(serializers.RelatedField):\n def to_representation(self, value):\n duration = time.strftime('%M:%S', time.gmtime(value.duration))\n return 'Track %d: %s (%s)' % (value.order, value.name, duration)\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackListingField(many=True)\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n This custom field would then serialize to the following representation:
{\n 'album_name': 'Sometimes I Wish We Were an Eagle',\n 'artist': 'Bill Callahan',\n 'tracks': [\n 'Track 1: Jim Cain (04:39)',\n 'Track 2: Eid Ma Clack Shaw (04:19)',\n 'Track 3: The Wind and the Dove (04:34)',\n ...\n ]\n}\n"},{"location":"api-guide/relations/#custom-hyperlinked-fields","title":"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.
Say we have a URL for a customer object that takes two keyword arguments, like so:
/api/<organization_slug>/customers/<customer_pk>/\n 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\nfrom rest_framework.reverse import reverse\n\nclass CustomerHyperlink(serializers.HyperlinkedRelatedField):\n # We define these as class attributes, so we don't need to pass them as arguments.\n view_name = 'customer-detail'\n queryset = Customer.objects.all()\n\n def get_url(self, obj, view_name, request, format):\n url_kwargs = {\n 'organization_slug': obj.organization.slug,\n 'customer_pk': obj.pk\n }\n return reverse(view_name, kwargs=url_kwargs, request=request, format=format)\n\n def get_object(self, view_name, view_args, view_kwargs):\n lookup_kwargs = {\n 'organization__slug': view_kwargs['organization_slug'],\n 'pk': view_kwargs['customer_pk']\n }\n return self.get_queryset().get(**lookup_kwargs)\n 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.
"},{"location":"api-guide/relations/#further-notes","title":"Further notes","text":""},{"location":"api-guide/relations/#the-queryset-argument","title":"Thequeryset 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.
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):\n def display_value(self, instance):\n return 'Track: %s' % (instance.title)\n"},{"location":"api-guide/relations/#select-field-cutoffs","title":"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(\n queryset=User.objects.all(),\n slug_field='username',\n style={'base_template': 'input.html'}\n)\n"},{"location":"api-guide/relations/#reverse-relations","title":"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):\n class Meta:\n fields = ['tracks', ...]\n 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):\n album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)\n ...\n 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):\n class Meta:\n fields = ['track_set', ...]\n See the Django documentation on reverse relationships for more details.
"},{"location":"api-guide/relations/#generic-relationships","title":"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):\n \"\"\"\n Tags arbitrary model instances using a generic relation.\n\n See: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/\n \"\"\"\n tag_name = models.SlugField()\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n object_id = models.PositiveIntegerField()\n tagged_object = GenericForeignKey('content_type', 'object_id')\n\n def __str__(self):\n return self.tag_name\n And the following two models, which may have associated tags:
class Bookmark(models.Model):\n \"\"\"\n A bookmark consists of a URL, and 0 or more descriptive tags.\n \"\"\"\n url = models.URLField()\n tags = GenericRelation(TaggedItem)\n\n\nclass Note(models.Model):\n \"\"\"\n A note consists of some text, and 0 or more descriptive tags.\n \"\"\"\n text = models.CharField(max_length=1000)\n tags = GenericRelation(TaggedItem)\n 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):\n \"\"\"\n A custom field to use for the `tagged_object` generic relationship.\n \"\"\"\n\n def to_representation(self, value):\n \"\"\"\n Serialize tagged objects to a simple textual representation.\n \"\"\"\n if isinstance(value, Bookmark):\n return 'Bookmark: ' + value.url\n elif isinstance(value, Note):\n return 'Note: ' + value.text\n raise Exception('Unexpected type of tagged object')\n 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):\n \"\"\"\n Serialize bookmark instances using a bookmark serializer,\n and note instances using a note serializer.\n \"\"\"\n if isinstance(value, Bookmark):\n serializer = BookmarkSerializer(value)\n elif isinstance(value, Note):\n serializer = NoteSerializer(value)\n else:\n raise Exception('Unexpected type of tagged object')\n\n return serializer.data\n 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.
"},{"location":"api-guide/relations/#manytomanyfields-with-a-through-model","title":"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.
"},{"location":"api-guide/relations/#third-party-packages","title":"Third Party Packages","text":"The following third party packages are also available.
"},{"location":"api-guide/relations/#drf-nested-routers","title":"DRF Nested Routers","text":"The drf-nested-routers package provides routers and relationship fields for working with nested resources.
"},{"location":"api-guide/relations/#rest-framework-generic-relations","title":"Rest Framework Generic Relations","text":"The rest-framework-generic-relations library provides read/write serialization for generic foreign keys.
The rest-framework-gm2m-relations library provides read/write serialization for django-gm2m.
"},{"location":"api-guide/renderers/","title":"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.
"},{"location":"api-guide/renderers/#how-the-renderer-is-determined","title":"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.
"},{"location":"api-guide/renderers/#setting-the-renderers","title":"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 = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n ]\n}\n 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\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass UserCountView(APIView):\n \"\"\"\n A view that returns the count of active users in JSON.\n \"\"\"\n renderer_classes = [JSONRenderer]\n\n def get(self, request, format=None):\n user_count = User.objects.filter(active=True).count()\n content = {'user_count': user_count}\n return Response(content)\n Or, if you're using the @api_view decorator with function based views.
@api_view(['GET'])\n@renderer_classes([JSONRenderer])\ndef user_count_view(request, format=None):\n \"\"\"\n A view that returns the count of active users in JSON.\n \"\"\"\n user_count = User.objects.filter(active=True).count()\n content = {'user_count': user_count}\n return Response(content)\n"},{"location":"api-guide/renderers/#ordering-of-renderer-classes","title":"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.
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}\n 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.
{\n \"unicode black star\": \"\u2605\",\n \"value\": 999\n}\n 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
Renders data to HTML, using Django's standard template rendering. Unlike other renderers, the data passed to the Response does not need to be serialized. Also, unlike other renderers, you may want to include a template_name argument when creating the Response.
The TemplateHTMLRenderer will create a RequestContext, using the response.data as the context dict, and determine a template name to use to render the context.
Note
When used with a view that makes use of a serializer the Response sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
response.data = {'results': response.data}\n The template name is determined by (in order of preference):
template_name argument passed to the response..template_name attribute set on this class.view.get_template_names().An example of a view that uses TemplateHTMLRenderer:
class UserDetail(generics.RetrieveAPIView):\n \"\"\"\n A view that returns a templated HTML representation of a given user.\n \"\"\"\n queryset = User.objects.all()\n renderer_classes = [TemplateHTMLRenderer]\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n return Response({'user': self.object}, template_name='user_detail.html')\n 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 prioritized 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
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'])\n@renderer_classes([StaticHTMLRenderer])\ndef simple_html_view(request):\n data = '<html><body><h1>Hello, world</h1></body></html>'\n return Response(data)\n 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
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'
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):\n def get_default_renderer(self, view):\n return JSONRenderer()\n"},{"location":"api-guide/renderers/#adminrenderer","title":"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):\n url = serializers.CharField(source='get_absolute_url', read_only=True)\n\n class Meta:\n model = Account\n .media_type: text/html
.format: 'admin'
.charset: utf-8
.template: 'rest_framework/admin.html'
Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing <form> tags, a hidden CSRF input or any submit buttons.
This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the render_form template tag.
{% load rest_framework %}\n\n<form action=\"/submit-report/\" method=\"post\">\n {% csrf_token %}\n {% render_form serializer %}\n <input type=\"submit\" value=\"Save\" />\n</form>\n For more information see the HTML & Forms documentation.
.media_type: text/html
.format: 'form'
.charset: utf-8
.template: 'rest_framework/horizontal/form.html'
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
To implement a custom renderer, you should override BaseRenderer, set the .media_type and .format properties, and implement the .render(self, data, accepted_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","text":"The request data, as set by the Response() instantiation.
accepted_media_type=None","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\".
renderer_context=None","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.
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_str\nfrom rest_framework import renderers\n\n\nclass PlainTextRenderer(renderers.BaseRenderer):\n media_type = 'text/plain'\n format = 'txt'\n\n def render(self, data, accepted_media_type=None, renderer_context=None):\n return smart_str(data, encoding=self.charset)\n"},{"location":"api-guide/renderers/#setting-the-character-set","title":"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):\n media_type = 'text/plain'\n format = 'txt'\n charset = 'iso-8859-1'\n\n def render(self, data, accepted_media_type=None, renderer_context=None):\n return data.encode(self.charset)\n 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):\n media_type = 'image/jpeg'\n format = 'jpg'\n charset = None\n render_style = 'binary'\n\n def render(self, data, accepted_media_type=None, renderer_context=None):\n return data\n"},{"location":"api-guide/renderers/#advanced-renderer-usage","title":"Advanced renderer usage","text":"You can do some pretty flexible things using REST framework's renderers. Some examples...
media_type = 'image/*', and use the Accept header to vary the encoding of the response.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'])\n@renderer_classes([TemplateHTMLRenderer, JSONRenderer])\ndef list_users(request):\n \"\"\"\n A view that can return JSON or HTML representations\n of the users in the system.\n \"\"\"\n queryset = Users.objects.filter(active=True)\n\n if request.accepted_renderer.format == 'html':\n # TemplateHTMLRenderer takes a context dict,\n # and additionally requires a 'template_name'.\n # It does not require serialization.\n data = {'users': queryset}\n return Response(data, template_name='list_users.html')\n\n # JSONRenderer requires serialized data as normal.\n serializer = UserSerializer(instance=queryset)\n data = serializer.data\n return Response(data)\n"},{"location":"api-guide/renderers/#underspecifying-the-media-type","title":"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')\n"},{"location":"api-guide/renderers/#designing-your-media-types","title":"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.
"},{"location":"api-guide/renderers/#html-error-views","title":"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.
{status_code}.html.api_exception.html.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.
The following third party packages are also available.
"},{"location":"api-guide/renderers/#yaml","title":"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.
"},{"location":"api-guide/renderers/#installation-configuration","title":"Installation & configuration","text":"Install using pip.
$ pip install djangorestframework-yaml\n Modify your REST framework settings.
REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework_yaml.parsers.YAMLParser',\n ],\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ],\n}\n"},{"location":"api-guide/renderers/#xml","title":"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.
"},{"location":"api-guide/renderers/#installation-configuration_1","title":"Installation & configuration","text":"Install using pip.
$ pip install djangorestframework-xml\n Modify your REST framework settings.
REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework_xml.parsers.XMLParser',\n ],\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework_xml.renderers.XMLRenderer',\n ],\n}\n"},{"location":"api-guide/renderers/#jsonp","title":"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.
Install using pip.
$ pip install djangorestframework-jsonp\n Modify your REST framework settings.
REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework_jsonp.renderers.JSONPRenderer',\n ],\n}\n"},{"location":"api-guide/renderers/#messagepack","title":"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.
"},{"location":"api-guide/renderers/#microsoft-excel-xlsx-binary-spreadsheet-endpoints","title":"Microsoft Excel: XLSX (Binary Spreadsheet Endpoints)","text":"XLSX is the world's most popular binary spreadsheet format. Tim Allen of The Wharton School maintains drf-excel, 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.
"},{"location":"api-guide/renderers/#installation-configuration_3","title":"Installation & configuration","text":"Install using pip.
$ pip install drf-excel\n Modify your REST framework settings.
REST_FRAMEWORK = {\n ...\n\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n 'drf_excel.renderers.XLSXRenderer',\n ],\n}\n 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\nfrom drf_excel.mixins import XLSXFileMixin\nfrom drf_excel.renderers import XLSXRenderer\n\nfrom .models import MyExampleModel\nfrom .serializers import MyExampleSerializer\n\nclass MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):\n queryset = MyExampleModel.objects.all()\n serializer_class = MyExampleSerializer\n renderer_classes = [XLSXRenderer]\n filename = 'my_export.xlsx'\n"},{"location":"api-guide/renderers/#csv","title":"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.
"},{"location":"api-guide/renderers/#ultrajson","title":"UltraJSON","text":"UltraJSON is an optimized C JSON encoder which can give significantly faster JSON rendering. Adam Mertz maintains drf_ujson2, a fork of the now unmaintained drf-ujson-renderer, which implements JSON rendering using the UJSON package.
"},{"location":"api-guide/renderers/#camelcase-json","title":"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.
"},{"location":"api-guide/renderers/#pandas-csv-excel-png","title":"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.
Rest Framework Latex provides a renderer that outputs PDFs using Lualatex. It is maintained by Pebble (S/F Software).
"},{"location":"api-guide/requests/","title":"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.
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.
"},{"location":"api-guide/requests/#data","title":".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:
POST, meaning that you can access the content of PUT and PATCH requests.For more details see the parsers documentation.
"},{"location":"api-guide/requests/#query_params","title":".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.
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.
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types.
"},{"location":"api-guide/requests/#accepted_renderer","title":".accepted_renderer","text":"The renderer instance that was selected by the content negotiation stage.
"},{"location":"api-guide/requests/#accepted_media_type","title":".accepted_media_type","text":"A string representing the media type that was accepted by the content negotiation stage.
"},{"location":"api-guide/requests/#authentication","title":"Authentication","text":"REST framework provides flexible, per-request authentication, that gives you the ability to:
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.
"},{"location":"api-guide/requests/#auth","title":".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.
"},{"location":"api-guide/requests/#authenticators","title":".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.
REST framework supports a few browser enhancements such as browser-based PUT, PATCH and DELETE forms.
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.
"},{"location":"api-guide/requests/#content_type","title":".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.
"},{"location":"api-guide/requests/#stream","title":".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.
"},{"location":"api-guide/requests/#standard-httprequest-attributes","title":"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.
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 initialized 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.
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.The unrendered, serialized data of the response.
"},{"location":"api-guide/responses/#status_code","title":".status_code","text":"The numeric status code of the HTTP response.
"},{"location":"api-guide/responses/#content","title":".content","text":"The rendered content of the response. The .render() method must have been called before .content can be accessed.
The template_name, if supplied. Only required if HTMLRenderer or some other custom template renderer is the accepted renderer for the response.
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.
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.
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.
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()\nresponse['Cache-Control'] = 'no-cache'\n"},{"location":"api-guide/responses/#render","title":".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.
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:
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.
"},{"location":"api-guide/reverse/#reverse","title":"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\nfrom rest_framework.views import APIView\nfrom django.utils.timezone import now\n\nclass APIRootView(APIView):\n def get(self, request):\n year = now().year\n data = {\n ...\n 'year-summary-url': reverse('year-summary', args=[year], request=request)\n }\n return Response(data)\n"},{"location":"api-guide/reverse/#reverse_lazy","title":"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)\n"},{"location":"api-guide/routers/","title":"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.
"},{"location":"api-guide/routers/#usage","title":"Usage","text":"Here's an example of a simple URL conf, that uses SimpleRouter.
from rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\nurlpatterns = router.urls\n 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:
^users/$ Name: 'user-list'^users/{pk}/$ Name: 'user-detail'^accounts/$ Name: 'account-list'^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.\n 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.
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()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\n\nurlpatterns = [\n path('forgot-password/', ForgotPasswordFormView.as_view()),\n]\n\nurlpatterns += router.urls\n Alternatively you can use Django's include function, like so...
urlpatterns = [\n path('forgot-password', ForgotPasswordFormView.as_view()),\n path('', include(router.urls)),\n]\n You may use include with an application namespace:
urlpatterns = [\n path('forgot-password/', ForgotPasswordFormView.as_view()),\n path('api/', include((router.urls, 'app_name'))),\n]\n Or both an application and instance namespace:
urlpatterns = [\n path('forgot-password/', ForgotPasswordFormView.as_view()),\n path('api/', include((router.urls, 'app_name'), namespace='instance_name')),\n]\n 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.
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\nfrom rest_framework.decorators import action\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ...\n The following route would be generated:
^users/{pk}/set_password/$'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\nfrom rest_framework.decorators import action\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],\n url_path='change-password', url_name='change_password')\n def set_password(self, request, pk=None):\n ...\n The above example would now generate the following URL pattern:
^users/{pk}/change-password/$'user-change_password'path() with routers","text":"By default, the URLs created by routers use regular expressions. This behavior can be modified by setting the use_regex_path argument to False when instantiating the router, in this case path converters are used. For example:
router = SimpleRouter(use_regex_path=False)\n 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 or lookup_value_converter if using path converters. For example, you can limit the lookup to valid UUIDs:
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):\n lookup_field = 'my_model_id'\n lookup_value_regex = '[0-9a-f]{32}'\n\nclass MyPathModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):\n lookup_field = 'my_model_uuid'\n lookup_value_converter = 'uuid'\n Note that path converters will be used on all URLs registered in the router, including viewset actions.
"},{"location":"api-guide/routers/#api-guide","title":"API Guide","text":""},{"location":"api-guide/routers/#simplerouter","title":"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.
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)\n 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.
"},{"location":"api-guide/routers/#defaultrouter","title":"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.
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)\n"},{"location":"api-guide/routers/#custom-routers","title":"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.
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.
"},{"location":"api-guide/routers/#example","title":"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\n\nclass CustomReadOnlyRouter(SimpleRouter):\n \"\"\"\n A router for read-only APIs, which doesn't use trailing slashes.\n \"\"\"\n routes = [\n Route(\n url=r'^{prefix}$',\n mapping={'get': 'list'},\n name='{basename}-list',\n detail=False,\n initkwargs={'suffix': 'List'}\n ),\n Route(\n url=r'^{prefix}/{lookup}$',\n mapping={'get': 'retrieve'},\n name='{basename}-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n DynamicRoute(\n url=r'^{prefix}/{lookup}/{url_path}$',\n name='{basename}-{url_name}',\n detail=True,\n initkwargs={}\n )\n ]\n Let's take a look at the routes our CustomReadOnlyRouter would generate for a simple viewset.
views.py:
class UserViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n lookup_field = 'username'\n\n @action(detail=True)\n def group_names(self, request, pk=None):\n \"\"\"\n Returns a list of all the group names that the given\n user belongs to.\n \"\"\"\n user = self.get_object()\n groups = user.groups.all()\n return Response([group.name for group in groups])\n urls.py:
router = CustomReadOnlyRouter()\nrouter.register('users', UserViewSet)\nurlpatterns = router.urls\n The following mappings would be generated...
URLHTTP MethodActionURL Name /usersGETlistuser-list /users/{username}GETretrieveuser-detail /users/{username}/group_namesGETgroup_namesuser-group-namesFor another example of setting the .routes attribute, see the source code for the SimpleRouter class.
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.
The following third party packages are also available.
"},{"location":"api-guide/routers/#drf-nested-routers","title":"DRF Nested Routers","text":"The drf-nested-routers package provides routers and relationship fields for working with nested resources.
"},{"location":"api-guide/routers/#modelrouter-wqdbrest","title":"ModelRouter (wq.db.rest)","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\nfrom myapp.models import MyModel\n\nrest.router.register_model(MyModel)\n"},{"location":"api-guide/routers/#drf-extensions","title":"DRF-extensions","text":"The DRF-extensions package provides routers for creating nested viewsets, collection level controllers with customizable endpoint names.
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
Deprecation notice:
REST framework's built-in support for generating OpenAPI schemas is deprecated in favor of 3rd party packages that can provide this functionality instead. The built-in support will be moved into a separate package and then subsequently retired over the next releases.
As a full-fledged replacement, we recommend the drf-spectacular package. It has extensive support for generating OpenAPI 3 schemas from REST framework APIs, with both automatic and customizable options available. For further information please refer to Documenting your API.
API schemas are a useful tool that allow for a range of use cases, including generating reference documentation, or driving dynamic client libraries that can interact with your API.
Django REST Framework provides support for automatic generation of OpenAPI schemas.
"},{"location":"api-guide/schemas/#overview","title":"Overview","text":"Schema generation has several moving parts. It's worth having an overview:
SchemaGenerator is a top-level class that is responsible for walking your configured URL patterns, finding APIView subclasses, enquiring for their schema representation, and compiling the final schema object.AutoSchema encapsulates all the details necessary for per-view schema introspection. Is attached to each view via the schema attribute. You subclass AutoSchema in order to customize your schema.generateschema management command allows you to generate a static schema offline.SchemaView to dynamically generate and serve your schema.settings.DEFAULT_SCHEMA_CLASS allows you to specify an AutoSchema subclass to serve as your project's default.The following sections explain more.
"},{"location":"api-guide/schemas/#generating-an-openapi-schema","title":"Generating an OpenAPI Schema","text":""},{"location":"api-guide/schemas/#install-dependencies","title":"Install dependencies","text":"pip install pyyaml uritemplate inflection\n pyyaml is used to generate schema into YAML-based OpenAPI format.uritemplate is used internally to get parameters in path.inflection is used to pluralize operations more appropriately in the list endpoints.generateschema management command","text":"If your schema is static, you can use the generateschema management command:
./manage.py generateschema --file openapi-schema.yml\n 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.
"},{"location":"api-guide/schemas/#generating-a-dynamic-schema-with-schemaview","title":"Generating a dynamic schema withSchemaView","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\n\nurlpatterns = [\n # ...\n # Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.\n # * `title` and `description` parameters are passed to `SchemaGenerator`.\n # * Provide view name for use with `reverse()`.\n path(\n \"openapi\",\n get_schema_view(\n title=\"Your Project\", description=\"API for all things \u2026\", version=\"1.0.0\"\n ),\n name=\"openapi-schema\",\n ),\n # ...\n]\n"},{"location":"api-guide/schemas/#get_schema_view","title":"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.url: May be used to pass a canonical base URL for the schema.
schema_view = get_schema_view(\n title='Server Monitoring API',\n url='https://www.example.org/api/'\n)\n 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(\n title='Server Monitoring API',\n url='https://www.example.org/api/',\n urlconf='myproject.urls'\n)\n 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 = [\n path('api/', include('myproject.api.urls')),\n]\n\nschema_view = get_schema_view(\n title='Server Monitoring API',\n url='https://www.example.org/api/',\n patterns=schema_url_patterns,\n)\n public: May be used to specify if schema should bypass views permissions. Default to Falsegenerator_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_CLASSESpermission_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.Schema-level customization
from rest_framework.schemas.openapi import SchemaGenerator\n SchemaGenerator is a class that walks a list of routed URL patterns, requests the schema for each view and collates the resulting OpenAPI schema.
Typically you won't need to instantiate SchemaGenerator yourself, but you can do so like so:
generator = SchemaGenerator(title='Stock Prices API')\n Arguments:
title required: The name of the API.description: Longer descriptive text.version: The version of the API. Defaults to 0.1.0.url: The root URL of the API schema. This option is not required unless the schema is included under path prefix.patterns: A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.urlconf: A URL conf module name to use when generating the schema. Defaults to settings.ROOT_URLCONF.In order to customize the top-level schema, subclass rest_framework.schemas.openapi.SchemaGenerator and provide your subclass as an argument to the generateschema command or get_schema_view() helper function.
Returns a dictionary that represents the OpenAPI schema:
generator = SchemaGenerator(title='Stock Prices API')\nschema = generator.get_schema()\n The request argument is optional, and may be used if you want to apply per-user permissions to the resulting schema generation.
This is a good point to override if you want to customize the generated dictionary For example you might wish to add terms of service to the top-level info object:
class TOSSchemaGenerator(SchemaGenerator):\n def get_schema(self, *args, **kwargs):\n schema = super().get_schema(*args, **kwargs)\n schema[\"info\"][\"termsOfService\"] = \"https://example.com/tos.html\"\n return schema\n"},{"location":"api-guide/schemas/#autoschema","title":"AutoSchema","text":"Per-View Customization
from rest_framework.schemas.openapi import AutoSchema\n By default, view introspection is performed by an AutoSchema instance accessible via the schema attribute on APIView.
auto_schema = some_view.schema\n AutoSchema provides the OpenAPI elements needed for each view, request method and path:
components = auto_schema.get_components(...)\noperation = auto_schema.get_operation(...)\n In compiling the schema, SchemaGenerator calls get_components() and get_operation() for each view, allowed method, and path.
Note
The automatic introspection of components, and many operation parameters relies on the relevant attributes and methods of GenericAPIView: get_serializer(), pagination_class, filter_backends, etc. For basic APIView subclasses, default introspection is essentially limited to the URL kwarg path parameters for this reason.
AutoSchema encapsulates the view introspection needed for schema generation. Because of this all the schema generation logic is kept in a single place, rather than being spread around the already extensive view, serializer and field APIs.
Keeping with this pattern, try not to let schema logic leak into your own views, serializers, or fields when customizing the schema generation. You might be tempted to do something like this:
class CustomSchema(AutoSchema):\n \"\"\"\n AutoSchema subclass using schema_extra_info on the view.\n \"\"\"\n\n ...\n\n\nclass CustomView(APIView):\n schema = CustomSchema()\n schema_extra_info = ... # some extra info\n Here, the AutoSchema subclass goes looking for schema_extra_info on the view. This is OK (it doesn't actually hurt) but it means you'll end up with your schema logic spread out in a number of different places.
Instead try to subclass AutoSchema such that the extra_info doesn't leak out into the view:
class BaseSchema(AutoSchema):\n \"\"\"\n AutoSchema subclass that knows how to use extra_info.\n \"\"\"\n\n ...\n\n\nclass CustomSchema(BaseSchema):\n extra_info = ... # some extra info\n\n\nclass CustomView(APIView):\n schema = CustomSchema()\n This style is slightly more verbose but maintains the encapsulation of the schema related code. It's more cohesive in the parlance. It'll keep the rest of your API code more tidy.
If an option applies to many view classes, rather than creating a specific subclass per-view, you may find it more convenient to allow specifying the option as an __init__() kwarg to your base AutoSchema subclass:
class CustomSchema(BaseSchema):\n def __init__(self, **kwargs):\n # store extra_info for later\n self.extra_info = kwargs.pop(\"extra_info\")\n super().__init__(**kwargs)\n\n\nclass CustomView(APIView):\n schema = CustomSchema(extra_info=...) # some extra info\n This saves you having to create a custom subclass per-view for a commonly used option.
Not all AutoSchema methods expose related __init__() kwargs, but those for the more commonly needed options do.
AutoSchema methods","text":""},{"location":"api-guide/schemas/#get_components","title":"get_components()","text":"Generates the OpenAPI components that describe request and response bodies, deriving their properties from the serializer.
Returns a dictionary mapping the component name to the generated representation. By default this has just a single pair but you may override get_components() to return multiple pairs if your view uses multiple serializers.
get_component_name()","text":"Computes the component's name from the serializer.
You may see warnings if your API has duplicate component names. If so you can override get_component_name() or pass the component_name __init__() kwarg (see below) to provide different names.
get_reference()","text":"Returns a reference to the serializer component. This may be useful if you override get_schema().
map_serializer()","text":"Maps serializers to their OpenAPI representations.
Most serializers should conform to the standard OpenAPI object type, but you may wish to override map_serializer() in order to customize this or other serializer-level fields.
map_field()","text":"Maps individual serializer fields to their schema representation. The base implementation will handle the default fields that Django REST Framework provides.
For SerializerMethodField instances, for which the schema is unknown, or custom field subclasses you should override map_field() to generate the correct schema:
class CustomSchema(AutoSchema):\n \"\"\"Extension of ``AutoSchema`` to add support for custom field schemas.\"\"\"\n\n def map_field(self, field):\n # Handle SerializerMethodFields or custom fields here...\n # ...\n return super().map_field(field)\n Authors of third-party packages should aim to provide an AutoSchema subclass, and a mixin, overriding map_field() so that users can easily generate schemas for their custom fields.
get_tags()","text":"OpenAPI groups operations by tags. By default tags taken from the first path segment of the routed URL. For example, a URL like /users/{id}/ will generate the tag users.
You can pass an __init__() kwarg to manually specify tags (see below), or override get_tags() to provide custom logic.
get_operation()","text":"Returns the OpenAPI operation object that describes the endpoint, including path and query parameters for pagination, filtering, and so on.
Together with get_components(), this is the main entry point to the view introspection.
get_operation_id()","text":"There must be a unique operationid for each operation. By default the operationId is deduced from the model name, serializer name or view name. The operationId looks like \"listItems\", \"retrieveItem\", \"updateItem\", etc. The operationId is camelCase by convention.
get_operation_id_base()","text":"If you have several views with the same model name, you may see duplicate operationIds.
In order to work around this, you can override get_operation_id_base() to provide a different base for name part of the ID.
get_serializer()","text":"If the view has implemented get_serializer(), returns the result.
get_request_serializer()","text":"By default returns get_serializer() but can be overridden to differentiate between request and response objects.
get_response_serializer()","text":"By default returns get_serializer() but can be overridden to differentiate between request and response objects.
AutoSchema.__init__() kwargs","text":"AutoSchema provides a number of __init__() kwargs that can be used for common customizations, if the default generated values are not appropriate.
The available kwargs are:
tags: Specify a list of tags.component_name: Specify the component name.operation_id_base: Specify the resource-name part of operation IDs.You pass the kwargs when declaring the AutoSchema instance on your view:
class PetDetailView(generics.RetrieveUpdateDestroyAPIView):\n schema = AutoSchema(\n tags=['Pets'],\n component_name='Pet',\n operation_id_base='Pet',\n )\n ...\n Assuming a Pet model and PetSerializer serializer, the kwargs in this example are probably not needed. Often, though, you'll need to pass the kwargs if you have multiple view targeting the same model, or have multiple views with identically named serializers.
If your views have related customizations that are needed frequently, you can create a base AutoSchema subclass for your project that takes additional __init__() kwargs to save subclassing AutoSchema for each view.
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.
Let's start by creating a simple object we can use for example purposes:
from datetime import datetime\n\nclass Comment:\n def __init__(self, email, content, created=None):\n self.email = email\n self.content = content\n self.created = created or datetime.now()\n\ncomment = Comment(email='leila@example.com', content='foo bar')\n 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\n\nclass CommentSerializer(serializers.Serializer):\n email = serializers.EmailField()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n"},{"location":"api-guide/serializers/#serializing-objects","title":"Serializing objects","text":"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)\nserializer.data\n# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}\n At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into json.
from rest_framework.renderers import JSONRenderer\n\njson = JSONRenderer().render(serializer.data)\njson\n# b'{\"email\":\"leila@example.com\",\"content\":\"foo bar\",\"created\":\"2016-01-27T15:17:10.375877\"}'\n"},{"location":"api-guide/serializers/#deserializing-objects","title":"Deserializing objects","text":"Deserialization is similar. First we parse a stream into Python native datatypes...
import io\nfrom rest_framework.parsers import JSONParser\n\nstream = io.BytesIO(json)\ndata = JSONParser().parse(stream)\n ...then we restore those native datatypes into a dictionary of validated data.
serializer = CommentSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}\n"},{"location":"api-guide/serializers/#saving-instances","title":"Saving instances","text":"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):\n email = serializers.EmailField()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n def create(self, validated_data):\n return Comment(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n return instance\n 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):\n return Comment.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n instance.save()\n return instance\n Now when deserializing data, we can call .save() to return an object instance, based on the validated data.
comment = serializer.save()\n 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.\nserializer = CommentSerializer(data=data)\n\n# .save() will update the existing `comment` instance.\nserializer = CommentSerializer(comment, data=data)\n Both the .create() and .update() methods are optional. You can implement either none, one, or both of them, depending on the use-case for your serializer class.
.save()","text":"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)\n Any additional keyword arguments will be included in the validated_data argument when .create() or .update() are called.
.save() directly.","text":"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):\n email = serializers.EmailField()\n message = serializers.CharField()\n\n def save(self):\n email = self.validated_data['email']\n message = self.validated_data['message']\n send_email(from=email, message=message)\n Note that in the case above we're now having to access the serializer .validated_data property directly.
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'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'email': ['Enter a valid email address.'], 'created': ['This field is required.']}\n 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.
"},{"location":"api-guide/serializers/#raising-an-exception-on-invalid-data","title":"Raising an exception on invalid data","text":"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.\nserializer.is_valid(raise_exception=True)\n"},{"location":"api-guide/serializers/#field-level-validation","title":"Field-level validation","text":"You can specify custom field-level validation by adding .validate_<field_name> methods to your Serializer subclass. These are similar to the .clean_<field_name> methods on Django forms.
These methods take a single argument, which is the field value that requires validation.
Your validate_<field_name> methods should return the validated value or raise a serializers.ValidationError. For example:
from rest_framework import serializers\n\nclass BlogPostSerializer(serializers.Serializer):\n title = serializers.CharField(max_length=100)\n content = serializers.CharField()\n\n def validate_title(self, value):\n \"\"\"\n Check that the blog post is about Django.\n \"\"\"\n if 'django' not in value.lower():\n raise serializers.ValidationError(\"Blog post is not about Django\")\n return value\n Note
If your <field_name> is declared on your serializer with the parameter required=False then this validation step will not take place if the field is not included.
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\n\nclass EventSerializer(serializers.Serializer):\n description = serializers.CharField(max_length=100)\n start = serializers.DateTimeField()\n finish = serializers.DateTimeField()\n\n def validate(self, data):\n \"\"\"\n Check that start is before finish.\n \"\"\"\n if data['start'] > data['finish']:\n raise serializers.ValidationError(\"finish must occur after start\")\n return data\n"},{"location":"api-guide/serializers/#validators","title":"Validators","text":"Individual fields on a serializer can include validators, by declaring them on the field instance, for example:
def multiple_of_ten(value):\n if value % 10 != 0:\n raise serializers.ValidationError('Not a multiple of ten')\n\nclass GameRecord(serializers.Serializer):\n score = serializers.IntegerField(validators=[multiple_of_ten])\n ...\n 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):\n name = serializers.CharField()\n room_number = serializers.ChoiceField(choices=[101, 102, 103, 201])\n date = serializers.DateField()\n\n class Meta:\n # Each room only has one event per day.\n validators = [\n UniqueTogetherValidator(\n queryset=Event.objects.all(),\n fields=['room_number', 'date']\n )\n ]\n For more information see the validators documentation.
"},{"location":"api-guide/serializers/#accessing-the-initial-data-and-instance","title":"Accessing the initial data and instance","text":"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.
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\nserializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True)\n"},{"location":"api-guide/serializers/#dealing-with-nested-objects","title":"Dealing with nested objects","text":"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):\n email = serializers.EmailField()\n username = serializers.CharField(max_length=100)\n\nclass CommentSerializer(serializers.Serializer):\n user = UserSerializer()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n 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):\n user = UserSerializer(required=False) # May be an anonymous user.\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n Similarly if a nested representation should be a list of items, you should pass the many=True flag to the nested serializer.
class CommentSerializer(serializers.Serializer):\n user = UserSerializer(required=False)\n edits = EditItemSerializer(many=True) # A nested list of 'edit' items.\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n"},{"location":"api-guide/serializers/#writable-nested-representations","title":"Writable nested representations","text":"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'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'user': {'email': ['Enter a valid email address.']}, 'created': ['This field is required.']}\n Similarly, the .validated_data property will include nested data structures.
.create() methods for nested representations","text":"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):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ['username', 'email', 'profile']\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user\n"},{"location":"api-guide/serializers/#writing-update-methods-for-nested-representations","title":"Writing .update() methods for nested representations","text":"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?
NULL in the database.Here's an example for an .update() method on our previous UserSerializer class.
def update(self, instance, validated_data):\n profile_data = validated_data.pop('profile')\n # Unless the application properly enforces that this field is\n # always set, the following could raise a `DoesNotExist`, which\n # would need to be handled.\n profile = instance.profile\n\n instance.username = validated_data.get('username', instance.username)\n instance.email = validated_data.get('email', instance.email)\n instance.save()\n\n profile.is_premium_member = profile_data.get(\n 'is_premium_member',\n profile.is_premium_member\n )\n profile.has_support_contract = profile_data.get(\n 'has_support_contract',\n profile.has_support_contract\n )\n profile.save()\n\n return instance\n 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.
"},{"location":"api-guide/serializers/#handling-saving-related-instances-in-model-manager-classes","title":"Handling saving related instances in model manager classes","text":"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):\n ...\n\n def create(self, username, email, is_premium_member=False, has_support_contract=False):\n user = User(username=username, email=email)\n user.save()\n profile = Profile(\n user=user,\n is_premium_member=is_premium_member,\n has_support_contract=has_support_contract\n )\n profile.save()\n return user\n 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):\n return User.objects.create(\n username=validated_data['username'],\n email=validated_data['email'],\n is_premium_member=validated_data['profile']['is_premium_member'],\n has_support_contract=validated_data['profile']['has_support_contract']\n )\n For more details on this approach see the Django documentation on model managers, and this blogpost on using model and manager classes.
"},{"location":"api-guide/serializers/#dealing-with-multiple-objects","title":"Dealing with multiple objects","text":"The Serializer class can also handle serializing or deserializing lists of 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()\nserializer = BookSerializer(queryset, many=True)\nserializer.data\n# [\n# {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},\n# {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},\n# {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}\n# ]\n"},{"location":"api-guide/serializers/#deserializing-multiple-objects","title":"Deserializing multiple objects","text":"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.
"},{"location":"api-guide/serializers/#including-extra-context","title":"Including extra context","text":"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})\nserializer.data\n# {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}\n The context dictionary can be used within any serializer field logic, such as a custom .to_representation() method, by accessing the self.context attribute.
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:
.create() and .update().Declaring a ModelSerializer looks like this:
class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ['id', 'account_name', 'users', 'created']\n 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.
ModelSerializer","text":"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\n>>> serializer = AccountSerializer()\n>>> print(repr(serializer))\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n"},{"location":"api-guide/serializers/#specifying-which-fields-to-include","title":"Specifying which fields to include","text":"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):\n class Meta:\n model = Account\n fields = ['id', 'account_name', 'users', 'created']\n 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):\n class Meta:\n model = Account\n fields = '__all__'\n You can set the exclude attribute to a list of fields to be excluded from the serializer.
For example:
class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n exclude = ['users']\n 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.
The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option:
class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ['id', 'account_name', 'users', 'created']\n depth = 1\n 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.
"},{"location":"api-guide/serializers/#specifying-fields-explicitly","title":"Specifying fields explicitly","text":"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):\n url = serializers.CharField(source='get_absolute_url', read_only=True)\n groups = serializers.PrimaryKeyRelatedField(many=True)\n\n class Meta:\n model = Account\n fields = ['url', 'groups']\n Extra fields can correspond to any property or callable on the model.
"},{"location":"api-guide/serializers/#specifying-read-only-fields","title":"Specifying read only fields","text":"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):\n class Meta:\n model = Account\n fields = ['id', 'account_name', 'users', 'created']\n read_only_fields = ['account_name']\n 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())\n Please review the Validators Documentation for details on the UniqueTogetherValidator and CurrentUserDefault classes.
"},{"location":"api-guide/serializers/#additional-keyword-arguments","title":"Additional keyword arguments","text":"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):\n class Meta:\n model = User\n fields = ['email', 'username', 'password']\n extra_kwargs = {'password': {'write_only': True}}\n\n def create(self, validated_data):\n user = User(\n email=validated_data['email'],\n username=validated_data['username']\n )\n user.set_password(validated_data['password'])\n user.save()\n return user\n 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.
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.
"},{"location":"api-guide/serializers/#customizing-field-mappings","title":"Customizing field mappings","text":"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","text":"A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
"},{"location":"api-guide/serializers/#serializer_related_field","title":"serializer_related_field","text":"This property should be the serializer field class, that is used for relational fields by default.
For ModelSerializer this defaults to serializers.PrimaryKeyRelatedField.
For HyperlinkedModelSerializer this defaults to serializers.HyperlinkedRelatedField.
serializer_url_field","text":"The serializer field class that should be used for any url field on the serializer.
Defaults to serializers.HyperlinkedIdentityField
serializer_choice_field","text":"The serializer field class that should be used for any choice fields on the serializer.
Defaults to serializers.ChoiceField
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)","text":"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)","text":"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)","text":"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)","text":"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)","text":"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)","text":"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.
"},{"location":"api-guide/serializers/#hyperlinkedmodelserializer","title":"HyperlinkedModelSerializer","text":"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):\n class Meta:\n model = Account\n fields = ['url', 'id', 'account_name', 'users', 'created']\n"},{"location":"api-guide/serializers/#absolute-and-relative-urls","title":"Absolute and relative URLs","text":"When instantiating a HyperlinkedModelSerializer you must include the current request in the serializer context, for example:
serializer = AccountSerializer(queryset, context={'request': request})\n 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/\n Rather than relative URLs, such as:
/accounts/1/\n If you do want to use relative URLs, you should explicitly pass {'request': None} in the serializer context.
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):\n class Meta:\n model = Account\n fields = ['url', 'account_name', 'users', 'created']\n extra_kwargs = {\n 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'},\n 'users': {'lookup_field': 'username'}\n }\n Alternatively you can set the fields on the serializer explicitly. For example:
class AccountSerializer(serializers.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='accounts',\n lookup_field='slug'\n )\n users = serializers.HyperlinkedRelatedField(\n view_name='user-detail',\n lookup_field='username',\n many=True,\n read_only=True\n )\n\n class Meta:\n model = Account\n fields = ['url', 'account_name', 'users', 'created']\n 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.
The name of the URL field defaults to 'url'. You can override this globally, by using the URL_FIELD_NAME setting.
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","text":"This is True by default, but can be set to False if you want to disallow empty lists as valid input.
max_length","text":"This is None by default, but can be set to a positive integer if you want to validate that the list contains no more than this number of elements.
min_length","text":"This is None by default, but can be set to a positive integer if you want to validate that the list contains no fewer than this number of elements.
ListSerializer behavior","text":"There are a few use cases when you might want to customize the ListSerializer behavior. For example:
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):\n ...\n\nclass CustomSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = CustomListSerializer\n"},{"location":"api-guide/serializers/#customizing-multiple-create","title":"Customizing multiple create","text":"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):\n def create(self, validated_data):\n books = [Book(**item) for item in validated_data]\n return Book.objects.bulk_create(books)\n\nclass BookSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = BookListSerializer\n"},{"location":"api-guide/serializers/#customizing-multiple-update","title":"Customizing multiple update","text":"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:
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):\n def update(self, instance, validated_data):\n # Maps for id->instance and id->data item.\n book_mapping = {book.id: book for book in instance}\n data_mapping = {item['id']: item for item in validated_data}\n\n # Perform creations and updates.\n ret = []\n for book_id, data in data_mapping.items():\n book = book_mapping.get(book_id, None)\n if book is None:\n ret.append(self.child.create(data))\n else:\n ret.append(self.child.update(book, data))\n\n # Perform deletions.\n for book_id, book in book_mapping.items():\n if book_id not in data_mapping:\n book.delete()\n\n return ret\n\nclass BookSerializer(serializers.Serializer):\n # We need to identify elements in the list using their primary key,\n # so use a writable field here, rather than the default which would be read-only.\n id = serializers.IntegerField()\n ...\n\n class Meta:\n list_serializer_class = BookListSerializer\n"},{"location":"api-guide/serializers/#customizing-listserializer-initialization","title":"Customizing ListSerializer initialization","text":"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\n def many_init(cls, *args, **kwargs):\n # Instantiate the child serializer.\n kwargs['child'] = cls()\n # Instantiate the parent list serializer.\n return CustomListSerializer(*args, **kwargs)\n"},{"location":"api-guide/serializers/#baseserializer","title":"BaseSerializer","text":"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.
BaseSerializer classes","text":"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):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField()\n It's simple to create a read-only serializer for converting HighScore instances into primitive data types.
class HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, instance):\n return {\n 'score': instance.score,\n 'player_name': instance.player_name\n }\n We can now use this class to serialize single HighScore instances:
@api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data)\n Or use it to serialize multiple instances:
@api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)\n"},{"location":"api-guide/serializers/#read-write-baseserializer-classes","title":"Read-write BaseSerializer classes","text":"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):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise serializers.ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise serializers.ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) > 10:\n raise serializers.ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, instance):\n return {\n 'score': instance.score,\n 'player_name': instance.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)\n"},{"location":"api-guide/serializers/#creating-new-base-classes","title":"Creating new base classes","text":"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 complex objects into primitive representations.
class ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, instance):\n output = {}\n for attribute_name in dir(instance):\n attribute = getattr(instance, attribute_name)\n if attribute_name.startswith('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)\n return output\n"},{"location":"api-guide/serializers/#advanced-serializer-usage","title":"Advanced serializer usage","text":""},{"location":"api-guide/serializers/#overriding-serialization-and-deserialization-behavior","title":"Overriding serialization and deserialization behavior","text":"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...
The signatures for these methods are as follows:
"},{"location":"api-guide/serializers/#to_representationself-instance","title":"to_representation(self, instance)","text":"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 to modify the representation style. For example:
def to_representation(self, instance):\n \"\"\"Convert `username` to lowercase.\"\"\"\n ret = super().to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret\n"},{"location":"api-guide/serializers/#to_internal_valueself-data","title":"to_internal_value(self, data)","text":"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.
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):\n my_field = serializers.CharField()\n\n def validate_my_field(self, value):\n ...\n\nclass MySerializer(MyBaseSerializer):\n ...\n 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):\n class Meta(MyBaseSerializer.Meta):\n model = Account\n 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:
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):\n my_field = serializers.CharField()\n\nclass MySerializer(MyBaseSerializer):\n my_field = None\n 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.
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.
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):\n \"\"\"\n A ModelSerializer that takes an additional `fields` argument that\n controls which fields should be displayed.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # Don't pass the 'fields' arg up to the superclass\n fields = kwargs.pop('fields', None)\n\n # Instantiate the superclass normally\n super().__init__(*args, **kwargs)\n\n if fields is not None:\n # Drop any fields that are not specified in the `fields` argument.\n allowed = set(fields)\n existing = set(self.fields)\n for field_name in existing - allowed:\n self.fields.pop(field_name)\n This would then allow you to do the following:
>>> class UserSerializer(DynamicFieldsModelSerializer):\n>>> class Meta:\n>>> model = User\n>>> fields = ['id', 'username', 'email']\n>>>\n>>> print(UserSerializer(user))\n{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}\n>>>\n>>> print(UserSerializer(user, fields=('id', 'email')))\n{'id': 2, 'email': 'jon@example.com'}\n"},{"location":"api-guide/serializers/#customizing-the-default-fields","title":"Customizing the default fields","text":"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.
"},{"location":"api-guide/serializers/#third-party-packages","title":"Third party packages","text":"The following third party packages are also available.
"},{"location":"api-guide/serializers/#django-rest-marshmallow","title":"Django REST marshmallow","text":"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.
"},{"location":"api-guide/serializers/#serpy","title":"Serpy","text":"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.
"},{"location":"api-guide/serializers/#mongoenginemodelserializer","title":"MongoengineModelSerializer","text":"The django-rest-framework-mongoengine package provides a MongoEngineModelSerializer serializer class that supports using MongoDB as the storage layer for Django REST framework.
The django-rest-framework-gis package provides a GeoFeatureModelSerializer serializer class that supports GeoJSON both for read and write operations.
The django-rest-framework-hstore package provides an HStoreSerializer to support django-hstore DictionaryField model field and its schema-mode feature.
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.
"},{"location":"api-guide/serializers/#dynamic-fields-mixin","title":"Dynamic Fields Mixin","text":"The drf-dynamic-fields package provides a mixin to dynamically limit the fields per serializer to a subset specified by an URL parameter.
"},{"location":"api-guide/serializers/#drf-flexfields","title":"DRF FlexFields","text":"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.
"},{"location":"api-guide/serializers/#serializer-extensions","title":"Serializer Extensions","text":"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.
"},{"location":"api-guide/serializers/#html-json-forms","title":"HTML JSON Forms","text":"The html-json-forms package provides an algorithm and serializer for processing <form> submissions per the (inactive) HTML JSON Form specification. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, <input name=\"items[0][id]\" value=\"5\"> will be interpreted as {\"items\": [{\"id\": \"5\"}]}.
DRF-Base64 provides a set of field and model serializers that handles the upload of base64-encoded files.
"},{"location":"api-guide/serializers/#queryfields","title":"QueryFields","text":"djangorestframework-queryfields allows API clients to specify which fields will be sent in the response via inclusion/exclusion query parameters.
"},{"location":"api-guide/serializers/#drf-writable-nested","title":"DRF Writable Nested","text":"The drf-writable-nested package provides writable nested model serializer which allows to create/update models with nested related data.
"},{"location":"api-guide/serializers/#drf-encrypt-content","title":"DRF Encrypt Content","text":"The drf-encrypt-content package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
"},{"location":"api-guide/serializers/#shapeless-serializers","title":"Shapeless Serializers","text":"The drf-shapeless-serializers package provides dynamic serializer configuration capabilities, allowing runtime field selection, renaming, attribute modification, and nested relationship configuration without creating multiple serializer classes. It helps eliminate serializer boilerplate while providing flexible API responses.
"},{"location":"api-guide/settings/","title":"Settings","text":"Namespaces are one honking great idea - let's do more of those!
\u2014 The Zen of Python
Configuration for REST framework is all namespaced inside a single Django setting, named REST_FRAMEWORK.
For example your project's settings.py file might include something like this:
REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n ],\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework.parsers.JSONParser',\n ]\n}\n"},{"location":"api-guide/settings/#accessing-settings","title":"Accessing settings","text":"If you need to access the values of REST framework's API settings in your project, you should use the api_settings object. For example.
from rest_framework.settings import api_settings\n\nprint(api_settings.DEFAULT_AUTHENTICATION_CLASSES)\n The api_settings object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.
The following settings control the basic API policies, and are applied to every APIView class-based view, or @api_view function based view.
A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a Response object.
Default:
[\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n]\n"},{"location":"api-guide/settings/#default_parser_classes","title":"DEFAULT_PARSER_CLASSES","text":"A list or tuple of parser classes, that determines the default set of parsers used when accessing the request.data property.
Default:
[\n 'rest_framework.parsers.JSONParser',\n 'rest_framework.parsers.FormParser',\n 'rest_framework.parsers.MultiPartParser'\n]\n"},{"location":"api-guide/settings/#default_authentication_classes","title":"DEFAULT_AUTHENTICATION_CLASSES","text":"A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the request.user or request.auth properties.
Default:
[\n 'rest_framework.authentication.SessionAuthentication',\n 'rest_framework.authentication.BasicAuthentication'\n]\n"},{"location":"api-guide/settings/#default_permission_classes","title":"DEFAULT_PERMISSION_CLASSES","text":"A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list.
Default:
[\n 'rest_framework.permissions.AllowAny',\n]\n"},{"location":"api-guide/settings/#default_throttle_classes","title":"DEFAULT_THROTTLE_CLASSES","text":"A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.
Default: []
A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.
Default: 'rest_framework.negotiation.DefaultContentNegotiation'
A view inspector class that will be used for schema generation.
Default: 'rest_framework.schemas.openapi.AutoSchema'
The following settings control the behavior of the generic class-based views.
"},{"location":"api-guide/settings/#default_filter_backends","title":"DEFAULT_FILTER_BACKENDS","text":"A list of filter backend classes that should be used for generic filtering. If set to None then generic filtering is disabled.
The default class to use for queryset pagination. If set to None, pagination is disabled by default. See the pagination documentation for further guidance on setting and modifying the pagination style.
Default: None
The default page size to use for pagination. If set to None, pagination is disabled by default.
Default: None
The name of a query parameter, which can be used to specify the search term used by SearchFilter.
Default: search
The name of a query parameter, which can be used to specify the ordering of results returned by OrderingFilter.
Default: ordering
The value that should be used for request.version when no versioning information is present.
Default: None
If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set.
Default: None
The string that should used for any versioning parameters, such as in the media type or URL query parameters.
Default: 'version'
The default versioning scheme to use.
Default: None
The following settings control the behavior of unauthenticated requests.
"},{"location":"api-guide/settings/#unauthenticated_user","title":"UNAUTHENTICATED_USER","text":"The class that should be used to initialize request.user for unauthenticated requests. (If removing authentication entirely, e.g. by removing django.contrib.auth from INSTALLED_APPS, set UNAUTHENTICATED_USER to None.)
Default: django.contrib.auth.models.AnonymousUser
The class that should be used to initialize request.auth for unauthenticated requests.
Default: None
The following settings control the behavior of APIRequestFactory and APIClient
"},{"location":"api-guide/settings/#test_request_default_format","title":"TEST_REQUEST_DEFAULT_FORMAT","text":"The default format that should be used when making test requests.
This should match up with the format of one of the renderer classes in the TEST_REQUEST_RENDERER_CLASSES setting.
Default: 'multipart'
The renderer classes that are supported when building test requests.
The format of any of these renderer classes may be used when constructing a test request, for example: client.post('/users', {'username': 'jamie'}, format='json')
Default:
[\n 'rest_framework.renderers.MultiPartRenderer',\n 'rest_framework.renderers.JSONRenderer'\n]\n"},{"location":"api-guide/settings/#schema-generation-controls","title":"Schema generation controls","text":""},{"location":"api-guide/settings/#schema_coerce_path_pk","title":"SCHEMA_COERCE_PATH_PK","text":"If set, this maps the 'pk' identifier in the URL conf onto the actual field name when generating a schema path parameter. Typically this will be 'id'. This gives a more suitable representation as \"primary key\" is an implementation detail, whereas \"identifier\" is a more general concept.
Default: True
If set, this is used to map internal viewset method names onto external action names used in the schema generation. This allows us to generate names that are more suitable for an external representation than those that are used internally in the codebase.
Default: {'retrieve': 'read', 'destroy': 'delete'}
The name of a URL parameter that may be used to override the default content negotiation Accept header behavior, by using a format=\u2026 query parameter in the request URL.
For example: http://example.com/organizations/?format=csv
If the value of this setting is None then URL format overrides will be disabled.
Default: 'format'
The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using format_suffix_patterns to include suffixed URL patterns.
For example: http://example.com/organizations.csv/
Default: 'format'
The following settings are used to control how date and time representations may be parsed and rendered.
"},{"location":"api-guide/settings/#datetime_format","title":"DATETIME_FORMAT","text":"A format string that should be used by default for rendering the output of DateTimeField serializer fields. If None, then DateTimeField serializer fields will return Python datetime objects, and the datetime encoding will be determined by the renderer.
May be any of None, 'iso-8601' or a Python strftime format string.
Default: 'iso-8601'
A list of format strings that should be used by default for parsing inputs to DateTimeField serializer fields.
May be a list including the string 'iso-8601' or Python strftime format strings.
Default: ['iso-8601']
A format string that should be used by default for rendering the output of DateField serializer fields. If None, then DateField serializer fields will return Python date objects, and the date encoding will be determined by the renderer.
May be any of None, 'iso-8601' or a Python strftime format string.
Default: 'iso-8601'
A list of format strings that should be used by default for parsing inputs to DateField serializer fields.
May be a list including the string 'iso-8601' or Python strftime format strings.
Default: ['iso-8601']
A format string that should be used by default for rendering the output of TimeField serializer fields. If None, then TimeField serializer fields will return Python time objects, and the time encoding will be determined by the renderer.
May be any of None, 'iso-8601' or a Python strftime format string.
Default: 'iso-8601'
A list of format strings that should be used by default for parsing inputs to TimeField serializer fields.
May be a list including the string 'iso-8601' or Python strftime format strings.
Default: ['iso-8601']
Indicates the default format that should be used for rendering the output of DurationField serializer fields. If None, then DurationField serializer fields will return Python timedelta objects, and the duration encoding will be determined by the renderer.
May be any of None, 'iso-8601' or 'django' (the format accepted by django.utils.dateparse.parse_duration).
Default: 'django'
When set to True, JSON responses will allow unicode characters in responses. For example:
{\"unicode black star\":\"\u2605\"}\n When set to False, JSON responses will escape non-ascii characters, like so:
{\"unicode black star\":\"\\u2605\"}\n Both styles conform to RFC 4627, and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses.
Default: True
When set to True, JSON responses will return compact representations, with no spacing after ':' and ',' characters. For example:
{\"is_admin\":false,\"email\":\"jane@example\"}\n When set to False, JSON responses will return slightly more verbose representations, like so:
{\"is_admin\": false, \"email\": \"jane@example\"}\n The default style is to return minified responses, in line with Heroku's API design guidelines.
Default: True
When set to True, JSON rendering and parsing will only observe syntactically valid JSON, raising an exception for the extended float values (nan, inf, -inf) accepted by Python's json module. This is the recommended setting, as these values are not generally supported. e.g., neither Javascript's JSON.Parse nor PostgreSQL's JSON data type accept these values.
When set to False, JSON rendering and parsing will be permissive. However, these values are still invalid and will need to be specially handled in your code.
Default: True
When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations.
When set to True, the serializer DecimalField class will return strings instead of Decimal objects. When set to False, serializers will return Decimal objects, which the default JSON encoder will return as floats.
Default: True
When returning biginteger objects in API representations that do not support numbers up to 2^64, it is best to return the value as a string. This avoids the loss of precision that occurs with biginteger implementations.
When set to True, the serializer BigIntegerField class (by default) will return strings instead of BigInteger objects. When set to False, serializers will return BigInteger objects, which the default JSON encoder will return as numbers.
Default: False
The following settings are used to generate the view names and descriptions, as used in responses to OPTIONS requests, and as used in the browsable API.
A string representing the function that should be used when generating view names.
This should be a function with the following signature:
view_name(self)\n self: The view instance. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing self.__class__.__name__.If the view instance inherits ViewSet, it may have been initialized with several optional arguments:
name: A name explicitly provided to a view in the viewset. Typically, this value should be used as-is when provided.suffix: Text used when differentiating individual views in a viewset. This argument is mutually exclusive to name.detail: Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view.Default: 'rest_framework.views.get_view_name'
A string representing the function that should be used when generating view descriptions.
This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support rst markup in your view docstrings being output in the browsable API.
This should be a function with the following signature:
view_description(self, html=False)\n self: The view instance. Typically the description function would inspect the docstring of the class when generating a description, by accessing self.__class__.__doc__html: A boolean indicating if HTML output is required. True when used in the browsable API, and False when used in generating OPTIONS responses.If the view instance inherits ViewSet, it may have been initialized with several optional arguments:
description: A description explicitly provided to the view in the viewset. Typically, this is set by extra viewset actions, and should be used as-is.Default: 'rest_framework.views.get_view_description'
Global settings for select field cutoffs for rendering relational fields in the browsable API.
"},{"location":"api-guide/settings/#html_select_cutoff","title":"HTML_SELECT_CUTOFF","text":"Global setting for the html_cutoff value. Must be an integer.
Default: 1000
"},{"location":"api-guide/settings/#html_select_cutoff_text","title":"HTML_SELECT_CUTOFF_TEXT","text":"A string representing a global setting for html_cutoff_text.
Default: \"More than {count} items...\"
A string representing the function that should be used when returning a response for any given exception. If the function returns None, a 500 error will be raised.
This setting can be changed to support error responses other than the default {\"detail\": \"Failure...\"} responses. For example, you can use it to provide API responses like {\"errors\": [{\"message\": \"Failure...\", \"code\": \"\"} ...]}.
This should be a function with the following signature:
exception_handler(exc, context)\n exc: The exception.Default: 'rest_framework.views.exception_handler'
A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors.
Default: 'non_field_errors'
A string representing the key that should be used for the URL fields generated by HyperlinkedModelSerializer.
Default: 'url'
An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to None then less strict IP matching will be used by the throttle classes.
Default: None
418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code \"418 I'm a teapot\". The resulting entity body MAY be short and stout.
\u2014 RFC 2324, Hyper Text Coffee Pot Control Protocol
Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make your code more obvious and readable.
from rest_framework import status\nfrom rest_framework.response import Response\n\ndef empty_view(self):\n content = {'please move along': 'nothing to see here'}\n return Response(content, status=status.HTTP_404_NOT_FOUND)\n The full set of HTTP status codes included in the status module is listed below.
The module also includes a set of helper functions for testing if a status code is in a given range.
from rest_framework import status\nfrom rest_framework.test import APITestCase\n\nclass ExampleTestCase(APITestCase):\n def test_url_root(self):\n url = reverse('index')\n response = self.client.get(url)\n self.assertTrue(status.is_success(response.status_code))\n For more information on proper usage of HTTP status codes see RFC 2616 and RFC 6585.
"},{"location":"api-guide/status-codes/#informational-1xx","title":"Informational - 1xx","text":"This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.
HTTP_100_CONTINUE\nHTTP_101_SWITCHING_PROTOCOLS\nHTTP_102_PROCESSING\nHTTP_103_EARLY_HINTS\n"},{"location":"api-guide/status-codes/#successful-2xx","title":"Successful - 2xx","text":"This class of status code indicates that the client's request was successfully received, understood, and accepted.
HTTP_200_OK\nHTTP_201_CREATED\nHTTP_202_ACCEPTED\nHTTP_203_NON_AUTHORITATIVE_INFORMATION\nHTTP_204_NO_CONTENT\nHTTP_205_RESET_CONTENT\nHTTP_206_PARTIAL_CONTENT\nHTTP_207_MULTI_STATUS\nHTTP_208_ALREADY_REPORTED\nHTTP_226_IM_USED\n"},{"location":"api-guide/status-codes/#redirection-3xx","title":"Redirection - 3xx","text":"This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.
HTTP_300_MULTIPLE_CHOICES\nHTTP_301_MOVED_PERMANENTLY\nHTTP_302_FOUND\nHTTP_303_SEE_OTHER\nHTTP_304_NOT_MODIFIED\nHTTP_305_USE_PROXY\nHTTP_306_RESERVED\nHTTP_307_TEMPORARY_REDIRECT\nHTTP_308_PERMANENT_REDIRECT\n"},{"location":"api-guide/status-codes/#client-error-4xx","title":"Client Error - 4xx","text":"The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
HTTP_400_BAD_REQUEST\nHTTP_401_UNAUTHORIZED\nHTTP_402_PAYMENT_REQUIRED\nHTTP_403_FORBIDDEN\nHTTP_404_NOT_FOUND\nHTTP_405_METHOD_NOT_ALLOWED\nHTTP_406_NOT_ACCEPTABLE\nHTTP_407_PROXY_AUTHENTICATION_REQUIRED\nHTTP_408_REQUEST_TIMEOUT\nHTTP_409_CONFLICT\nHTTP_410_GONE\nHTTP_411_LENGTH_REQUIRED\nHTTP_412_PRECONDITION_FAILED\nHTTP_413_REQUEST_ENTITY_TOO_LARGE\nHTTP_414_REQUEST_URI_TOO_LONG\nHTTP_415_UNSUPPORTED_MEDIA_TYPE\nHTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE\nHTTP_417_EXPECTATION_FAILED\nHTTP_421_MISDIRECTED_REQUEST\nHTTP_422_UNPROCESSABLE_ENTITY\nHTTP_423_LOCKED\nHTTP_424_FAILED_DEPENDENCY\nHTTP_425_TOO_EARLY\nHTTP_426_UPGRADE_REQUIRED\nHTTP_428_PRECONDITION_REQUIRED\nHTTP_429_TOO_MANY_REQUESTS\nHTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE\nHTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS\n"},{"location":"api-guide/status-codes/#server-error-5xx","title":"Server Error - 5xx","text":"Response status codes beginning with the digit \"5\" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
HTTP_500_INTERNAL_SERVER_ERROR\nHTTP_501_NOT_IMPLEMENTED\nHTTP_502_BAD_GATEWAY\nHTTP_503_SERVICE_UNAVAILABLE\nHTTP_504_GATEWAY_TIMEOUT\nHTTP_505_HTTP_VERSION_NOT_SUPPORTED\nHTTP_506_VARIANT_ALSO_NEGOTIATES\nHTTP_507_INSUFFICIENT_STORAGE\nHTTP_508_LOOP_DETECTED\nHTTP_509_BANDWIDTH_LIMIT_EXCEEDED\nHTTP_510_NOT_EXTENDED\nHTTP_511_NETWORK_AUTHENTICATION_REQUIRED\n"},{"location":"api-guide/status-codes/#helper-functions","title":"Helper functions","text":"The following helper functions are available for identifying the category of the response code.
is_informational() # 1xx\nis_success() #\u00a02xx\nis_redirect() # 3xx\nis_client_error() # 4xx\nis_server_error() # 5xx\n"},{"location":"api-guide/testing/","title":"Testing","text":"Code without tests is broken as designed.
\u2014 Jacob Kaplan-Moss
REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.
"},{"location":"api-guide/testing/#apirequestfactory","title":"APIRequestFactory","text":"Extends Django's existing RequestFactory class.
The APIRequestFactory class supports an almost identical API to Django's standard RequestFactory class. This means that the standard .get(), .post(), .put(), .patch(), .delete(), .head() and .options() methods are all available.
from rest_framework.test import APIRequestFactory\n\n# Using the standard RequestFactory API to create a form POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'})\n\n# Using the standard RequestFactory API to encode JSON data\nrequest = factory.post('/notes/', {'title': 'new idea'}, content_type='application/json')\n"},{"location":"api-guide/testing/#using-the-format-argument","title":"Using the format argument","text":"Methods which create a request body, such as post, put and patch, include a format argument, which make it easy to generate requests using a wide set of request formats. When using this argument, the factory will select an appropriate renderer and its configured content_type. For example:
# Create a JSON POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'}, format='json')\n By default the available formats are 'multipart' and 'json'. For compatibility with Django's existing RequestFactory the default format is 'multipart'.
To support a wider set of request formats, or change the default format, see the configuration section.
"},{"location":"api-guide/testing/#explicitly-encoding-the-request-body","title":"Explicitly encoding the request body","text":"If you need to explicitly encode the request body, you can do so by setting the content_type flag. For example:
request = factory.post('/notes/', yaml.dump({'title': 'new idea'}), content_type='application/yaml')\n"},{"location":"api-guide/testing/#put-and-patch-with-form-data","title":"PUT and PATCH with form data","text":"One difference worth noting between Django's RequestFactory and REST framework's APIRequestFactory is that multipart form data will be encoded for methods other than just .post().
For example, using APIRequestFactory, you can make a form PUT request like so:
factory = APIRequestFactory()\nrequest = factory.put('/notes/547/', {'title': 'remember to email dave'})\n Using Django's RequestFactory, you'd need to explicitly encode the data yourself:
from django.test.client import encode_multipart, RequestFactory\n\nfactory = RequestFactory()\ndata = {'title': 'remember to email dave'}\ncontent = encode_multipart('BoUnDaRyStRiNg', data)\ncontent_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'\nrequest = factory.put('/notes/547/', content, content_type=content_type)\n"},{"location":"api-guide/testing/#forcing-authentication","title":"Forcing authentication","text":"When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.
To forcibly authenticate a request, use the force_authenticate() method.
from rest_framework.test import force_authenticate\n\nfactory = APIRequestFactory()\nuser = User.objects.get(username='olivia')\nview = AccountDetail.as_view()\n\n# Make an authenticated request to the view...\nrequest = factory.get('/accounts/django-superstars/')\nforce_authenticate(request, user=user)\nresponse = view(request)\n The signature for the method is force_authenticate(request, user=None, token=None). When making the call, either or both of the user and token may be set.
For example, when forcibly authenticating using a token, you might do something like the following:
user = User.objects.get(username='olivia')\nrequest = factory.get('/accounts/django-superstars/')\nforce_authenticate(request, user=user, token=user.auth_token)\n Note
force_authenticate directly sets request.user to the in-memory user instance. If you are reusing the same user instance across multiple tests that update the saved user state, you may need to call refresh_from_db() between tests.
Note
When using APIRequestFactory, the object that is returned is Django's standard HttpRequest, and not REST framework's Request object, which is only generated once the view is called.
This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting .token directly will have no effect, and setting .user directly will only work if session authentication is being used.
# Request will only authenticate if `SessionAuthentication` is in use.\nrequest = factory.get('/accounts/django-superstars/')\nrequest.user = user\nresponse = view(request)\n If you want to test a request involving the REST framework\u2019s 'Request' object, you\u2019ll need to manually transform it first:
class DummyView(APIView):\n ...\n\nfactory = APIRequestFactory()\nrequest = factory.get('/', {'demo': 'test'})\ndrf_request = DummyView().initialize_request(request)\nassert drf_request.query_params == {'demo': ['test']}\n\nrequest = factory.post('/', {'example': 'test'})\ndrf_request = DummyView().initialize_request(request)\nassert drf_request.data.get('example') == 'test'\n"},{"location":"api-guide/testing/#forcing-csrf-validation","title":"Forcing CSRF validation","text":"By default, requests created with APIRequestFactory will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the enforce_csrf_checks flag when instantiating the factory.
factory = APIRequestFactory(enforce_csrf_checks=True)\n Note
It's worth noting that Django's standard RequestFactory doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.
Extends Django's existing Client class.
The APIClient class supports the same request interface as Django's standard Client class. This means that the standard .get(), .post(), .put(), .patch(), .delete(), .head() and .options() methods are all available. For example:
from rest_framework.test import APIClient\n\nclient = APIClient()\nclient.post('/notes/', {'title': 'new idea'}, format='json')\n To support a wider set of request formats, or change the default format, see the configuration section.
"},{"location":"api-guide/testing/#authenticating","title":"Authenticating","text":""},{"location":"api-guide/testing/#loginkwargs","title":".login(**kwargs)","text":"The login method functions exactly as it does with Django's regular Client class. This allows you to authenticate requests against any views which include SessionAuthentication.
# Make all requests in the context of a logged in session.\nclient = APIClient()\nclient.login(username='lauren', password='secret')\n To logout, call the logout method as usual.
# Log out\nclient.logout()\n The login method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.
The credentials method can be used to set headers that will then be included on all subsequent requests by the test client.
from rest_framework.authtoken.models import Token\nfrom rest_framework.test import APIClient\n\n# Include an appropriate `Authorization:` header on all requests.\ntoken = Token.objects.get(user__username='lauren')\nclient = APIClient()\nclient.credentials(HTTP_AUTHORIZATION='Token ' + token.key)\n Note that calling credentials a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments.
# Stop including any credentials\nclient.credentials()\n The credentials method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.
Sometimes you may want to bypass authentication entirely and force all requests by the test client to be automatically treated as authenticated.
This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.
user = User.objects.get(username='lauren')\nclient = APIClient()\nclient.force_authenticate(user=user)\n To unauthenticate subsequent requests, call force_authenticate setting the user and/or token to None.
client.force_authenticate(user=None)\n"},{"location":"api-guide/testing/#csrf-validation","title":"CSRF validation","text":"By default CSRF validation is not applied when using APIClient. If you need to explicitly enable CSRF validation, you can do so by setting the enforce_csrf_checks flag when instantiating the client.
client = APIClient(enforce_csrf_checks=True)\n As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling login().
REST framework also includes a client for interacting with your application using the popular Python library, requests. This may be useful if:
This exposes exactly the same interface as if you were using a requests session directly.
from rest_framework.test import RequestsClient\n\nclient = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200\n Note that the requests client requires you to pass fully qualified URLs.
"},{"location":"api-guide/testing/#requestsclient-and-working-with-the-database","title":"RequestsClient and working with the database","text":"The RequestsClient class is useful if you want to write tests that solely interact with the service interface. This is a little stricter than using the standard Django test client, as it means that all interactions should be via the API.
If you're using RequestsClient you'll want to ensure that test setup, and results assertions are performed as regular API calls, rather than interacting with the database models directly. For example, rather than checking that Customer.objects.count() == 3 you would list the customers endpoint, and ensure that it contains three records.
Custom headers and authentication credentials can be provided in the same way as when using a standard requests.Session instance.
from requests.auth import HTTPBasicAuth\n\nclient.auth = HTTPBasicAuth('user', 'pass')\nclient.headers.update({'x-test': 'true'})\n"},{"location":"api-guide/testing/#csrf","title":"CSRF","text":"If you're using SessionAuthentication then you'll need to include a CSRF token for any POST, PUT, PATCH or DELETE requests.
You can do so by following the same flow that a JavaScript based client would use. First, make a GET request in order to obtain a CSRF token, then present that token in the following request.
For example...
client = RequestsClient()\n\n# Obtain a CSRF token.\nresponse = client.get('http://testserver/homepage/')\nassert response.status_code == 200\ncsrftoken = response.cookies['csrftoken']\n\n# Interact with the API.\nresponse = client.post('http://testserver/organizations/', json={\n 'name': 'MegaCorp',\n 'status': 'active'\n}, headers={'X-CSRFToken': csrftoken})\nassert response.status_code == 200\n"},{"location":"api-guide/testing/#live-tests","title":"Live tests","text":"With careful usage both the RequestsClient and the CoreAPIClient provide the ability to write test cases that can run either in development, or be run directly against your staging server or production environment.
Using this style to create basic tests of a few core pieces of functionality is a powerful way to validate your live service. Doing so may require some careful attention to setup and teardown to ensure that the tests run in a way that they do not directly affect customer data.
"},{"location":"api-guide/testing/#coreapiclient","title":"CoreAPIClient","text":"The CoreAPIClient allows you to interact with your API using the Python coreapi client library.
# Fetch the API schema\nclient = CoreAPIClient()\nschema = client.get('http://testserver/schema/')\n\n# Create a new organization\nparams = {'name': 'MegaCorp', 'status': 'active'}\nclient.action(schema, ['organizations', 'create'], params)\n\n# Ensure that the organization exists in the listing\ndata = client.action(schema, ['organizations', 'list'])\nassert(len(data) == 1)\nassert(data == [{'name': 'MegaCorp', 'status': 'active'}])\n"},{"location":"api-guide/testing/#headers-authentication_1","title":"Headers & Authentication","text":"Custom headers and authentication may be used with CoreAPIClient in a similar way as with RequestsClient.
from requests.auth import HTTPBasicAuth\n\nclient = CoreAPIClient()\nclient.session.auth = HTTPBasicAuth('user', 'pass')\nclient.session.headers.update({'x-test': 'true'})\n"},{"location":"api-guide/testing/#api-test-cases","title":"API Test cases","text":"REST framework includes the following test case classes, that mirror the existing Django's test case classes, but use APIClient instead of Django's default Client.
APISimpleTestCaseAPITransactionTestCaseAPITestCaseAPILiveServerTestCaseYou can use any of REST framework's test case classes as you would for the regular Django test case classes. The self.client attribute will be an APIClient instance.
from django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom myproject.apps.core.models import Account\n\nclass AccountTests(APITestCase):\n def test_create_account(self):\n \"\"\"\n Ensure we can create a new account object.\n \"\"\"\n url = reverse('account-list')\n data = {'name': 'DabApps'}\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(Account.objects.count(), 1)\n self.assertEqual(Account.objects.get().name, 'DabApps')\n"},{"location":"api-guide/testing/#urlpatternstestcase","title":"URLPatternsTestCase","text":"REST framework also provides a test case class for isolating urlpatterns on a per-class basis. Note that this inherits from Django's SimpleTestCase, and will most likely need to be mixed with another test case class.
from django.urls import include, path, reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase, URLPatternsTestCase\n\n\nclass AccountTests(APITestCase, URLPatternsTestCase):\n urlpatterns = [\n path('api/', include('api.urls')),\n ]\n\n def test_create_account(self):\n \"\"\"\n Ensure we can create a new account object.\n \"\"\"\n url = reverse('account-list')\n response = self.client.get(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data), 1)\n"},{"location":"api-guide/testing/#testing-responses","title":"Testing responses","text":""},{"location":"api-guide/testing/#checking-the-response-data","title":"Checking the response data","text":"When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.
For example, it's easier to inspect response.data:
response = self.client.get('/users/4/')\nself.assertEqual(response.data, {'id': 4, 'username': 'lauren'})\n Instead of inspecting the result of parsing response.content:
response = self.client.get('/users/4/')\nself.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})\n"},{"location":"api-guide/testing/#rendering-responses","title":"Rendering responses","text":"If you're testing views directly using APIRequestFactory, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access response.content, you'll first need to render the response.
view = UserDetail.as_view()\nrequest = factory.get('/users/4')\nresponse = view(request, pk='4')\nresponse.render() # Cannot access `response.content` without this.\nself.assertEqual(response.content, '{\"username\": \"lauren\", \"id\": 4}')\n"},{"location":"api-guide/testing/#configuration","title":"Configuration","text":""},{"location":"api-guide/testing/#setting-the-default-format","title":"Setting the default format","text":"The default format used to make test requests may be set using the TEST_REQUEST_DEFAULT_FORMAT setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your settings.py file:
REST_FRAMEWORK = {\n ...\n 'TEST_REQUEST_DEFAULT_FORMAT': 'json'\n}\n"},{"location":"api-guide/testing/#setting-the-available-formats","title":"Setting the available formats","text":"If you need to test requests using something other than multipart or json requests, you can do so by setting the TEST_REQUEST_RENDERER_CLASSES setting.
For example, to add support for using format='html' in test requests, you might have something like this in your settings.py file.
REST_FRAMEWORK = {\n ...\n 'TEST_REQUEST_RENDERER_CLASSES': [\n 'rest_framework.renderers.MultiPartRenderer',\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.TemplateHTMLRenderer'\n ]\n}\n"},{"location":"api-guide/throttling/","title":"Throttling","text":"HTTP/1.1 420 Enhance Your Calm
Twitter API rate limiting response
Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.
As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.
Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.
Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.
The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.
"},{"location":"api-guide/throttling/#how-throttling-is-determined","title":"How throttling is determined","text":"As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
Before running the main body of the view each throttle in the list is checked. If any throttle check fails an exceptions.Throttled exception will be raised, and the main body of the view will not run.
The default throttling policy may be set globally, using the DEFAULT_THROTTLE_CLASSES and DEFAULT_THROTTLE_RATES settings. For example.
REST_FRAMEWORK = {\n 'DEFAULT_THROTTLE_CLASSES': [\n 'rest_framework.throttling.AnonRateThrottle',\n 'rest_framework.throttling.UserRateThrottle'\n ],\n 'DEFAULT_THROTTLE_RATES': {\n 'anon': '100/day',\n 'user': '1000/day'\n }\n}\n The rates used in DEFAULT_THROTTLE_RATES can be specified over a period of second, minute, hour or day. The period must be specified after the / separator using s, m, h or d, respectively. For increased clarity, extended units such as second, minute, hour, day or even abbreviations like sec, min, hr are allowed, as only the first character is relevant to identify the rate.
You can also set the throttling policy on a per-view or per-viewset basis, using the APIView class-based views.
from rest_framework.response import Response\nfrom rest_framework.throttling import UserRateThrottle\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n throttle_classes = [UserRateThrottle]\n\n def get(self, request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n If you're using the @api_view decorator with function based views you can use the following decorator.
@api_view(['GET'])\n@throttle_classes([UserRateThrottle])\ndef example_view(request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n It's also possible to set throttle classes for routes that are created using the @action decorator. Throttle classes set in this way will override any viewset level class settings.
@action(detail=True, methods=[\"post\"], throttle_classes=[UserRateThrottle])\ndef example_adhoc_method(request, pk=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n"},{"location":"api-guide/throttling/#how-clients-are-identified","title":"How clients are identified","text":"The X-Forwarded-For HTTP header and REMOTE_ADDR WSGI variable are used to uniquely identify client IP addresses for throttling. If the X-Forwarded-For header is present then it will be used, otherwise the value of the REMOTE_ADDR variable from the WSGI environment will be used.
If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the NUM_PROXIES setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the X-Forwarded-For header, once any application proxy IP addresses have first been excluded. If set to zero, then the REMOTE_ADDR value will always be used as the identifying IP address.
It is important to understand that if you configure the NUM_PROXIES setting, then all clients behind a unique NAT'd gateway will be treated as a single client.
Further context on how the X-Forwarded-For header works, and identifying a remote client IP can be found here.
The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate cache settings. The default value of LocMemCache backend should be okay for simple setups. See Django's cache documentation for more details.
If you need to use a cache other than 'default', you can do so by creating a custom throttle class and setting the cache attribute. For example:
from django.core.cache import caches\n\nclass CustomAnonRateThrottle(AnonRateThrottle):\n cache = caches['alternate']\n You'll need to remember to also set your custom throttle class in the 'DEFAULT_THROTTLE_CLASSES' settings key, or using the throttle_classes view attribute.
The built-in throttle implementations are open to race conditions, so under high concurrency they may allow a few extra requests through.
If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class. See issue #5181 for more details.
"},{"location":"api-guide/throttling/#api-reference","title":"API Reference","text":""},{"location":"api-guide/throttling/#anonratethrottle","title":"AnonRateThrottle","text":"The AnonRateThrottle will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
The allowed request rate is determined from one of the following (in order of preference).
rate property on the class, which may be provided by overriding AnonRateThrottle and setting the property.DEFAULT_THROTTLE_RATES['anon'] setting.AnonRateThrottle is suitable if you want to restrict the rate of requests from unknown sources.
The UserRateThrottle will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.
The allowed request rate is determined from one of the following (in order of preference).
rate property on the class, which may be provided by overriding UserRateThrottle and setting the property.DEFAULT_THROTTLE_RATES['user'] setting.An API may have multiple UserRateThrottles in place at the same time. To do so, override UserRateThrottle and set a unique \"scope\" for each class.
For example, multiple user throttle rates could be implemented by using the following classes...
class BurstRateThrottle(UserRateThrottle):\n scope = 'burst'\n\nclass SustainedRateThrottle(UserRateThrottle):\n scope = 'sustained'\n ...and the following settings.
REST_FRAMEWORK = {\n 'DEFAULT_THROTTLE_CLASSES': [\n 'example.throttles.BurstRateThrottle',\n 'example.throttles.SustainedRateThrottle'\n ],\n 'DEFAULT_THROTTLE_RATES': {\n 'burst': '60/min',\n 'sustained': '1000/day'\n }\n}\n UserRateThrottle is suitable if you want simple global rate restrictions per-user.
The ScopedRateThrottle class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a .throttle_scope property. The unique throttle key will then be formed by concatenating the \"scope\" of the request with the unique user id or IP address.
The allowed request rate is determined by the DEFAULT_THROTTLE_RATES setting using a key from the request \"scope\".
For example, given the following views...
class ContactListView(APIView):\n throttle_scope = 'contacts'\n ...\n\nclass ContactDetailView(APIView):\n throttle_scope = 'contacts'\n ...\n\nclass UploadView(APIView):\n throttle_scope = 'uploads'\n ...\n ...and the following settings.
REST_FRAMEWORK = {\n 'DEFAULT_THROTTLE_CLASSES': [\n 'rest_framework.throttling.ScopedRateThrottle',\n ],\n 'DEFAULT_THROTTLE_RATES': {\n 'contacts': '1000/day',\n 'uploads': '20/day'\n }\n}\n User requests to either ContactListView or ContactDetailView would be restricted to a total of 1000 requests per-day. User requests to UploadView would be restricted to 20 requests per day.
To create a custom throttle, override BaseThrottle and implement .allow_request(self, request, view). The method should return True if the request should be allowed, and False otherwise.
Optionally you may also override the .wait() method. If implemented, .wait() should return a recommended number of seconds to wait before attempting the next request, or None. The .wait() method will only be called if .allow_request() has previously returned False.
If the .wait() method is implemented and the request is throttled, then a Retry-After header will be included in the response.
The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
import random\n\nclass RandomRateThrottle(throttling.BaseThrottle):\n def allow_request(self, request, view):\n return random.randint(1, 10) != 1\n"},{"location":"api-guide/validators/","title":"Validators","text":"Validators can be useful for reusing validation logic between different types of fields.
\u2014 Django documentation
Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.
However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
"},{"location":"api-guide/validators/#validation-in-rest-framework","title":"Validation in REST framework","text":"Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class.
With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
ModelSerializer classes and using explicit Serializer classes. Any validation behavior being used for ModelSerializer is simple to replicate.repr of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.When you're using ModelSerializer all of this is handled automatically for you. If you want to drop down to using Serializer classes instead, then you need to define the validation rules explicitly.
As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.
class CustomerReportRecord(models.Model):\n time_raised = models.DateTimeField(default=timezone.now, editable=False)\n reference = models.CharField(unique=True, max_length=20)\n description = models.TextField()\n Here's a basic ModelSerializer that we can use for creating or updating instances of CustomerReportRecord:
class CustomerReportSerializer(serializers.ModelSerializer):\n class Meta:\n model = CustomerReportRecord\n If we open up the Django shell using manage.py shell we can now
>>> from project.example.serializers import CustomerReportSerializer\n>>> serializer = CustomerReportSerializer()\n>>> print(repr(serializer))\nCustomerReportSerializer():\n id = IntegerField(label='ID', read_only=True)\n time_raised = DateTimeField(read_only=True)\n reference = CharField(max_length=20, validators=[UniqueValidator(queryset=CustomerReportRecord.objects.all())])\n description = CharField(style={'type': 'textarea'})\n The interesting bit here is the reference field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.
Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. REST framework validators, like their Django counterparts, implement the __eq__ method, allowing you to compare instances for equality.
This validator can be used to enforce the unique=True constraint on model fields. It takes a single required argument, and an optional messages argument:
queryset required - This is the queryset against which uniqueness should be enforced.message - The error message that should be used when validation fails.lookup - The lookup used to find an existing instance with the value being validated. Defaults to 'exact'.This validator should be applied to serializer fields, like so:
from rest_framework.validators import UniqueValidator\n\nslug = SlugField(\n max_length=100,\n validators=[UniqueValidator(queryset=BlogPost.objects.all())]\n)\n"},{"location":"api-guide/validators/#uniquetogethervalidator","title":"UniqueTogetherValidator","text":"This validator can be used to enforce unique_together constraints on model instances. It has two required arguments, and a single optional messages argument:
queryset required - This is the queryset against which uniqueness should be enforced.fields required - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.message - The error message that should be used when validation fails.The validator should be applied to serializer classes, like so:
from rest_framework.validators import UniqueTogetherValidator\n\nclass ExampleSerializer(serializers.Serializer):\n # ...\n class Meta:\n # ToDo items belong to a parent list, and have an ordering defined\n # by the 'position' field. No two items in a given list may share\n # the same position.\n validators = [\n UniqueTogetherValidator(\n queryset=ToDoItem.objects.all(),\n fields=['list', 'position']\n )\n ]\n Note
The UniqueTogetherValidator class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.
These validators can be used to enforce the unique_for_date, unique_for_month and unique_for_year constraints on model instances. They take the following arguments:
queryset required - This is the queryset against which uniqueness should be enforced.field required - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.date_field required - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.message - The error message that should be used when validation fails.The validator should be applied to serializer classes, like so:
from rest_framework.validators import UniqueForYearValidator\n\nclass ExampleSerializer(serializers.Serializer):\n # ...\n class Meta:\n # Blog posts should have a slug that is unique for the current year.\n validators = [\n UniqueForYearValidator(\n queryset=BlogPostItem.objects.all(),\n field='slug',\n date_field='published'\n )\n ]\n The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class default=..., because the value being used for the default wouldn't be generated until after the validation has run.
There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using ModelSerializer you'll probably simply rely on the defaults that REST framework generates for you, but if you are using Serializer or simply want more explicit control, use on of the styles demonstrated below.
If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a default argument, or by setting required=True.
published = serializers.DateTimeField(required=True)\n"},{"location":"api-guide/validators/#using-with-a-read-only-date-field","title":"Using with a read-only date field.","text":"If you want the date field to be visible, but not editable by the user, then set read_only=True and additionally set a default=... argument.
published = serializers.DateTimeField(read_only=True, default=timezone.now)\n"},{"location":"api-guide/validators/#using-with-a-hidden-date-field","title":"Using with a hidden date field.","text":"If you want the date field to be entirely hidden from the user, then use HiddenField. This field type does not accept user input, but instead always returns its default value to the validated_data in the serializer.
published = serializers.HiddenField(default=timezone.now)\n Note
The UniqueFor<Range>Validator classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.
Note
HiddenField() does not appear in partial=True serializer (when making PATCH request).
Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that is available as input to the validator. For this purposes use HiddenField. This field will be present in validated_data but will not be used in the serializer output representation.
Note
Using a read_only=True field is excluded from writable fields so it won't use a default=\u2026 argument. Look 3.8 announcement.
REST framework includes a couple of defaults that may be useful in this context.
"},{"location":"api-guide/validators/#currentuserdefault","title":"CurrentUserDefault","text":"A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.
owner = serializers.HiddenField(\n default=serializers.CurrentUserDefault()\n)\n"},{"location":"api-guide/validators/#createonlydefault","title":"CreateOnlyDefault","text":"A default class that can be used to only set a default argument during create operations. During updates the field is omitted.
It takes a single argument, which is the default value or callable that should be used during create operations.
created_at = serializers.DateTimeField(\n default=serializers.CreateOnlyDefault(timezone.now)\n)\n"},{"location":"api-guide/validators/#limitations-of-validators","title":"Limitations of validators","text":"There are some ambiguous cases where you'll need to instead handle validation explicitly, rather than relying on the default serializer classes that ModelSerializer generates.
In these cases you may want to disable the automatically generated validators, by specifying an empty list for the serializer Meta.validators attribute.
By default \"unique together\" validation enforces that all fields be required=True. In some cases, you might want to explicit apply required=False to one of the fields, in which case the desired behavior of the validation is ambiguous.
In this case you will typically need to exclude the validator from the 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):\n def validate(self, attrs):\n # Apply custom validation either here, or in the view.\n\n class Meta:\n fields = ['client', 'date', 'amount']\n extra_kwargs = {'client': {'required': False}}\n validators = [] # Remove a default \"unique together\" constraint.\n"},{"location":"api-guide/validators/#updating-nested-serializers","title":"Updating nested serializers","text":"When applying an update to an existing instance, uniqueness validators will exclude the current instance from the uniqueness check. The current instance is available in the context of the uniqueness check, because it exists as an attribute on the serializer, having initially been passed using instance=... when instantiating the serializer.
In the case of update operations on nested serializers there's no way of applying this exclusion, because the instance is not available.
Again, you'll probably want to explicitly remove the validator from the serializer class, and write the code for the validation constraint explicitly, in a .validate() method, or in the view.
If you're not sure exactly what behavior a ModelSerializer class will generate it is usually a good idea to run manage.py shell, and print an instance of the serializer, so that you can inspect the fields and validators that it automatically generates for you.
>>> serializer = MyComplexModelSerializer()\n>>> print(serializer)\nclass MyComplexModelSerializer:\n my_fields = ...\n Also keep in mind that with complex cases it can often be better to explicitly define your serializer classes, rather than relying on the default ModelSerializer behavior. This involves a little more code, but ensures that the resulting behavior is more transparent.
You can use any of Django's existing validators, or write your own custom validators.
"},{"location":"api-guide/validators/#function-based","title":"Function based","text":"A validator may be any callable that raises a serializers.ValidationError on failure.
def even_number(value):\n if value % 2 != 0:\n raise serializers.ValidationError('This field must be an even number.')\n"},{"location":"api-guide/validators/#field-level-validation","title":"Field-level validation","text":"You can specify custom field-level validation by adding .validate_<field_name> methods to your Serializer subclass. This is documented in the Serializer docs
To write a class-based validator, use the __call__ method. Class-based validators are useful as they allow you to parameterize and reuse behavior.
class MultipleOf:\n def __init__(self, base):\n self.base = base\n\n def __call__(self, value):\n if value % self.base != 0:\n message = 'This field must be a multiple of %d.' % self.base\n raise serializers.ValidationError(message)\n"},{"location":"api-guide/validators/#accessing-the-context","title":"Accessing the context","text":"In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by setting a requires_context = True attribute on the validator class. The __call__ method will then be called with the serializer_field or serializer as an additional argument.
class MultipleOf:\n requires_context = True\n\n def __call__(self, value, serializer_field):\n ...\n"},{"location":"api-guide/versioning/","title":"Versioning","text":"Versioning an interface is just a \"polite\" way to kill deployed clients.
\u2014 Roy Fielding.
API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes.
Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers.
There are a number of valid approaches to approaching versioning. Non-versioned systems can also be appropriate, particularly if you're engineering for very long-term systems with multiple clients outside of your control.
"},{"location":"api-guide/versioning/#versioning-with-rest-framework","title":"Versioning with REST framework","text":"When API versioning is enabled, the request.version attribute will contain a string that corresponds to the version requested in the incoming client request.
By default, versioning is not enabled, and request.version will always return None.
How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example:
def get_serializer_class(self):\n if self.request.version == 'v1':\n return AccountSerializerVersion1\n return AccountSerializer\n"},{"location":"api-guide/versioning/#reversing-urls-for-versioned-apis","title":"Reversing URLs for versioned APIs","text":"The reverse function included by REST framework ties in with the versioning scheme. You need to make sure to include the current request as a keyword argument, like so.
from rest_framework.reverse import reverse\n\nreverse('bookings-list', request=request)\n The above function will apply any URL transformations appropriate to the request version. For example:
NamespaceVersioning was being used, and the API version was 'v1', then the URL lookup used would be 'v1:bookings-list', which might resolve to a URL like http://example.org/v1/bookings/.QueryParameterVersioning was being used, and the API version was 1.0, then the returned URL might be something like http://example.org/bookings/?version=1.0When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer.
def get(self, request):\n queryset = Booking.objects.all()\n serializer = BookingsSerializer(queryset, many=True, context={'request': request})\n return Response({'all_bookings': serializer.data})\n Doing so will allow any returned URLs to include the appropriate versioning.
"},{"location":"api-guide/versioning/#configuring-the-versioning-scheme","title":"Configuring the versioning scheme","text":"The versioning scheme is defined by the DEFAULT_VERSIONING_CLASS settings key.
REST_FRAMEWORK = {\n 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'\n}\n Unless it is explicitly set, the value for DEFAULT_VERSIONING_CLASS will be None. In this case the request.version attribute will always return None.
You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the versioning_class attribute.
class ProfileList(APIView):\n versioning_class = versioning.QueryParameterVersioning\n"},{"location":"api-guide/versioning/#other-versioning-settings","title":"Other versioning settings","text":"The following settings keys are also used to control versioning:
DEFAULT_VERSION. The value that should be used for request.version when no versioning information is present. Defaults to None.ALLOWED_VERSIONS. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version is not in this set. Note that the value used for the DEFAULT_VERSION setting is always considered to be part of the ALLOWED_VERSIONS set (unless it is None). Defaults to None.VERSION_PARAM. The string that should be used for any versioning parameters, such as in the media type or URL query parameters. Defaults to 'version'.You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the default_version, allowed_versions and version_param class variables. For example, if you want to use URLPathVersioning:
from rest_framework.versioning import URLPathVersioning\nfrom rest_framework.views import APIView\n\nclass ExampleVersioning(URLPathVersioning):\n default_version = ...\n allowed_versions = ...\n version_param = ...\n\nclass ExampleView(APIVIew):\n versioning_class = ExampleVersioning\n"},{"location":"api-guide/versioning/#api-reference","title":"API Reference","text":""},{"location":"api-guide/versioning/#acceptheaderversioning","title":"AcceptHeaderVersioning","text":"This scheme requires the client to specify the version as part of the media type in the Accept header. The version is included as a media type parameter, that supplements the main media type.
Here's an example HTTP request using the accept header versioning style.
GET /bookings/ HTTP/1.1\nHost: example.com\nAccept: application/json; version=1.0\n In the example request above request.version attribute would return the string '1.0'.
Versioning based on accept headers is generally considered as best practice, although other styles may be suitable depending on your client requirements.
"},{"location":"api-guide/versioning/#using-accept-headers-with-vendor-media-types","title":"Using accept headers with vendor media types","text":"Strictly speaking the json media type is not specified as including additional parameters. If you are building a well-specified public API you might consider using a vendor media type. To do so, configure your renderers to use a JSON based renderer with a custom media type:
class BookingsAPIRenderer(JSONRenderer):\n media_type = 'application/vnd.megacorp.bookings+json'\n Your client requests would now look like this:
GET /bookings/ HTTP/1.1\nHost: example.com\nAccept: application/vnd.megacorp.bookings+json; version=1.0\n"},{"location":"api-guide/versioning/#urlpathversioning","title":"URLPathVersioning","text":"This scheme requires the client to specify the version as part of the URL path.
GET /v1/bookings/ HTTP/1.1\nHost: example.com\nAccept: application/json\n Your URL conf must include a pattern that matches the version with a 'version' keyword argument, so that this information is available to the versioning scheme.
urlpatterns = [\n re_path(\n r'^(?P<version>(v1|v2))/bookings/$',\n bookings_list,\n name='bookings-list'\n ),\n re_path(\n r'^(?P<version>(v1|v2))/bookings/(?P<pk>[0-9]+)/$',\n bookings_detail,\n name='bookings-detail'\n )\n]\n"},{"location":"api-guide/versioning/#namespaceversioning","title":"NamespaceVersioning","text":"To the client, this scheme is the same as URLPathVersioning. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.
GET /v1/something/ HTTP/1.1\nHost: example.com\nAccept: application/json\n With this scheme the request.version attribute is determined based on the namespace that matches the incoming request path.
In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace:
# bookings/urls.py\nurlpatterns = [\n re_path(r'^$', bookings_list, name='bookings-list'),\n re_path(r'^(?P<pk>[0-9]+)/$', bookings_detail, name='bookings-detail')\n]\n\n# urls.py\nurlpatterns = [\n re_path(r'^v1/bookings/', include('bookings.urls', namespace='v1')),\n re_path(r'^v2/bookings/', include('bookings.urls', namespace='v2'))\n]\n Both URLPathVersioning and NamespaceVersioning are reasonable if you just need a simple versioning scheme. The URLPathVersioning approach might be better suitable for small ad-hoc projects, and the NamespaceVersioning is probably easier to manage for larger projects.
The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL.
For example the following is an HTTP request to the http://v1.example.com/bookings/ URL:
GET /bookings/ HTTP/1.1\nHost: v1.example.com\nAccept: application/json\n By default this implementation expects the hostname to match this simple regular expression:
^([a-zA-Z0-9]+)\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+$\n Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.
The HostNameVersioning scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as 127.0.0.1. There are various online tutorials on how to access localhost with a custom subdomain which you may find helpful in this case.
Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions.
"},{"location":"api-guide/versioning/#queryparameterversioning","title":"QueryParameterVersioning","text":"This scheme is a simple style that includes the version as a query parameter in the URL. For example:
GET /something/?version=0.1 HTTP/1.1\nHost: example.com\nAccept: application/json\n"},{"location":"api-guide/versioning/#custom-versioning-schemes","title":"Custom versioning schemes","text":"To implement a custom versioning scheme, subclass BaseVersioning and override the .determine_version method.
The following example uses a custom X-API-Version header to determine the requested version.
class XAPIVersionScheme(versioning.BaseVersioning):\n def determine_version(self, request, *args, **kwargs):\n return request.META.get('HTTP_X_API_VERSION', None)\n If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the .reverse() method on the class. See the source code for examples.
Django's class-based views are a welcome departure from the old-style views.
\u2014 Reinout van Rees
REST framework provides an APIView class, which subclasses Django's View class.
APIView classes are different from regular View classes in the following ways:
Request instances, not Django's HttpRequest instances.Response, instead of Django's HttpResponse. The view will manage content negotiation and setting the correct renderer on the response.APIException exceptions will be caught and mediated into appropriate responses.Using the APIView class is pretty much the same as using a regular View class, as usual, the incoming request is dispatched to an appropriate handler method such as .get() or .post(). Additionally, a number of attributes may be set on the class that control various aspects of the API policy.
For example:
from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import authentication, permissions\nfrom django.contrib.auth.models import User\n\nclass ListUsers(APIView):\n \"\"\"\n View to list all users in the system.\n\n * Requires token authentication.\n * Only admin users are able to access this view.\n \"\"\"\n authentication_classes = [authentication.TokenAuthentication]\n permission_classes = [permissions.IsAdminUser]\n\n def get(self, request, format=None):\n \"\"\"\n Return a list of all users.\n \"\"\"\n usernames = [user.username for user in User.objects.all()]\n return Response(usernames)\n Note
The full methods, attributes on, and relations between Django REST Framework's APIView, GenericAPIView, various Mixins, and Viewsets can be initially complex. In addition to the documentation here, the Classy Django REST Framework resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views.
The following attributes control the pluggable aspects of API views.
"},{"location":"api-guide/views/#renderer_classes","title":".renderer_classes","text":""},{"location":"api-guide/views/#parser_classes","title":".parser_classes","text":""},{"location":"api-guide/views/#authentication_classes","title":".authentication_classes","text":""},{"location":"api-guide/views/#throttle_classes","title":".throttle_classes","text":""},{"location":"api-guide/views/#permission_classes","title":".permission_classes","text":""},{"location":"api-guide/views/#content_negotiation_class","title":".content_negotiation_class","text":""},{"location":"api-guide/views/#api-policy-instantiation-methods","title":"API policy instantiation methods","text":"The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.
"},{"location":"api-guide/views/#get_renderersself","title":".get_renderers(self)","text":""},{"location":"api-guide/views/#get_parsersself","title":".get_parsers(self)","text":""},{"location":"api-guide/views/#get_authenticatorsself","title":".get_authenticators(self)","text":""},{"location":"api-guide/views/#get_throttlesself","title":".get_throttles(self)","text":""},{"location":"api-guide/views/#get_permissionsself","title":".get_permissions(self)","text":""},{"location":"api-guide/views/#get_content_negotiatorself","title":".get_content_negotiator(self)","text":""},{"location":"api-guide/views/#get_exception_handlerself","title":".get_exception_handler(self)","text":""},{"location":"api-guide/views/#api-policy-implementation-methods","title":"API policy implementation methods","text":"The following methods are called before dispatching to the handler method.
"},{"location":"api-guide/views/#check_permissionsself-request","title":".check_permissions(self, request)","text":""},{"location":"api-guide/views/#check_throttlesself-request","title":".check_throttles(self, request)","text":""},{"location":"api-guide/views/#perform_content_negotiationself-request-forcefalse","title":".perform_content_negotiation(self, request, force=False)","text":""},{"location":"api-guide/views/#dispatch-methods","title":"Dispatch methods","text":"The following methods are called directly by the view's .dispatch() method. These perform any actions that need to occur before or after calling the handler methods such as .get(), .post(), put(), patch() and .delete().
Performs any actions that need to occur before the handler method gets called. This method is used to enforce permissions and throttling, and perform content negotiation.
You won't typically need to override this method.
"},{"location":"api-guide/views/#handle_exceptionself-exc","title":".handle_exception(self, exc)","text":"Any exception thrown by the handler method will be passed to this method, which either returns a Response instance, or re-raises the exception.
The default implementation handles any subclass of rest_framework.exceptions.APIException, as well as Django's Http404 and PermissionDenied exceptions, and returns an appropriate error response.
If you need to customize the error responses your API returns you should subclass this method.
"},{"location":"api-guide/views/#initialize_requestself-request-args-kwargs","title":".initialize_request(self, request, *args, **kwargs)","text":"Ensures that the request object that is passed to the handler method is an instance of Request, rather than the usual Django HttpRequest.
You won't typically need to override this method.
"},{"location":"api-guide/views/#finalize_responseself-request-response-args-kwargs","title":".finalize_response(self, request, response, *args, **kwargs)","text":"Ensures that any Response object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.
You won't typically need to override this method.
"},{"location":"api-guide/views/#function-based-views","title":"Function Based Views","text":"Saying [that class-based views] is always the superior solution is a mistake.
\u2014 Nick Coghlan
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of Request (rather than the usual Django HttpRequest) and allows them to return a Response (instead of a Django HttpResponse), and allow you to configure how the request is processed.
Signature: @api_view(http_method_names=['GET'])
The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\n@api_view()\ndef hello_world(request):\n return Response({\"message\": \"Hello, world!\"})\n This view will use the default renderers, parsers, authentication classes etc specified in the settings.
By default only GET methods will be accepted. Other methods will respond with \"405 Method Not Allowed\". To alter this behavior, specify which methods the view allows, like so:
@api_view(['GET', 'POST'])\ndef hello_world(request):\n if request.method == 'POST':\n return Response({\"message\": \"Got some data!\", \"data\": request.data})\n return Response({\"message\": \"Hello, world!\"})\n"},{"location":"api-guide/views/#api-policy-decorators","title":"API policy decorators","text":"To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come after (below) the @api_view decorator. For example, to create a view that uses a throttle to ensure it can only be called once per day by a particular user, use the @throttle_classes decorator, passing a list of throttle classes:
from rest_framework.decorators import api_view, throttle_classes\nfrom rest_framework.throttling import UserRateThrottle\n\nclass OncePerDayUserThrottle(UserRateThrottle):\n rate = '1/day'\n\n@api_view(['GET'])\n@throttle_classes([OncePerDayUserThrottle])\ndef view(request):\n return Response({\"message\": \"Hello for today! See you tomorrow!\"})\n These decorators correspond to the attributes set on APIView subclasses, described above.
The available decorators are:
@renderer_classes(...)@parser_classes(...)@authentication_classes(...)@throttle_classes(...)@permission_classes(...)@content_negotiation_class(...)@metadata_class(...)@versioning_class(...)Each of these decorators is equivalent to setting their respective api policy attributes.
All decorators take a single argument. The ones that end with _class expect a single class while the ones ending in _classes expect a list or tuple of classes.
To override the default schema generation for function based views you may use the @schema decorator. This must come after (below) the @api_view decorator. For example:
from rest_framework.decorators import api_view, schema\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomAutoSchema(AutoSchema):\n def get_link(self, path, method, base_url):\n # override view introspection here...\n\n@api_view(['GET'])\n@schema(CustomAutoSchema())\ndef view(request):\n return Response({\"message\": \"Hello for today! See you tomorrow!\"})\n This decorator takes a single AutoSchema instance, an AutoSchema subclass instance or ManualSchema instance as described in the Schemas documentation. You may pass None in order to exclude the view from schema generation.
@api_view(['GET'])\n@schema(None)\ndef view(request):\n return Response({\"message\": \"Will not appear in schema!\"})\n"},{"location":"api-guide/viewsets/","title":"ViewSets","text":"After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.
\u2014 Ruby on Rails Documentation
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().
The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.
Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.
"},{"location":"api-guide/viewsets/#example","title":"Example","text":"Let's define a simple viewset that can be used to list or retrieve all the users in the system.
from django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404\nfrom myapps.serializers import UserSerializer\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nclass UserViewSet(viewsets.ViewSet):\n \"\"\"\n A simple ViewSet for listing or retrieving users.\n \"\"\"\n def list(self, request):\n queryset = User.objects.all()\n serializer = UserSerializer(queryset, many=True)\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None):\n queryset = User.objects.all()\n user = get_object_or_404(queryset, pk=pk)\n serializer = UserSerializer(user)\n return Response(serializer.data)\n If we need to, we can bind this viewset into two separate views, like so:
user_list = UserViewSet.as_view({'get': 'list'})\nuser_detail = UserViewSet.as_view({'get': 'retrieve'})\n Warning
Do not use .as_view() with @action methods. It bypasses router setup and may ignore action settings like permission_classes. Use DefaultRouter for actions.
Typically, we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.
from myapp.views import UserViewSet\nfrom rest_framework.routers import DefaultRouter\n\nrouter = DefaultRouter()\nrouter.register(r'users', UserViewSet, basename='user')\nurlpatterns = router.urls\n Warning
When registering viewsets, do not include a trailing slash in the prefix (e.g., use r'users', not r'users/'). Unlike standard Django URL patterns, DRF routers append slashes automatically based on your trailing slash configuration.
Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:
class UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset for viewing and editing user instances.\n \"\"\"\n serializer_class = UserSerializer\n queryset = User.objects.all()\n There are two main advantages of using a ViewSet class over using a View class.
queryset once, and it'll be used across multiple views.Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
"},{"location":"api-guide/viewsets/#viewset-actions","title":"ViewSet actions","text":"The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
class UserViewSet(viewsets.ViewSet):\n \"\"\"\n Example empty viewset demonstrating the standard\n actions that will be handled by a router class.\n\n If you're using format suffixes, make sure to also include\n the `format=None` keyword argument for each action.\n \"\"\"\n\n def list(self, request):\n pass\n\n def create(self, request):\n pass\n\n def retrieve(self, request, pk=None):\n pass\n\n def update(self, request, pk=None):\n pass\n\n def partial_update(self, request, pk=None):\n pass\n\n def destroy(self, request, pk=None):\n pass\n"},{"location":"api-guide/viewsets/#introspecting-viewset-actions","title":"Introspecting ViewSet actions","text":"During dispatch, the following attributes are available on the ViewSet.
basename - the base to use for the URL names that are created.action - the name of the current action (e.g., list, create).detail - boolean indicating if the current action is configured for a list or detail view.suffix - the display suffix for the viewset type - mirrors the detail attribute.name - the display name for the viewset. This argument is mutually exclusive to suffix.description - the display description for the individual view of a viewset.You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the list action similar to this:
def get_permissions(self):\n \"\"\"\n Instantiates and returns the list of permissions that this view requires.\n \"\"\"\n if self.action == 'list':\n permission_classes = [IsAuthenticated]\n else:\n permission_classes = [IsAdminUser]\n return [permission() for permission in permission_classes]\n Note
The action attribute is not available in the get_parsers, get_authenticators and get_content_negotiator methods, as it is set after they are called in the framework lifecycle. If you override one of these methods and try to access the action attribute in them, you will get an AttributeError error.
If you have ad-hoc methods that should be routable, you can mark them as such with the @action decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the detail argument to True or False. The router will configure its URL patterns accordingly. e.g., the DefaultRouter will configure detail actions to contain pk in their URL patterns.
A more complete example of extra actions:
from django.contrib.auth.models import User\nfrom rest_framework import status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom myapp.serializers import UserSerializer, PasswordSerializer\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n @action(detail=True, methods=['post'])\n def set_password(self, request, pk=None):\n user = self.get_object()\n serializer = PasswordSerializer(data=request.data)\n if serializer.is_valid():\n user.set_password(serializer.validated_data['password'])\n user.save()\n return Response({'status': 'password set'})\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=False)\n def recent_users(self, request):\n recent_users = User.objects.all().order_by('-last_login')\n\n page = self.paginate_queryset(recent_users)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(recent_users, many=True)\n return Response(serializer.data)\n The action decorator will route GET requests by default, but may also accept other HTTP methods by setting the methods argument. For example:
@action(detail=True, methods=['post', 'delete'])\n def unset_password(self, request, pk=None):\n ...\n Argument methods also supports HTTP methods defined as HTTPMethod. Example below is identical to the one above:
from http import HTTPMethod\n\n @action(detail=True, methods=[HTTPMethod.POST, HTTPMethod.DELETE])\n def unset_password(self, request, pk=None):\n ...\n The decorator allows you to override any viewset-level configuration such as permission_classes, serializer_class, filter_backends...:
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ...\n The two new actions will then be available at the urls ^users/{pk}/set_password/$ and ^users/{pk}/unset_password/$. Use the url_path and url_name parameters to change the URL segment and the reverse URL name of the action.
To view all extra actions, call the .get_extra_actions() method.
Extra actions can map additional HTTP methods to separate ViewSet methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.
@action(detail=True, methods=[\"put\"], name=\"Change Password\")\ndef password(self, request, pk=None):\n \"\"\"Update the user's password.\"\"\"\n ...\n\n\n@password.mapping.delete\ndef delete_password(self, request, pk=None):\n \"\"\"Delete the user's password.\"\"\"\n ...\n"},{"location":"api-guide/viewsets/#reversing-action-urls","title":"Reversing action URLs","text":"If you need to get the URL of an action, use the .reverse_action() method. This is a convenience wrapper for reverse(), automatically passing the view's request object and prepending the url_name with the .basename attribute.
Note that the basename is provided by the router during ViewSet registration. If you are not using a router, then you must provide the basename argument to the .as_view() method.
Using the example from the previous section:
>>> view.reverse_action(\"set-password\", args=[\"1\"])\n'http://localhost:8000/api/users/1/set_password'\n Alternatively, you can use the url_name attribute set by the @action decorator.
>>> view.reverse_action(view.set_password.url_name, args=[\"1\"])\n'http://localhost:8000/api/users/1/set_password'\n The url_name argument for .reverse_action() should match the same argument to the @action decorator. Additionally, this method can be used to reverse the default actions, such as list and create.
The ViewSet class inherits from APIView. You can use any of the standard attributes such as permission_classes, authentication_classes in order to control the API policy on the viewset.
The ViewSet class does not provide any implementations of actions. In order to use a ViewSet class you'll override the class and define the action implementations explicitly.
The GenericViewSet class inherits from GenericAPIView, and provides the default set of get_object, get_queryset methods and other generic view base behavior, but does not include any actions by default.
In order to use a GenericViewSet class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.
The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy().
Because ModelViewSet extends GenericAPIView, you'll normally need to provide at least the queryset and serializer_class attributes. For example:
class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n Note that you can use any of the standard attributes or method overrides provided by GenericAPIView. For example, to use a ViewSet that dynamically determines the queryset it should operate on, you might do something like this:
class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing the accounts\n associated with the user.\n \"\"\"\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n\n def get_queryset(self):\n return self.request.user.accounts.all()\n Note however that upon removal of the queryset property from your ViewSet, any associated router will be unable to derive the basename of your Model automatically, and so you will have to specify the basename kwarg as part of your router registration.
Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.
"},{"location":"api-guide/viewsets/#readonlymodelviewset","title":"ReadOnlyModelViewSet","text":"The ReadOnlyModelViewSet class also inherits from GenericAPIView. As with ModelViewSet it also includes implementations for various actions, but unlike ModelViewSet only provides the 'read-only' actions, .list() and .retrieve().
As with ModelViewSet, you'll normally need to provide at least the queryset and serializer_class attributes. For example:
class AccountViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A simple ViewSet for viewing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n Again, as with ModelViewSet, you can use any of the standard attributes and method overrides available to GenericAPIView.
You may need to provide custom ViewSet classes that do not have the full set of ModelViewSet actions, or that customize the behavior in some other way.
To create a base viewset class that provides create, list and retrieve operations, inherit from GenericViewSet, and mixin the required actions:
from rest_framework import mixins, viewsets\n\nclass CreateListRetrieveViewSet(mixins.CreateModelMixin,\n mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet):\n \"\"\"\n A viewset that provides `retrieve`, `create`, and `list` actions.\n\n To use it, override the class and set the `.queryset` and\n `.serializer_class` attributes.\n \"\"\"\n pass\n By creating your own base ViewSet classes, you can provide common behavior that can be reused in multiple viewsets across your API.
The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.
This release is incremental in nature. There are some breaking API changes, and upgrading will require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.
The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.
3.0 is the first of three releases that have been funded by our recent Kickstarter campaign.
As ever, a huge thank you to our many wonderful sponsors. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring.
"},{"location":"community/3.0-announcement/#new-features","title":"New features","text":"Notable features of this new release include:
ModelSerializer class and the explicit Serializer class.BaseSerializer class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.ListField and MultipleChoiceField.OPTIONS requests are handled by your API.Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two Kickstarter stretch goals - \"Feature improvements\" and \"Admin interface\". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
"},{"location":"community/3.0-announcement/#rest-framework-under-the-hood","title":"REST framework: Under the hood.","text":"This talk from the Django: Under the Hood event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.
Below is an in-depth guide to the API changes and migration notes for 3.0.
"},{"location":"community/3.0-announcement/#request-objects","title":"Request objects","text":""},{"location":"community/3.0-announcement/#the-data-and-query_params-properties","title":"The.data and .query_params properties.","text":"The usage of request.DATA and request.FILES is now pending deprecation in favor of a single request.data attribute that contains all the parsed data.
Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports.
You may now pass all the request data to a serializer class in a single argument:
# Do this...\nExampleSerializer(data=request.data)\n Instead of passing the files argument separately:
# Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES)\n The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params.
Previously the serializers used a two-step object creation, as follows:
serializer.object.serializer.save() would then save the object instance to the database.This style is in-line with how the ModelForm class works in Django, but is problematic for a number of reasons:
.save() is called.ExampleModel.objects.create(...). Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.We now use single-step object creation, like so:
serializer.validated_data.serializer.save() then saves and returns the new object instance.The resulting API changes are further detailed below.
"},{"location":"community/3.0-announcement/#the-create-and-update-methods","title":"The.create() and .update() methods.","text":"The .restore_object() method is now removed, and we instead have two separate methods, .create() and .update(). These methods work slightly different to the previous .restore_object().
When using the .create() and .update() methods you should both create and save the object instance. This is in contrast to the previous .restore_object() behavior that would instantiate the object but not save it.
These methods also replace the optional .save_object() method, which no longer exists.
The following example from the tutorial previously used restore_object() to handle both creating and updating object instances.
def restore_object(self, attrs, instance=None):\n if instance:\n # Update existing instance\n instance.title = attrs.get('title', instance.title)\n instance.code = attrs.get('code', instance.code)\n instance.linenos = attrs.get('linenos', instance.linenos)\n instance.language = attrs.get('language', instance.language)\n instance.style = attrs.get('style', instance.style)\n return instance\n\n # Create new instance\n return Snippet(**attrs)\n This would now be split out into two separate methods.
def update(self, instance, validated_data):\n instance.title = validated_data.get('title', instance.title)\n instance.code = validated_data.get('code', instance.code)\n instance.linenos = validated_data.get('linenos', instance.linenos)\n instance.language = validated_data.get('language', instance.language)\n instance.style = validated_data.get('style', instance.style)\n instance.save()\n return instance\n\ndef create(self, validated_data):\n return Snippet.objects.create(**validated_data)\n Note that these methods should return the newly created object instance.
"},{"location":"community/3.0-announcement/#use-validated_data-instead-of-object","title":"Use.validated_data instead of .object.","text":"You must now use the .validated_data attribute if you need to inspect the data before saving, rather than using the .object attribute, which no longer exists.
For example the following code is no longer valid:
if serializer.is_valid():\n name = serializer.object.name # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.object.user = request.user # Include the user when saving.\n serializer.save()\n Instead of using .object to inspect a partially constructed instance, you would now use .validated_data to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the .save() method as keyword arguments.
The corresponding code would now look like this:
if serializer.is_valid():\n name = serializer.validated_data['name'] # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.save(user=request.user) # Include the user when saving.\n"},{"location":"community/3.0-announcement/#using-is_validraise_exceptiontrue","title":"Using .is_valid(raise_exception=True)","text":"The .is_valid() method now takes an optional boolean flag, raise_exception.
Calling .is_valid(raise_exception=True) will cause a ValidationError to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code.
The handling and formatting of error responses may be altered globally by using the EXCEPTION_HANDLER settings key.
This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.
"},{"location":"community/3.0-announcement/#using-serializersvalidationerror","title":"Usingserializers.ValidationError.","text":"Previously serializers.ValidationError error was simply a synonym for django.core.exceptions.ValidationError. This has now been altered so that it inherits from the standard APIException base class.
The reason behind this is that Django's ValidationError class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers.
For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the serializers.ValidationError exception class, and not Django's built-in exception.
We strongly recommend that you use the namespaced import style of import serializers and not from serializers import ValidationError in order to avoid any potential confusion.
validate_<field_name>.","text":"The validate_<field_name> method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field:
def validate_score(self, attrs, source):\n if attrs['score'] % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return attrs\n This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.
def validate_score(self, value):\n if value % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return value\n Any ad-hoc validation that applies to more than one field should go in the .validate(self, attrs) method as usual.
Because .validate_<field_name> would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use .validate() instead.
You can either return non_field_errors from the validate method by raising a simple ValidationError
def validate(self, attrs):\n # serializer.errors == {'non_field_errors': ['A non field error']}\n raise serializers.ValidationError('A non field error')\n Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the ValidationError, like so:
def validate(self, attrs):\n # serializer.errors == {'my_field': ['A field error']}\n raise serializers.ValidationError({'my_field': 'A field error'})\n This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.
"},{"location":"community/3.0-announcement/#removal-of-transform_field_name","title":"Removal oftransform_<field_name>.","text":"The under-used transform_<field_name> on serializer classes is no longer provided. Instead you should just override to_representation() if you need to apply any modifications to the representation style.
For example:
def to_representation(self, instance):\n ret = super(UserSerializer, self).to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret\n Dropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches.
If you absolutely need to preserve transform_<field_name> behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example:
class BaseModelSerializer(ModelSerializer):\n \"\"\"\n A custom ModelSerializer class that preserves 2.x style `transform_<field_name>` behavior.\n \"\"\"\n def to_representation(self, instance):\n ret = super(BaseModelSerializer, self).to_representation(instance)\n for key, value in ret.items():\n method = getattr(self, 'transform_' + key, None)\n if method is not None:\n ret[key] = method(value)\n return ret\n"},{"location":"community/3.0-announcement/#differences-between-modelserializer-validation-and-modelform","title":"Differences between ModelSerializer validation and ModelForm.","text":"This change also means that we no longer use the .full_clean() method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on ModelSerializer classes that can't also be easily replicated on regular Serializer classes.
For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different.
The one difference that you do need to note is that the .clean() method will not be called as part of serializer validation, as it would be if using a ModelForm. Use the serializer .validate() method to perform a final validation step on incoming data where required.
There may be some cases where you really do need to keep validation logic in the model .clean() method, and cannot instead separate it into the serializer .validate(). You can do so by explicitly instantiating a model instance in the .validate() method.
def validate(self, attrs):\n instance = ExampleModel(**attrs)\n instance.clean()\n return attrs\n Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.
"},{"location":"community/3.0-announcement/#writable-nested-serialization","title":"Writable nested serialization.","text":"REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic:
None data.Using the depth option on ModelSerializer will now create read-only nested serializers by default.
If you try to use a writable nested serializer without writing a custom create() and/or update() method you'll see an assertion error when you attempt to save the serializer. For example:
>>> class ProfileSerializer(serializers.ModelSerializer):\n>>> class Meta:\n>>> model = Profile\n>>> fields = ['address', 'phone']\n>>>\n>>> class UserSerializer(serializers.ModelSerializer):\n>>> profile = ProfileSerializer()\n>>> class Meta:\n>>> model = User\n>>> fields = ['username', 'email', 'profile']\n>>>\n>>> data = {\n>>> 'username': 'lizzy',\n>>> 'email': 'lizzy@example.com',\n>>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n>>> }\n>>>\n>>> serializer = UserSerializer(data=data)\n>>> serializer.save()\nAssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.\n To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the create() and/or update() methods explicitly.
class UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ['username', 'email', 'profile']\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user\n The single-step object creation makes this far simpler and more obvious than the previous .restore_object() behavior.
Serializer instances now support a printable representation that allows you to inspect the fields present on the instance.
For instance, given the following example model:
class LocationRating(models.Model):\n location = models.CharField(max_length=100)\n rating = models.IntegerField()\n created_by = models.ForeignKey(User)\n Let's create a simple ModelSerializer class corresponding to the LocationRating model.
class LocationRatingSerializer(serializer.ModelSerializer):\n class Meta:\n model = LocationRating\n We can now inspect the serializer representation in the Django shell, using python manage.py shell...
>>> serializer = LocationRatingSerializer()\n>>> print(serializer) # Or use `print serializer` in Python 2.x\nLocationRatingSerializer():\n id = IntegerField(label='ID', read_only=True)\n location = CharField(max_length=100)\n rating = IntegerField()\n created_by = PrimaryKeyRelatedField(queryset=User.objects.all())\n"},{"location":"community/3.0-announcement/#the-extra_kwargs-option","title":"The extra_kwargs option.","text":"The write_only_fields option on ModelSerializer has been moved to PendingDeprecation and replaced with a more generic extra_kwargs.
class MySerializer(serializer.ModelSerializer):\n class Meta:\n model = MyModel\n fields = ['id', 'email', 'notes', 'is_admin']\n extra_kwargs = {\n 'is_admin': {'write_only': True}\n }\n Alternatively, specify the field explicitly on the serializer class:
class MySerializer(serializer.ModelSerializer):\n is_admin = serializers.BooleanField(write_only=True)\n\n class Meta:\n model = MyModel\n fields = ['id', 'email', 'notes', 'is_admin']\n The read_only_fields option remains as a convenient shortcut for the more common case.
HyperlinkedModelSerializer.","text":"The view_name and lookup_field options have been moved to PendingDeprecation. They are no longer required, as you can use the extra_kwargs argument instead:
class MySerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = MyModel\n fields = ['url', 'email', 'notes', 'is_admin']\n extra_kwargs = {\n 'url': {'lookup_field': 'uuid'}\n }\n Alternatively, specify the field explicitly on the serializer class:
class MySerializer(serializer.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='mymodel-detail',\n lookup_field='uuid'\n )\n\n class Meta:\n model = MyModel\n fields = ['url', 'email', 'notes', 'is_admin']\n"},{"location":"community/3.0-announcement/#fields-for-model-methods-and-properties","title":"Fields for model methods and properties.","text":"With ModelSerializer you can now specify field names in the fields option that refer to model methods or properties. For example, suppose you have the following model:
class Invitation(models.Model):\n created = models.DateTimeField()\n to_email = models.EmailField()\n message = models.CharField(max_length=1000)\n\n def expiry_date(self):\n return self.created + datetime.timedelta(days=30)\n You can include expiry_date as a field option on a ModelSerializer class.
class InvitationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Invitation\n fields = ['to_email', 'message', 'expiry_date']\n These fields will be mapped to serializers.ReadOnlyField() instances.
>>> serializer = InvitationSerializer()\n>>> print(repr(serializer))\nInvitationSerializer():\n to_email = EmailField(max_length=75)\n message = CharField(max_length=1000)\n expiry_date = ReadOnlyField()\n"},{"location":"community/3.0-announcement/#the-listserializer-class","title":"The ListSerializer class.","text":"The ListSerializer class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.
class MultipleUserSerializer(ListSerializer):\n child = UserSerializer()\n You can also still use the many=True argument to serializer classes. It's worth noting that many=True argument transparently creates a ListSerializer instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.
You will typically want to continue to use the existing many=True flag rather than declaring ListSerializer classes explicitly, but declaring the classes explicitly can be useful if you need to write custom create or update methods for bulk updates, or provide for other custom behavior.
See also the new ListField class, which validates input in the same way, but does not include the serializer interfaces of .is_valid(), .data, .save() and so on.
BaseSerializer class.","text":"REST framework now includes a simple 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 an 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.
BaseSerializer classes.","text":"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):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField()\n It's simple to create a read-only serializer for converting HighScore instances into primitive data types.
class HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n We can now use this class to serialize single HighScore instances:
@api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data)\n Or use it to serialize multiple instances:
@api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)\n"},{"location":"community/3.0-announcement/#read-write-baseserializer-classes","title":"Read-write BaseSerializer classes.","text":"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 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):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) > 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)\n"},{"location":"community/3.0-announcement/#creating-new-generic-serializers-with-baseserializer","title":"Creating new generic serializers with BaseSerializer.","text":"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):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name.startswith('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)\n"},{"location":"community/3.0-announcement/#serializer-fields","title":"Serializer fields","text":""},{"location":"community/3.0-announcement/#the-field-and-readonly-field-classes","title":"The Field and ReadOnly field classes.","text":"There are some minor tweaks to the field base classes.
Previously we had these two base classes:
Field as the base class for read-only fields. A default implementation was included for serializing data.WritableField as the base class for read-write fields.We now use the following:
Field is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.ReadOnlyField is a concrete implementation for read-only fields that simply returns the attribute value without modification.required, allow_null, allow_blank and default arguments.","text":"REST framework now has more explicit and clear control over validating empty values for fields.
Previously the meaning of the required=False keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be None or the empty string.
We now have a better separation, with separate required, allow_null and allow_blank arguments.
The following set of arguments are used to control validation of empty values:
required=False: The value does not need to be present in the input, and will not be passed to .create() or .update() if it is not seen.default=<value>: The value does not need to be present in the input, and a default value will be passed to .create() or .update() if it is not seen.allow_null=True: None is a valid input.allow_blank=True: '' is valid input. For CharField and subclasses only.Typically you'll want to use required=False if the corresponding model field has a default value, and additionally set either allow_null=True or allow_blank=True if required.
The default argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the required argument when a default is specified, and doing so will result in an error.
The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an IntegerField would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior.
.validate().","text":"The .validate() method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override to_internal_value().
class UppercaseCharField(serializers.CharField):\n def to_internal_value(self, data):\n value = super(UppercaseCharField, self).to_internal_value(data)\n if value != value.upper():\n raise serializers.ValidationError('The input should be uppercase only.')\n return value\n Previously validation errors could be raised in either .to_native() or .validate(), making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.
ListField class.","text":"The ListField class has now been added. This field validates list input. It takes a child keyword argument which is used to specify the field used to validate each item in the list. For example:
scores = ListField(child=IntegerField(min_value=0, max_value=100))\n You can also use a declarative style to create new subclasses of ListField, like this:
class ScoresField(ListField):\n child = IntegerField(min_value=0, max_value=100)\n We can now use the ScoresField class inside another serializer:
scores = ScoresField()\n See also the new ListSerializer class, which validates input in the same way, but also includes the serializer interfaces of .is_valid(), .data, .save() and so on.
ChoiceField class may now accept a flat list.","text":"The ChoiceField class may now accept a list of choices in addition to the existing style of using a list of pairs of (name, display_value). The following is now valid:
color = ChoiceField(choices=['red', 'green', 'blue'])\n"},{"location":"community/3.0-announcement/#the-multiplechoicefield-class","title":"The MultipleChoiceField class.","text":"The MultipleChoiceField class has been added. This field acts like ChoiceField, but returns a set, which may include none, one or many of the valid choices.
The from_native(self, value) and to_native(self, data) method names have been replaced with the more obviously named to_internal_value(self, data) and to_representation(self, value).
The field_from_native() and field_to_native() methods are removed. Previously you could use these methods if you wanted to customize the behavior in a way that did not simply lookup the field value from the object. For example...
def field_to_native(self, obj, field_name):\n \"\"\"A custom read-only field that returns the class name.\"\"\"\n return obj.__class__.__name__\n Now if you need to access the entire object you'll instead need to override one or both of the following:
get_attribute to modify the attribute value passed to to_representation().get_value to modify the data value passed to_internal_value().For example:
def get_attribute(self, obj):\n # Pass the entire object through to `to_representation()`,\n # instead of the standard attribute lookup.\n return obj\n\ndef to_representation(self, value):\n return value.__class__.__name__\n"},{"location":"community/3.0-announcement/#explicit-queryset-required-on-relational-fields","title":"Explicit queryset required on relational fields.","text":"Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a ModelSerializer.
This code would be valid in 2.4.3:
class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n class Meta:\n model = Account\n However this code would not be valid in 3.0:
# Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n def restore_object(self, attrs, instance=None):\n # ...\n The queryset argument is now always required for writable relational fields. This removes some magic and makes it easier and more obvious to move between implicit ModelSerializer classes and explicit Serializer classes.
class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(\n slug_field='name',\n queryset=Organization.objects.all()\n )\n\n class Meta:\n model = Account\n The queryset argument is only ever required for writable fields, and is not required or valid for fields with read_only=True.
SerializerMethodField.","text":"The argument to SerializerMethodField is now optional, and defaults to get_<field_name>. For example the following is valid:
class AccountSerializer(serializers.Serializer):\n # `method_name='get_billing_details'` by default.\n billing_details = serializers.SerializerMethodField()\n\n def get_billing_details(self, account):\n return calculate_billing(account)\n In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code will raise an error:
billing_details = serializers.SerializerMethodField('get_billing_details')\n"},{"location":"community/3.0-announcement/#enforcing-consistent-source-usage","title":"Enforcing consistent source usage.","text":"I've see several codebases that unnecessarily include the source argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that source is usually not required.
The following usage will now raise an error:
email = serializers.EmailField(source='email')\n"},{"location":"community/3.0-announcement/#the-uniquevalidator-and-uniquetogethervalidator-classes","title":"The UniqueValidator and UniqueTogetherValidator classes.","text":"REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit Serializer class instead of using ModelSerializer.
The UniqueValidator should be applied to a serializer field, and takes a single queryset argument.
from rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\nclass OrganizationSerializer(serializers.Serializer):\n url = serializers.HyperlinkedIdentityField(view_name='organization_detail')\n created = serializers.DateTimeField(read_only=True)\n name = serializers.CharField(\n max_length=100,\n validators=UniqueValidator(queryset=Organization.objects.all())\n )\n The UniqueTogetherValidator should be applied to a serializer, and takes a queryset argument and a fields argument which should be a list or tuple of field names.
class RaceResultSerializer(serializers.Serializer):\n category = serializers.ChoiceField(['5k', '10k'])\n position = serializers.IntegerField()\n name = serializers.CharField(max_length=100)\n\n class Meta:\n validators = [UniqueTogetherValidator(\n queryset=RaceResult.objects.all(),\n fields=['category', 'position']\n )]\n"},{"location":"community/3.0-announcement/#the-uniquefordatevalidator-classes","title":"The UniqueForDateValidator classes.","text":"REST framework also now includes explicit validator classes for validating the unique_for_date, unique_for_month, and unique_for_year model field constraints. These are used internally instead of calling into Model.full_clean().
These classes are documented in the Validators section of the documentation.
"},{"location":"community/3.0-announcement/#generic-views","title":"Generic views","text":""},{"location":"community/3.0-announcement/#simplification-of-view-logic","title":"Simplification of view logic.","text":"The view logic for the default method handlers has been significantly simplified, due to the new serializers API.
"},{"location":"community/3.0-announcement/#changes-to-prepost-save-hooks","title":"Changes to pre/post save hooks.","text":"The pre_save and post_save hooks no longer exist, but are replaced with perform_create(self, serializer) and perform_update(self, serializer).
These methods should save the object instance by calling serializer.save(), adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.
For example:
def perform_create(self, serializer):\n # Include the owner attribute directly, rather than from request data.\n instance = serializer.save(owner=self.request.user)\n # Perform a custom post-save action.\n send_email(instance.to_email, instance.message)\n The pre_delete and post_delete hooks no longer exist, and are replaced with .perform_destroy(self, instance), which should delete the instance and perform any custom actions.
def perform_destroy(self, instance):\n # Perform a custom pre-delete action.\n send_deletion_alert(user=instance.created_by, deleted=instance)\n # Delete the object instance.\n instance.delete()\n"},{"location":"community/3.0-announcement/#removal-of-view-attributes","title":"Removal of view attributes.","text":"The .object and .object_list attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic.
I would personally recommend that developers treat view instances as immutable objects in their application code.
"},{"location":"community/3.0-announcement/#put-as-create","title":"PUT as create.","text":"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 we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.
If you need to restore the previous behavior you may want to include this AllowPUTAsCreateMixin class as a mixin to your views.
The generic views now raise ValidationFailed exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a 400 Bad Request response directly.
This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.
"},{"location":"community/3.0-announcement/#the-metadata-api","title":"The metadata API","text":"Behavior for dealing with OPTIONS requests was previously built directly into the class-based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.
This makes it far easier to use a different style for OPTIONS responses throughout your API, and makes it possible to create third-party metadata policies.
REST framework 3.0 includes templated HTML form rendering for serializers.
This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.
Significant changes that you do need to be aware of include:
UserSerializer with a nested ProfileSerializer will now render a nested fieldset when used in the browsable API.widget option is no longer available for serializer fields. You can instead control the template that is used for a given field, by using the style dictionary.style keyword argument for serializer fields.","text":"The style keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the HTMLFormRenderer uses the base_template key to determine which template to render the field with.
For example, to use a textarea control instead of the default input control, you would use the following\u2026
additional_notes = serializers.CharField(\n style={'base_template': 'textarea.html'}\n)\n Similarly, to use a radio button control instead of the default select control, you would use the following\u2026
color_channel = serializers.ChoiceField(\n choices=['red', 'blue', 'green'],\n style={'base_template': 'radio.html'}\n)\n This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.
"},{"location":"community/3.0-announcement/#api-style","title":"API style","text":"There are some improvements in the default style we use in our API responses.
"},{"location":"community/3.0-announcement/#unicode-json-by-default","title":"Unicode JSON by default.","text":"Unicode JSON is now the default. The UnicodeJSONRenderer class no longer exists, and the UNICODE_JSON setting has been added. To revert this behavior use the new setting:
REST_FRAMEWORK = {\n 'UNICODE_JSON': False\n}\n"},{"location":"community/3.0-announcement/#compact-json-by-default","title":"Compact JSON by default.","text":"We now output compact JSON in responses by default. For example, we return:
{\"email\":\"amy@example.com\",\"is_admin\":true}\n Instead of the following:
{\"email\": \"amy@example.com\", \"is_admin\": true}\n The COMPACT_JSON setting has been added, and can be used to revert this behavior if needed:
REST_FRAMEWORK = {\n 'COMPACT_JSON': False\n}\n"},{"location":"community/3.0-announcement/#file-fields-as-urls","title":"File fields as URLs","text":"The FileField and ImageField classes are now represented as URLs by default. You should ensure you set Django's standard MEDIA_URL setting appropriately, and ensure your application serves the uploaded files.
You can revert this behavior, and display filenames in the representation by using the UPLOADED_FILES_USE_URL settings key:
REST_FRAMEWORK = {\n 'UPLOADED_FILES_USE_URL': False\n}\n You can also modify serializer fields individually, using the use_url argument:
uploaded_file = serializers.FileField(use_url=False)\n Also note that you should pass the request object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form https://example.com/url_path/filename.txt. For example:
context = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data)\n If the request is omitted from the context, the returned URLs will be of the form /url_path/filename.txt.
Retry-After.","text":"The custom X-Throttle-Wait-Second header has now been dropped in favor of the standard Retry-After header. You can revert this behavior if needed by writing a custom exception handler for your application.
Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as Date, Time and DateTime objects, and later coerced to strings by the renderer.
You can modify this behavior globally by settings the existing DATE_FORMAT, DATETIME_FORMAT and TIME_FORMAT settings keys. Setting these values to None instead of their default value of 'iso-8601' will result in native objects being returned in serializer data.
REST_FRAMEWORK = {\n # Return native `Date` and `Time` objects in `serializer.data`\n 'DATETIME_FORMAT': None\n 'DATE_FORMAT': None\n 'TIME_FORMAT': None\n}\n You can also modify serializer fields individually, using the date_format, time_format and datetime_format arguments:
# Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None)\n"},{"location":"community/3.0-announcement/#decimals-as-strings-in-serializer-data","title":"Decimals as strings in serializer data.","text":"Decimals are now coerced to strings by default in the serializer output. Previously they were returned as Decimal objects, and later coerced to strings by the renderer.
You can modify this behavior globally by using the COERCE_DECIMAL_TO_STRING settings key.
REST_FRAMEWORK = {\n 'COERCE_DECIMAL_TO_STRING': False\n}\n Or modify it on an individual serializer field, using the coerce_to_string keyword argument.
# Return `Decimal` instances in `serializer.data`, not strings.\namount = serializers.DecimalField(\n max_digits=10,\n decimal_places=2,\n coerce_to_string=False\n)\n The default JSON renderer will return float objects for un-coerced Decimal instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.
ChoiceField does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.APIException subclasses could previously take any arbitrary type in the detail argument. These exceptions now use translatable text strings, and as a result call force_text on the detail argument, which must be a string. If you need complex arguments to an APIException class, you should subclass it and override the __init__() method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.
The 3.1 release is planned to address improvements in the following components:
The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.
You can follow development on the GitHub site, where we use milestones to indicate planning timescales.
"},{"location":"community/3.1-announcement/","title":"Django REST framework 3.1","text":"The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality.
Some highlights include:
HStoreField and ArrayField.The pagination API has been improved, making it both easier to use, and more powerful.
A guide to the headline features follows. For full details, see the pagination documentation.
Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes.
PAGINATE_BY settings key will continue to work but is now pending deprecation. The more obviously named PAGE_SIZE settings key should now be used instead.PAGINATE_BY_PARAM, MAX_PAGINATE_BY settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.paginate_by, page_query_param, paginate_by_param and max_paginate_by generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.pagination_serializer_class view attribute and DEFAULT_PAGINATION_SERIALIZER_CLASS settings key are no longer valid. The pagination API does not use serializers to determine the output format, and you'll need to instead override the get_paginated_response method on a pagination class in order to specify how the output format is controlled.Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default.
The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for this blog post on the subject.
"},{"location":"community/3.1-announcement/#pagination-controls-in-the-browsable-api","title":"Pagination controls in the browsable API.","text":"Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API:
The cursor based pagination renders a more simple style of control:
"},{"location":"community/3.1-announcement/#support-for-header-based-pagination","title":"Support for header-based pagination.","text":"The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the Link or Content-Range headers.
For more information, see the custom pagination styles documentation.
"},{"location":"community/3.1-announcement/#versioning","title":"Versioning","text":"We've made it easier to build versioned APIs. Built-in schemes for versioning include both URL based and Accept header based variations.
When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request.
For example, when using NamespaceVersioning, and the following hyperlinked serializer:
class AccountsSerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = Accounts\n fields = ['account_name', 'users']\n The output representation would match the version used on the incoming request. Like so:
GET http://example.org/v2/accounts/10 # Version 'v2'\n\n{\n \"account_name\": \"europa\",\n \"users\": [\n \"http://example.org/v2/users/12\", # Version 'v2'\n \"http://example.org/v2/users/54\",\n \"http://example.org/v2/users/87\"\n ]\n}\n"},{"location":"community/3.1-announcement/#internationalization","title":"Internationalization","text":"REST framework now includes a built-in set of translations, and supports internationalized error responses. This allows you to either change the default language, or to allow clients to specify the language via the Accept-Language header.
You can change the default language by using the standard Django LANGUAGE_CODE setting:
LANGUAGE_CODE = \"es-es\"\n You can turn on per-request language requests by adding LocalMiddleware to your MIDDLEWARE_CLASSES setting:
MIDDLEWARE_CLASSES = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n]\n When per-request internationalization is enabled, client requests will respect the Accept-Language header where possible. For example, let's make a request for an unsupported media type:
Request
GET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org\n Response
HTTP/1.0 406 NOT ACCEPTABLE\n\n{\n \"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"\n}\n Note that the structure of the error responses is still the same. We still have a detail key in the response. If needed you can modify this behavior too, by using a custom exception handler.
We include built-in translations both for standard exception cases, and for serializer validation errors.
The full list of supported languages can be found on our Transifex project page.
If you only wish to support a subset of the supported languages, use Django's standard LANGUAGES setting:
LANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n]\n For more details, see the internationalization documentation.
Many thanks to Craig Blaszczyk for helping push this through.
"},{"location":"community/3.1-announcement/#new-field-types","title":"New field types","text":"Django 1.8's new ArrayField, HStoreField and UUIDField are now all fully supported.
This work also means that we now have both serializers.DictField(), and serializers.ListField() types, allowing you to express and validate a wider set of representations.
If you're building a new 1.8 project, then you should probably consider using UUIDField as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style:
http://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d\n"},{"location":"community/3.1-announcement/#modelserializer-api","title":"ModelSerializer API","text":"The serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships.
For more information, see the documentation on customizing field mappings for ModelSerializer classes.
"},{"location":"community/3.1-announcement/#moving-packages-out-of-core","title":"Moving packages out of core","text":"We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to pip install the new packages, and change any import paths.
We're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework.
The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained Django OAuth toolkit has now been promoted as our recommended option for integrating OAuth support.
The following packages are now moved out of core and should be separately installed:
It's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do:
pip install djangorestframework-xml\n And modify your settings, like so:
REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n 'rest_framework_xml.renderers.XMLRenderer'\n ]\n}\n Thanks go to the latest member of our maintenance team, Jos\u00e9 Padilla, for handling this work and taking on ownership of these packages.
"},{"location":"community/3.1-announcement/#deprecations","title":"Deprecations","text":"The request.DATA, request.FILES and request.QUERY_PARAMS attributes move from pending deprecation, to deprecated. Use request.data and request.query_params instead, as discussed in the 3.0 release notes.
The ModelSerializer Meta options for write_only_fields, view_name and lookup_field are also moved from pending deprecation, to deprecated. Use extra_kwargs instead, as discussed in the 3.0 release notes.
All these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2.
"},{"location":"community/3.1-announcement/#whats-next","title":"What's next?","text":"The next focus will be on HTML renderings of API output and will include:
This will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release.
"},{"location":"community/3.10-announcement/","title":"3.10 Announcement","text":""},{"location":"community/3.10-announcement/#django-rest-framework-310","title":"Django REST framework 3.10","text":"The 3.10 release drops support for Python 2.
Since we first introduced schema support in Django REST Framework 3.5, OpenAPI has emerged as the widely adopted standard for modeling Web APIs.
This release begins the deprecation process for the CoreAPI based schema generation, and introduces OpenAPI schema generation in its place.
"},{"location":"community/3.10-announcement/#continuing-to-use-coreapi","title":"Continuing to use CoreAPI","text":"If you're currently using the CoreAPI schemas, you'll need to make sure to update your REST framework settings to include DEFAULT_SCHEMA_CLASS explicitly.
settings.py:
REST_FRAMEWORK = {\n ...: ...,\n \"DEFAULT_SCHEMA_CLASS\": \"rest_framework.schemas.coreapi.AutoSchema\",\n}\n You'll still be able to keep using CoreAPI schemas, API docs, and client for the foreseeable future. We'll aim to ensure that the CoreAPI schema generator remains available as a third party package, even once it has eventually been removed from REST framework, scheduled for version 3.12.
We have removed the old documentation for the CoreAPI based schema generation. You may view the Legacy CoreAPI documentation here.
"},{"location":"community/3.10-announcement/#openapi-quickstart","title":"OpenAPI Quickstart","text":"You can generate a static OpenAPI schema, using the generateschema management command.
Alternately, to have the project serve an API schema, use the get_schema_view() shortcut.
In your urls.py:
from rest_framework.schemas import get_schema_view\n\nurlpatterns = [\n # ...\n # Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.\n # * `title` and `description` parameters are passed to `SchemaGenerator`.\n # * Provide view name for use with `reverse()`.\n path(\n \"openapi\",\n get_schema_view(title=\"Your Project\", description=\"API for all things \u2026\"),\n name=\"openapi-schema\",\n ),\n # ...\n]\n"},{"location":"community/3.10-announcement/#customization","title":"Customization","text":"For customizations that you want to apply across the entire API, you can subclass rest_framework.schemas.openapi.SchemaGenerator and provide it as an argument to the generateschema command or get_schema_view() helper function.
For specific per-view customizations, you can subclass AutoSchema, making sure to set schema = <YourCustomClass> on the view.
For more details, see the API Schema documentation.
"},{"location":"community/3.10-announcement/#api-documentation","title":"API Documentation","text":"There are some great third party options for documenting your API, based on the OpenAPI schema.
See the Documenting you API section for more details.
"},{"location":"community/3.10-announcement/#feature-roadmap","title":"Feature Roadmap","text":"Given that our OpenAPI schema generation is a new feature, it's likely that there will still be some iterative improvements for us to make. There will be two main cases here:
We'll aim to bring the first type of change quickly in point releases. For the second kind we'd like to adopt a slower approach, to make sure we keep the API simple, and as widely applicable as possible, before we bring in API changes.
It's also possible that we'll end up implementing API documentation and API client tooling that are driven by the OpenAPI schema. The apistar project has a significant amount of work towards this. However, if we do so, we'll plan on keeping any tooling outside of the core framework.
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.
Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, ESG, Rollbar, Cadre, Kloudless, and Lights On Software.
"},{"location":"community/3.11-announcement/","title":"3.11 Announcement","text":""},{"location":"community/3.11-announcement/#django-rest-framework-311","title":"Django REST framework 3.11","text":"The 3.11 release adds support for Django 3.0.
This release will be the last to support Python 3.5 or Django 1.11.
"},{"location":"community/3.11-announcement/#openapi-schema-generation-improvements","title":"OpenAPI Schema Generation Improvements","text":"The OpenAPI schema generation continues to mature. Some highlights in 3.11 include:
In this example view operation descriptions for the get and post methods will be extracted from the class docstring:
class DocStringExampleListView(APIView):\n \"\"\"\n get: A description of my GET operation.\n post: A description of my POST operation.\n \"\"\"\n\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n\n def get(self, request, *args, **kwargs): ...\n\n def post(self, request, *args, **kwargs): ...\n"},{"location":"community/3.11-announcement/#validator-default-context","title":"Validator / Default Context","text":"In some circumstances a Validator class or a Default class may need to access the serializer field with which it is called, or the .context with which the serializer was instantiated. In particular:
CurrentUserDefault needs to be able to determine the context with which the serializer was instantiated, in order to return the current user instance.Our previous approach to this was that implementations could include a set_context method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13.
Instead, validators or defaults which require the serializer context, should include a requires_context = True attribute on the class.
The __call__ method should then include an additional serializer_field argument.
Validator implementations will look like this:
class CustomValidator:\n requires_context = True\n\n def __call__(self, value, serializer_field): ...\n Default implementations will look like this:
class CustomDefault:\n requires_context = True\n\n def __call__(self, serializer_field): ...\n"},{"location":"community/3.11-announcement/#funding","title":"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.
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.
"},{"location":"community/3.12-announcement/","title":"3.12 Announcement","text":""},{"location":"community/3.12-announcement/#django-rest-framework-312","title":"Django REST framework 3.12","text":"REST framework 3.12 brings a handful of refinements to the OpenAPI schema generation, plus support for Django's new database-agnostic JSONField, and some improvements to the SearchFilter class.
Open API schemas will now automatically include tags, based on the first element in the URL path.
For example...
Method Path TagsGET, PUT, PATCH, DELETE /users/{id}/ ['users'] GET, POST /users/ ['users'] GET, PUT, PATCH, DELETE /orders/{id}/ ['orders'] GET, POST /orders/ ['orders'] The tags used for a particular view may also be overridden...
class MyOrders(APIView):\n schema = AutoSchema(tags=[\"users\", \"orders\"])\n ...\n See the schema documentation for more information.
"},{"location":"community/3.12-announcement/#customizing-the-operation-id","title":"Customizing the operation ID.","text":"REST framework automatically determines operation IDs to use in OpenAPI schemas. The latest version provides more control for overriding the behavior used to generate the operation IDs.
See the schema documentation for more information.
"},{"location":"community/3.12-announcement/#support-for-openapi-components","title":"Support for OpenAPI components.","text":"In order to output more graceful OpenAPI schemes, REST framework 3.12 now defines components in the schema, and then references them inside request and response objects. This is in contrast with the previous approach, which fully expanded the request and response bodies for each operation.
The names used for a component default to using the serializer class name, but may be overridden if needed...
class MyOrders(APIView):\n schema = AutoSchema(component_name=\"OrderDetails\")\n"},{"location":"community/3.12-announcement/#more-public-api","title":"More Public API","text":"Many methods on the AutoSchema class have now been promoted to public API, allowing you to more fully customize the schema generation. The following methods are now available for overriding...
get_path_parametersget_pagination_parametersget_filter_parametersget_request_bodyget_responsesget_serializerget_paginatormap_serializermap_fieldmap_choice_fieldmap_field_validatorsallows_filters.See the schema docs for details on using custom AutoSchema subclasses.
Django 3.1 deprecated the existing django.contrib.postgres.fields.JSONField in favor of a new database-agnositic JSONField.
REST framework 3.12 now supports this new model field, and ModelSerializer classes will correctly map the model field.
There are a couple of significant improvements to the SearchFilter class.
The class now supports nested search within JSONField and HStoreField, using the double underscore notation for traversing which element of the field the search should apply to.
class SitesSearchView(generics.ListAPIView):\n \"\"\"\n An API view to return a list of archaeological sites, optionally filtered\n by a search against the site name or location. (Location searches are\n matched against the region and country names.)\n \"\"\"\n\n queryset = Sites.objects.all()\n serializer_class = SitesSerializer\n filter_backends = [filters.SearchFilter]\n search_fields = [\"site_name\", \"location__region\", \"location__country\"]\n"},{"location":"community/3.12-announcement/#searches-against-annotate-fields","title":"Searches against annotate fields","text":"Django allows querysets to create additional virtual fields, using the .annotate method. We now support searching against annotate fields.
class PublisherSearchView(generics.ListAPIView):\n \"\"\"\n Search for publishers, optionally filtering the search against the average\n rating of all their books.\n \"\"\"\n\n queryset = Publisher.objects.annotate(avg_rating=Avg(\"book__rating\"))\n serializer_class = PublisherSerializer\n filter_backends = [filters.SearchFilter]\n search_fields = [\"avg_rating\"]\n"},{"location":"community/3.12-announcement/#deprecations","title":"Deprecations","text":""},{"location":"community/3.12-announcement/#serializersnullbooleanfield","title":"serializers.NullBooleanField","text":"serializers.NullBooleanField is now pending deprecation, and will be removed in 3.14.
Instead use serializers.BooleanField field and set allow_null=True which does the same thing.
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.
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.
"},{"location":"community/3.13-announcement/","title":"3.13 Announcement","text":""},{"location":"community/3.13-announcement/#django-rest-framework-313","title":"Django REST framework 3.13","text":""},{"location":"community/3.13-announcement/#django-40-support","title":"Django 4.0 support","text":"The latest release now fully supports Django 4.0.
Our requirements are now:
When instantiating fields on serializers, you should always use keyword arguments, such as serializers.CharField(max_length=200). This has always been the case, and all the examples that we have in the documentation use keyword arguments, rather than positional arguments.
From REST framework 3.13 onwards, this is now explicitly enforced.
The most feasible cases where users might be accidentally omitting the keyword arguments are likely in the composite fields, ListField and DictField. For instance...
aliases = serializers.ListField(serializers.CharField())\n They must now use the more explicit keyword argument style...
aliases = serializers.ListField(child=serializers.CharField())\n This change has been made because using positional arguments here does not result in the expected behavior.
See Pull Request #7632 for more details.
"},{"location":"community/3.14-announcement/","title":"3.14 Announcement","text":""},{"location":"community/3.14-announcement/#django-rest-framework-314","title":"Django REST framework 3.14","text":""},{"location":"community/3.14-announcement/#django-41-support","title":"Django 4.1 support","text":"The latest release now fully supports Django 4.1, and drops support for Django 2.2.
Our requirements are now:
raise_exception argument for is_valid is now keyword-only.","text":"Calling serializer_instance.is_valid(True) is no longer acceptable syntax. If you'd like to use the raise_exception argument, you must use it as a keyword argument.
See Pull Request #7952 for more details.
"},{"location":"community/3.14-announcement/#manyrelatedfield-supports-returning-the-default-when-the-source-attribute-doesnt-exist","title":"ManyRelatedField supports returning the default when the source attribute doesn't exist.","text":"Previously, if you used a serializer field with many=True with a dot notated source field that didn't exist, it would raise an AttributeError. Now it will return the default or be skipped depending on the other arguments.
See Pull Request #7574 for more details.
"},{"location":"community/3.14-announcement/#make-open-api-get_reference-public","title":"Make Open APIget_reference public.","text":"Returns a reference to the serializer component. This may be useful if you override get_schema().
When OR-ing two permissions, the request has to pass either class's has_permission() and has_object_permission().
Previously, both class's has_permission() was ignored when OR-ing two permissions together.
See Pull Request #7522 for more details.
"},{"location":"community/3.14-announcement/#minor-fixes-and-improvements","title":"Minor fixes and improvements","text":"There are a number of minor fixes and improvements in this release. See the release notes page for a complete listing.
"},{"location":"community/3.14-announcement/#deprecations","title":"Deprecations","text":""},{"location":"community/3.14-announcement/#serializersnullbooleanfield","title":"serializers.NullBooleanField","text":"serializers.NullBooleanField was moved to pending deprecation in 3.12, and deprecated in 3.13. It has now been removed from the core framework.
Instead use serializers.BooleanField field and set allow_null=True which does the same thing.
At the Internet, on March 15th, 2024, with 176 commits by 138 authors, we are happy to announce the release of Django REST framework 3.15.
"},{"location":"community/3.15-announcement/#django-50-and-python-312-support","title":"Django 5.0 and Python 3.12 support","text":"The latest release now fully supports Django 5.0 and Python 3.12.
The current minimum versions of Django still is 3.0 and Python 3.6.
"},{"location":"community/3.15-announcement/#primary-support-of-uniqueconstraint","title":"Primary Support of UniqueConstraint","text":"ModelSerializer generates validators for UniqueConstraint (both UniqueValidator and UniqueTogetherValidator)
By default the URLs created by SimpleRouter use regular expressions. This behavior can be modified by setting the use_regex_path argument to False when instantiating the router.
Dependency on pytz has been removed and deprecation warnings have been added, Django will provide ZoneInfo instances as long as USE_DEPRECATED_PYTZ is not enabled. More info on the migration can be found in this guide.
"},{"location":"community/3.15-announcement/#align-searchfilter-behavior-to-djangocontribadmin-search","title":"AlignSearchFilter behavior to django.contrib.admin search","text":"Searches now may contain quoted phrases with spaces, each phrase is considered as a single search term, and it will raise a validation error if any null-character is provided in search. See the Filtering API guide for more information.
"},{"location":"community/3.15-announcement/#other-fixes-and-improvements","title":"Other fixes and improvements","text":"There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behavior.
See the release notes page for a complete listing.
"},{"location":"community/3.16-announcement/","title":"3.16 Announcement","text":""},{"location":"community/3.16-announcement/#django-rest-framework-316","title":"Django REST framework 3.16","text":"At the Internet, on March 28th, 2025, we are happy to announce the release of Django REST framework 3.16.
"},{"location":"community/3.16-announcement/#updated-django-and-python-support","title":"Updated Django and Python support","text":"The latest release now fully supports Django 5.1 and the upcoming 5.2 LTS as well as Python 3.13.
The current minimum versions of Django is now 4.2 and Python 3.9.
"},{"location":"community/3.16-announcement/#django-loginrequiredmiddleware","title":"Django LoginRequiredMiddleware","text":"The new LoginRequiredMiddleware introduced by Django 5.1 can now be used alongside Django REST Framework, however it is not honored for API views as an equivalent behavior can be configured via DEFAULT_AUTHENTICATION_CLASSES. See our dedicated section in the docs for more information.
The generation of validators for UniqueConstraint has been improved to support better nullable fields and constraints with conditions.
"},{"location":"community/3.16-announcement/#other-fixes-and-improvements","title":"Other fixes and improvements","text":"There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behavior.
See the release notes page for a complete listing.
"},{"location":"community/3.2-announcement/","title":"Django REST framework 3.2","text":"The 3.2 release is the first version to include an admin interface for the browsable API.
This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing BrowsableAPIRenderer, or used together with it, allowing you to switch between the two styles as required.
We've also fixed a huge number of issues, and made numerous cleanups and improvements.
Over the course of the 3.1.x series we've resolved nearly 600 tickets on our GitHub issue tracker. This means we're currently running at a rate of closing around 100 issues or pull requests per month.
None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking a look through our sponsors and finding out who's hiring.
"},{"location":"community/3.2-announcement/#adminrenderer","title":"AdminRenderer","text":"To include AdminRenderer simply add it to your settings:
REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.AdminRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer'\n ],\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n}\n There are some limitations to the AdminRenderer, in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those.
Also note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates.
The idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.
"},{"location":"community/3.2-announcement/#supported-versions","title":"Supported versions","text":"This release drops support for Django 1.4.
Our supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.
"},{"location":"community/3.2-announcement/#deprecations","title":"Deprecations","text":"There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy.
request.DATA was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of request.data instead.request.QUERY_PARAMS was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of request.query_params instead.ModelSerializer.Meta options have now been removed: write_only_fields, view_name, lookup_field. Use the more general extra_kwargs option instead.The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors.
view.paginate_by - Use paginator.page_size instead.view.page_query_param - Use paginator.page_query_param instead.view.paginate_by_param - Use paginator.page_size_query_param instead.view.max_paginate_by - Use paginator.max_page_size instead.settings.PAGINATE_BY - Use paginator.page_size instead.settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead.settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead.There are a couple of bug fixes that are worth calling out as they introduce differing behavior.
These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.
"},{"location":"community/3.2-announcement/#manytomany-fields-and-blanktrue","title":"ManyToMany fields and blank=True","text":"We've now added an allow_empty argument, which can be used with ListSerializer, or with many=True relationships. This is True by default, but can be set to False if you want to disallow empty lists as valid input.
As a follow-up to this we are now able to properly mirror the behavior of Django's ModelForm with respect to how many-to-many fields are validated.
Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has blank=True set.
Here's what the mapping looks like in practice:
models.ManyToManyField() \u2192 serializers.PrimaryKeyRelatedField(many=True, allow_empty=False)models.ManyToManyField(blank=True) \u2192 serializers.PrimaryKeyRelatedField(many=True)The upshot is this: If you have many to many fields in your models, then make sure you've included the argument blank=True if you want to allow empty inputs in the equivalent ModelSerializer fields.
When using allow_null with ListField or a nested many=True serializer the previous behavior was to allow null values as items in the list. The behavior is now to allow null values instead of the list.
For example, take the following field:
NestedSerializer(many=True, allow_null=True)\n Previously the validation behavior would be:
[{\u2026}, null, {\u2026}] is valid.null is invalid.Our validation behavior as of 3.2.0 is now:
[{\u2026}, null, {\u2026}] is invalid.null is valid.If you want to allow null child items, you'll need to instead specify allow_null on the child class, using an explicit ListField instead of many=True. For example:
ListField(child=NestedSerializer(allow_null=True))\n"},{"location":"community/3.2-announcement/#whats-next","title":"What's next?","text":"The 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release.
This release is planned to include:
Thanks once again to all our sponsors and supporters.
"},{"location":"community/3.3-announcement/","title":"Django REST framework 3.3","text":"The 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding thank you to all our wonderful sponsors and supporters.
The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project.
In order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow @_tomchristie to keep up to date with these announcements, and be among the first set of sign ups.
We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product.
"},{"location":"community/3.3-announcement/#release-notes","title":"Release notes","text":"Significant new functionality in the 3.3 release includes:
JSONField serializer field, corresponding to Django 1.9's Postgres JSONField model field.Example of the new filter controls
"},{"location":"community/3.3-announcement/#supported-versions","title":"Supported versions","text":"This release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required.
This brings our supported versions into line with Django's currently supported versions
"},{"location":"community/3.3-announcement/#deprecations","title":"Deprecations","text":"The AJAX based support for the browsable API means that there are a number of internal cleanups in the request class. For the vast majority of developers this should largely remain transparent:
PUT and DELETE, or to support form content types such as JSON, you should now use the AJAX forms javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.accept query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to use a custom content negotiation class.HTTP_X_HTTP_METHOD_OVERRIDE header is no longer supported by default. If you require it then you'll need to use custom middleware.The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.
view.paginate_by - Use paginator.page_size instead.view.page_query_param - Use paginator.page_query_param instead.view.paginate_by_param - Use paginator.page_size_query_param instead.view.max_paginate_by - Use paginator.max_page_size instead.settings.PAGINATE_BY - Use paginator.page_size instead.settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead.settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead.The ModelSerializer and HyperlinkedModelSerializer classes should now include either a fields or exclude option, although the fields = '__all__' shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings ModelSerializer more closely in line with Django's ModelForm behavior.
The 3.4 release is the first in a planned series that will be addressing schema generation, hypermedia support, API clients, and finally realtime support.
"},{"location":"community/3.4-announcement/#funding","title":"Funding","text":"The 3.4 release has been made possible a recent Mozilla grant, and by our collaborative funding model. If you use REST framework commercially, and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid plan.
The initial aim is to provide a single full-time position on REST framework. Right now we're over 60% of the way towards achieving that. Every single sign-up makes a significant impact.
Many thanks to all our awesome sponsors, and in particular to our premium backers, Rover, Sentry, and Stream.
"},{"location":"community/3.4-announcement/#schemas-client-libraries","title":"Schemas & client libraries","text":"REST framework 3.4 brings built-in support for generating API schemas.
We provide this support by using Core API, a Document Object Model for describing APIs.
Because Core API represents the API schema in an format-independent manner, we're able to render the Core API Document object into many different schema formats, by allowing the renderer class to determine how the internal representation maps onto the external schema format.
This approach should also open the door to a range of auto-generated API documentation options in the future, by rendering the Document object into HTML documentation pages.
Alongside the built-in schema support, we're also now providing the following:
These API clients are dynamically driven, and able to interact with any API that exposes a supported schema format.
Dynamically driven clients allow you to interact with an API at an application layer interface, rather than a network layer interface, while still providing the benefits of RESTful Web API design.
We're expecting to expand the range of languages that we provide client libraries for over the coming months.
Further work on maturing the API schema support is also planned, including documentation on supporting file upload and download, and improved support for documentation generation and parameter annotation.
Current support for schema formats is as follows:
Name Support PyPI package Core JSON Schema generation & client support. Built-in support incoreapi. Swagger / OpenAPI Schema generation & client support. The openapi-codec package. JSON Hyper-Schema Currently client support only. The hyperschema-codec package. API Blueprint Not yet available. Not yet available. You can read more about any of this new functionality in the following:
It is also worth noting that Marc Gibbons is currently working towards a 2.0 release of the popular Django REST Swagger package, which will tie in with our new built-in support.
"},{"location":"community/3.4-announcement/#supported-versions","title":"Supported versions","text":"The 3.4.0 release adds support for Django 1.10.
The following versions of Python and Django are now supported:
(*) Note that Python 3.2 and 3.3 are not supported from Django 1.9 onwards.
"},{"location":"community/3.4-announcement/#deprecations-and-changes","title":"Deprecations and changes","text":"The 3.4 release includes very limited deprecation or behavioral changes, and should present a straightforward upgrade.
"},{"location":"community/3.4-announcement/#use-fields-or-exclude-on-serializer-classes","title":"Use fields or exclude on serializer classes.","text":"The following change in 3.3.0 is now escalated from \"pending deprecation\" to \"deprecated\". Its usage will continue to function but will raise warnings:
ModelSerializer and HyperlinkedModelSerializer should include either a fields option, or an exclude option. The fields = '__all__' shortcut may be used to explicitly include all fields.
Using the default JSON renderer and directly returning a datetime or time instance will now render with microsecond precision (6 digits), rather than millisecond precision (3 digits). This makes the output format consistent with the default string output of serializers.DateTimeField and serializers.TimeField.
This change does not affect the default behavior when using serializers, which is to serialize datetime and time instances into strings with microsecond precision.
The serializer behavior can be modified if needed, using the DATETIME_FORMAT and TIME_FORMAT settings.
The renderer behavior can be modified by setting a custom encoder_class attribute on a JSONRenderer subclass.
Making an OPTIONS request to views that have a serializer choice field will result in a list of the available choices being returned in the response.
In cases where there is a relational field, the previous behavior would be to return a list of available instances to choose from for that relational field.
In order to minimize exposed information the behavior now is to not return choices information for relational fields.
If you want to override this new behavior you'll need to implement a custom metadata class.
See issue #3751 for more information on this behavioral change.
"},{"location":"community/3.4-announcement/#other-improvements","title":"Other improvements","text":"This release includes further work from a huge number of pull requests and issues.
Many thanks to all our contributors who've been involved in the release, either through raising issues, giving feedback, improving the documentation, or suggesting and implementing code changes.
The full set of itemized release notes are available here.
"},{"location":"community/3.5-announcement/","title":"3.5 Announcement","text":""},{"location":"community/3.5-announcement/#django-rest-framework-35","title":"Django REST framework 3.5","text":"The 3.5 release is the second in a planned series that is addressing schema generation, hypermedia support, API client libraries, and finally realtime support.
"},{"location":"community/3.5-announcement/#funding","title":"Funding","text":"The 3.5 release would not have been possible without our collaborative funding model. If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan.
Many thanks to all our sponsors, and in particular to our premium backers, Rover, Sentry, Stream, and Machinalis.
"},{"location":"community/3.5-announcement/#improved-schema-generation","title":"Improved schema generation","text":"Docstrings on views are now pulled through into schema definitions, allowing you to use the schema definition to document your\u00a0API.
There is now also a shortcut function, get_schema_view(), which makes it easier to adding schema views to your API.
For example, to include a swagger schema to your API, you would do the following:
Run pip install django-rest-swagger.
Add 'rest_framework_swagger' to your INSTALLED_APPS setting.
Include the schema view in your URL conf:
from rest_framework.schemas import get_schema_view\nfrom rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer\n\nschema_view = get_schema_view(\n title=\"Example API\", renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]\n)\n\nurlpatterns = [path(\"swagger/\", schema_view), ...]\n There have been a large number of fixes to the schema generation. These should resolve issues for anyone using the latest version of the django-rest-swagger package.
Some of these changes do affect the resulting schema structure, so if you're already using schema generation you should make sure to review the deprecation notes, particularly if you're currently using a dynamic client library to interact with your API.
Finally, we're also now exposing the schema generation as a publicly documented API, allowing you to more easily override the behavior.
"},{"location":"community/3.5-announcement/#requests-test-client","title":"Requests test client","text":"You can now test your project using the requests library.
This exposes exactly the same interface as if you were using a standard requests session instance.
client = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200\n Rather than sending any HTTP requests to the network, this interface will coerce all outgoing requests into WSGI, and call into your application directly.
"},{"location":"community/3.5-announcement/#core-api-client","title":"Core API client","text":"You can also now test your project by interacting with it using the coreapi client library.
# Fetch the API schema\nclient = CoreAPIClient()\nschema = client.get('http://testserver/schema/')\n\n# Create a new organization\nparams = {'name': 'MegaCorp', 'status': 'active'}\nclient.action(schema, ['organizations', 'create'], params)\n\n# Ensure that the organization exists in the listing\ndata = client.action(schema, ['organizations', 'list'])\nassert(len(data) == 1)\nassert(data == [{'name': 'MegaCorp', 'status': 'active'}])\n Again, this will call directly into the application using the WSGI interface, rather than making actual network calls.
This is a good option if you are planning for clients to mainly interact with your API using the coreapi client library, or some other auto-generated client.
One interesting aspect of both the requests client and the coreapi client is that they allow you to write tests in such a way that they can also be made to run against a live service.
By switching the WSGI based client instances to actual instances of requests.Session or coreapi.Client you can have the test cases make actual network calls.
Being able to write test cases that can exercise your staging or production environment is a powerful tool. However in order to do this, you'll need to pay close attention to how you handle setup and teardown to ensure a strict isolation of test data from other live or staging data.
"},{"location":"community/3.5-announcement/#raml-support","title":"RAML support","text":"We now have preliminary support for RAML documentation generation.
Further work on the encoding and documentation generation is planned, in order to make features such as the 'Try it now' support available at a later date.
This work also now means that you can use the Core API client libraries to interact with APIs that expose a RAML specification. The RAML codec gives some examples of interacting with the Spotify API in this way.
"},{"location":"community/3.5-announcement/#validation-codes","title":"Validation codes","text":"Exceptions raised by REST framework now include short code identifiers. When used together with our customizable error handling, this now allows you to modify the style of API error messages.
As an example, this allows for the following style of error responses:
{\n \"message\": \"You do not have permission to perform this action.\",\n \"code\": \"permission_denied\"\n}\n This is particularly useful with validation errors, which use appropriate codes to identify differing kinds of failure...
{\n \"name\": {\"message\": \"This field is required.\", \"code\": \"required\"},\n \"age\": {\"message\": \"A valid integer is required.\", \"code\": \"invalid\"}\n}\n"},{"location":"community/3.5-announcement/#client-upload-download-support","title":"Client upload & download support","text":"The Python coreapi client library and the Core API command line tool both now fully support file uploads and downloads.
The router arguments for generating a schema view, such as schema_title, are now pending deprecation.
Instead of using DefaultRouter(schema_title='Example API'), you should use the get_schema_view() function, and include the view in your URL conf.
Make sure to include the view before your router urls. For example:
from rest_framework.schemas import get_schema_view\nfrom my_project.routers import router\n\nschema_view = get_schema_view(title='Example API')\n\nurlpatterns = [\n path('', schema_view),\n path('', include(router.urls)),\n]\n"},{"location":"community/3.5-announcement/#schema-path-representations","title":"Schema path representations","text":"The 'pk' identifier in schema paths is now mapped onto the actually model field name by default. This will typically be 'id'.
This gives a better external representation for schemas, with less implementation detail being exposed. It also reflects the behavior of using a ModelSerializer class with fields = '__all__'.
You can revert to the previous behavior by setting 'SCHEMA_COERCE_PATH_PK': False in the REST framework settings.
The internal retrieve() and destroy() method names are now coerced to an external representation of read and delete.
You can revert to the previous behavior by setting 'SCHEMA_COERCE_METHOD_NAMES': {} in the REST framework settings.
The functionality of the built-in DjangoFilterBackend is now completely included by the django-filter package.
You should change your imports and REST framework filter settings as follows:
rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend.rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet.The existing imports will continue to work but are now pending deprecation.
"},{"location":"community/3.5-announcement/#corejson-media-type","title":"CoreJSON media type","text":"The media type for CoreJSON is now application/json+coreapi, rather than the previous application/vnd.json+coreapi. This brings it more into line with other custom media types, such as those used by Swagger and RAML.
The clients currently accept either media type. The old style-media type will be deprecated at a later date.
"},{"location":"community/3.5-announcement/#modelserializer-fields-and-exclude","title":"ModelSerializer 'fields' and 'exclude'","text":"ModelSerializer and HyperlinkedModelSerializer must include either a fields option, or an exclude option. The fields = '__all__' shortcut may be used to explicitly include all fields.
Failing to set either fields or exclude raised a pending deprecation warning in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.
The 3.6 release adds two major new features to REST framework.
Above: The interactive API documentation.
"},{"location":"community/3.6-announcement/#funding","title":"Funding","text":"The 3.6 release would not have been possible without our backing from Mozilla to the project, and our collaborative funding\u00a0model.
If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan.
Many thanks to all our sponsors, and in particular to our premium backers, Rover, Sentry, Stream, Machinalis, Rollbar, and MicroPyramid.
"},{"location":"community/3.6-announcement/#interactive-api-documentation","title":"Interactive API documentation","text":"REST framework's new API documentation supports a number of features:
The coreapi library is required as a dependency for the API docs. Make sure to install the latest version (2.3.0 or above). The pygments and markdown libraries are optional but recommended.
To install the API documentation, you'll need to include it in your projects URLconf:
from rest_framework.documentation import include_docs_urls\n\nAPI_TITLE = 'API title'\nAPI_DESCRIPTION = '...'\n\nurlpatterns = [\n ...\n path('docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))\n]\n Once installed you should see something a little like this:
We'll likely be making further refinements to the API documentation over the coming weeks. Keep in mind that this is a new feature, and please do give us feedback if you run into any issues or limitations.
For more information on documenting your API endpoints see the \"Documenting your API\" section.
"},{"location":"community/3.6-announcement/#javascript-client-library","title":"JavaScript client library","text":"The JavaScript client library allows you to load an API schema, and then interact with that API at an application layer interface, rather than constructing fetch requests explicitly.
Here's a brief example that demonstrates:
index.html
<html>\n <head>\n <script src=\"/static/rest_framework/js/coreapi-0.1.0.js\"></script>\n <script src=\"/docs/schema.js\"></script>\n <script>\n const coreapi = window.coreapi\n const schema = window.schema\n\n // Instantiate a client...\n let auth = coreapi.auth.TokenAuthentication({scheme: 'JWT', token: 'xxx'})\n let client = coreapi.Client({auth: auth})\n\n // Make an API request...\n client.action(schema, ['projects', 'list']).then(function(result) {\n alert(result)\n })\n </script>\n </head>\n</html>\n The JavaScript client library supports various authentication schemes, and can be used by your project itself, or as an external client interacting with your API.
The client is not limited to usage with REST framework APIs, although it does currently only support loading CoreJSON API schemas. Support for Swagger and other API schemas is planned.
For more details see the JavaScript client library documentation.
"},{"location":"community/3.6-announcement/#authentication-classes-for-the-python-client-library","title":"Authentication classes for the Python client library","text":"Previous authentication support in the Python client library was limited to allowing users to provide explicit header values.
We now have better support for handling the details of authentication, with the introduction of the BasicAuthentication, TokenAuthentication, and SessionAuthentication schemes.
You can include the authentication scheme when instantiating a new client.
auth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')\nclient = coreapi.Client(auth=auth)\n For more information see the Python client library documentation.
"},{"location":"community/3.6-announcement/#deprecations","title":"Deprecations","text":""},{"location":"community/3.6-announcement/#updating-coreapi","title":"Updating coreapi","text":"If you're using REST framework's schema generation, or want to use the API docs, then you'll need to update to the latest version of coreapi. (2.3.0)
"},{"location":"community/3.6-announcement/#generating-schemas-from-router","title":"Generating schemas from Router","text":"The 3.5 \"pending deprecation\" of router arguments for generating a schema view, such as schema_title, schema_url and schema_renderers, have now been escalated to a \"deprecated\" warning.
Instead of using DefaultRouter(schema_title='Example API'), you should use the get_schema_view() function, and include the view explicitly in your URL conf.
The 3.5 \"pending deprecation\" warning of the built-in DjangoFilterBackend has now been escalated to a \"deprecated\" warning.
You should change your imports and REST framework filter settings as follows:
rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend.rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet.There are likely to be a number of refinements to the API documentation and JavaScript client library over the coming weeks, which could include some of the following:
Once work on those refinements is complete, we'll be starting feature work on realtime support, for the 3.7 release.
"},{"location":"community/3.7-announcement/","title":"3.7 Announcement","text":""},{"location":"community/3.7-announcement/#django-rest-framework-37","title":"Django REST framework 3.7","text":"The 3.7 release focuses on improvements to schema generation and the interactive API documentation.
This release has been made possible by Bayer who have sponsored the release.
"},{"location":"community/3.7-announcement/#funding","title":"Funding","text":"If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan.
As well as our release sponsor, we'd like to say thanks in particular our premium backers, Rover, Sentry, Stream, Machinalis, and Rollbar.
"},{"location":"community/3.7-announcement/#customizing-api-docs-schema-generation","title":"Customizing API docs & schema generation.","text":"The schema generation introduced in 3.5 and the related API docs generation in 3.6 are both hugely powerful features, however they've been somewhat limited in cases where the view introspection isn't able to correctly identify the schema for a particular view.
In order to try to address this we're now adding the ability for per-view customization of the API schema. The interface that we're adding for this allows either basic manual overrides over which fields should be included on a view, or for more complex programmatic overriding of the schema generation. We believe this release comprehensively addresses some of the existing shortcomings of the schema features.
Let's take a quick look at using the new functionality...
The APIView class has a schema attribute, that is used to control how the Schema for that particular view is generated. The default behavior is to use the AutoSchema class.
from rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomView(APIView):\n schema = AutoSchema() # Included for demonstration only. This is the default behavior.\n We can remove a view from the API schema and docs, like so:
class CustomView(APIView):\n schema = None\n If we want to mostly use the default behavior, but additionally include some additional fields on a particular view, we can now do so easily...
class CustomView(APIView):\n schema = AutoSchema(manual_fields=[\n coreapi.Field('search', location='query')\n ])\n To ignore the automatic generation for a particular view, and instead specify the schema explicitly, we use the ManualSchema class instead...
class CustomView(APIView):\n schema = ManualSchema(fields=[...])\n For more advanced behaviors you can subclass AutoSchema to provide for customized schema generation, and apply that to particular views.
class CustomView(APIView):\n schema = CustomizedSchemaGeneration()\n For full details on the new functionality, please see the Schema Documentation.
"},{"location":"community/3.7-announcement/#django-20-support","title":"Django 2.0 support","text":"REST framework 3.7 supports Django versions 1.10, 1.11, and 2.0 alpha.
"},{"location":"community/3.7-announcement/#minor-fixes-and-improvements","title":"Minor fixes and improvements","text":"There are a large number of minor fixes and improvements in this release. See the release notes page for a complete listing.
The number of open tickets against the project currently at its lowest number in quite some time, and we're continuing to focus on reducing these to a manageable amount.
"},{"location":"community/3.7-announcement/#deprecations","title":"Deprecations","text":""},{"location":"community/3.7-announcement/#exclude_from_schema","title":"exclude_from_schema","text":"Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view decorator and now PendingDeprecation. They will be moved to deprecated in the 3.8 release, and removed entirely in 3.9.
For APIView you should instead set a schema = None attribute on the view class.
For function based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None).
DjangoFilterBackend","text":"The DjangoFilterBackend was moved to pending deprecation in 3.5, and deprecated in 3.6. It has now been removed from the core framework.
The functionality remains fully available, but is instead provided in the django-filter package.
We're still planning to work on improving real-time support for REST framework by providing documentation on integrating with Django channels, as well adding support for more easily adding WebSocket support to existing HTTP endpoints.
This will likely be timed so that any REST framework development here ties in with similar work on API Star.
"},{"location":"community/3.8-announcement/","title":"3.8 Announcement","text":""},{"location":"community/3.8-announcement/#django-rest-framework-38","title":"Django REST framework 3.8","text":"The 3.8 release is a maintenance focused release resolving a large number of previously outstanding issues and laying the foundations for future changes.
"},{"location":"community/3.8-announcement/#funding","title":"Funding","text":"If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan.
We'd like to say thanks in particular our premium backers, Rover, Sentry, Stream, Machinalis, and Rollbar.
"},{"location":"community/3.8-announcement/#breaking-changes","title":"Breaking Changes","text":""},{"location":"community/3.8-announcement/#altered-the-behavior-of-read_only-plus-default-on-field","title":"Altered the behavior ofread_only plus default on Field.","text":"#5886 read_only fields will now always be excluded from writable fields.
Previously read_only fields when combined with a default value would use the default for create and update operations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted source attributes on nullable relations.
In order to maintain the old behavior you may need to pass the value of read_only fields when calling save() in the view:
def perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n Alternatively you may override save() or create() or update() on the serializer as appropriate.
action decorator replaces list_route and detail_route","text":"#5705 list_route and detail_route have been merge into a single action decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions.
Both list_route and detail_route are now pending deprecation. They will be deprecated in 3.9 and removed entirely in 3.10.
The new action decorator takes a boolean detail argument.
detail_route uses with @action(detail=True).list_route uses with @action(detail=False).exclude_from_schema","text":"Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view decorator are now deprecated. They will be removed entirely in 3.9.
For APIView you should instead set a schema = None attribute on the view class.
For function based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None).
There are a large number of minor fixes and improvements in this release. See the release notes page for a complete listing.
"},{"location":"community/3.8-announcement/#whats-next","title":"What's next","text":"We're currently working towards moving to using OpenAPI as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the coreapi and coreschema libraries, and instead use apistar for the API documentation generation, schema generation, and API client libraries.
The 3.9 release gives access to extra actions in the Browsable API, introduces composable permissions and built-in OpenAPI schema support. (Formerly known as Swagger)
"},{"location":"community/3.9-announcement/#funding","title":"Funding","text":"If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan.
Many thanks to all our wonderful sponsors, and in particular to our premium backers, Rover, Sentry, Stream, Auklet, Rollbar, Cadre, Load Impact, and Kloudless.
"},{"location":"community/3.9-announcement/#built-in-openapi-schema-support","title":"Built-in OpenAPI schema support","text":"REST framework now has a first-pass at directly including OpenAPI schema support. (Formerly known as Swagger)
Specifically:
OpenAPIRenderer, and JSONOpenAPIRenderer classes that deal with encoding coreapi.Document instances into OpenAPI YAML or OpenAPI JSON.get_schema_view(...) method now defaults to OpenAPI YAML, with CoreJSON as a secondary option if it is selected via HTTP content negotiation.generateschema, which you can use to dump the schema into your repository.Here's an example of adding an OpenAPI schema to the URL conf:
from rest_framework.schemas import get_schema_view\nfrom rest_framework.renderers import JSONOpenAPIRenderer\nfrom django.urls import path\n\nschema_view = get_schema_view(\n title=\"Server Monitoring API\",\n url=\"https://www.example.org/api/\",\n renderer_classes=[JSONOpenAPIRenderer],\n)\n\nurlpatterns = [path(\"schema.json\", schema_view), ...]\n And here's how you can use the generateschema management command:
$ python manage.py generateschema --format openapi > schema.yml\n There's lots of different tooling that you can use for working with OpenAPI schemas. One option that we're working on is the API Star command line tool.
You can use apistar to validate your API schema:
$ apistar validate --path schema.json --format openapi\n\u2713 Valid OpenAPI schema.\n Or to build API documentation:
$ apistar docs --path schema.json --format openapi\n\u2713 Documentation built at \"build/index.html\".\n API Star also includes a dynamic client library that uses an API schema to automatically provide a client library interface for making requests.
"},{"location":"community/3.9-announcement/#composable-permission-classes","title":"Composable permission classes","text":"You can now compose permission classes using the and/or operators, & and |.
For example...
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]\n If you're using custom permission classes then make sure that you are subclassing from BasePermission in order to enable this support.
Following the introduction of the action decorator in v3.8, extra actions defined on a ViewSet are now available from the Browsable API.
When defined, a dropdown of \"Extra Actions\", appropriately filtered to detail/non-detail actions, is displayed.
"},{"location":"community/3.9-announcement/#supported-versions","title":"Supported Versions","text":"REST framework 3.9 supports Django versions 1.11, 2.0, and 2.1.
"},{"location":"community/3.9-announcement/#deprecations","title":"Deprecations","text":""},{"location":"community/3.9-announcement/#djangoobjectpermissionsfilter-moved-to-third-party-package","title":"DjangoObjectPermissionsFilter moved to third-party package.","text":"The DjangoObjectPermissionsFilter class is pending deprecation, will be deprecated in 3.10 and removed entirely in 3.11.
It has been moved to the third-party djangorestframework-guardian package. Please use this instead.
basename for consistency.","text":"Router.register base_name argument has been renamed in favor of basename.Router.get_default_base_name method has been renamed in favor of Router.get_default_basename. #5990See #5990.
base_name and get_default_base_name() are pending deprecation. They will be deprecated in 3.10 and removed entirely in 3.11.
action decorator replaces list_route and detail_route","text":"Both list_route and detail_route are now deprecated in favor of the single action decorator. They will be removed entirely in 3.10.
The action decorator takes a boolean detail argument.
detail_route uses with @action(detail=True).list_route uses with @action(detail=False).exclude_from_schema","text":"Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view have now been removed.
For APIView you should instead set a schema = None attribute on the view class.
For function-based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None).
There are a large number of minor fixes and improvements in this release. See the release notes page for a complete listing.
"},{"location":"community/3.9-announcement/#whats-next","title":"What's next","text":"We're planning to iteratively work towards OpenAPI becoming the standard schema representation. This will mean that the coreapi dependency will gradually become removed, and we'll instead generate the schema directly, rather than building a CoreAPI Document object.
OpenAPI has clearly become the standard for specifying Web APIs, so there's not much value any more in our schema-agnostic document model. Making this change will mean that we'll more easily be able to take advantage of the full set of OpenAPI functionality.
This will also make a wider range of tooling available.
We'll focus on continuing to develop the API Star library and client tool into a recommended option for generating API docs, validating API schemas, and providing a dynamic client library.
There's also a huge amount of ongoing work on maturing the ASGI landscape, with the possibility that some of this work will eventually feed back into Django.
There will be further work on the Uvicorn web server, as well as lots of functionality planned for the Starlette web framework, which is building a foundational set of tooling for working with ASGI.
"},{"location":"community/contributing/","title":"Contributing to REST framework","text":"The world can only really be changed one piece at a time. The art is picking that piece.
\u2014 Tim Berners-Lee
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
Note
At this point in its lifespan we consider Django REST framework to be feature-complete. We focus on pull requests that track the continued development of Django versions, and generally do not accept new features or code formatting changes.
"},{"location":"community/contributing/#community","title":"Community","text":"The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
Other really great ways you can help move the community forward include helping to answer questions on the discussion group, or setting up an email alert on StackOverflow so that you get notified of any new questions with the django-rest-framework tag.
When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
"},{"location":"community/contributing/#code-of-conduct","title":"Code of conduct","text":"Please keep the tone polite & professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.
Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations.
The Django code of conduct gives a fuller set of guidelines for participating in community forums.
"},{"location":"community/contributing/#issues","title":"Issues","text":"Our contribution process is that the GitHub discussions page should generally be your starting point. Some tips on good potential issue reporting:
Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to
To start developing on Django REST framework, first create a Fork from the Django REST Framework repo on GitHub.
Then clone your fork. The clone command will look like this, with your GitHub username instead of YOUR-USERNAME:
git clone https://github.com/YOUR-USERNAME/django-rest-framework\n See GitHub's Fork a Repo Guide for more help.
Changes should broadly follow the PEP 8 style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles. You can check your contributions against these conventions each time you commit using the pre-commit hooks, which we also run on CI. To set them up, first ensure you have the pre-commit tool installed, for example:
python -m pip install pre-commit\n Then run:
pre-commit install\n"},{"location":"community/contributing/#testing","title":"Testing","text":"To run the tests, clone the repository, and then:
# Setup the virtual environment\npython3 -m venv env\nsource env/bin/activate\npip install -e . --group dev\n\n# Run the tests\n./runtests.py\n Tip
If your tests require access to the database, do not forget to inherit from django.test.TestCase or use the @pytest.mark.django_db() decorator.
For example, with TestCase:
from django.test import TestCase\n\nclass MyDatabaseTest(TestCase):\n def test_something(self):\n # Your test code here\n pass\n Or with decorator:
import pytest\n\n@pytest.mark.django_db()\nclass MyDatabaseTest:\n def test_something(self):\n # Your test code here\n pass\n You can reuse existing models defined in tests/models.py for your tests.
Run using a more concise output style.
./runtests.py -q\n If you do not want the output to be captured (for example, to see print statements directly), you can use the -s flag.
./runtests.py -s\n Run the tests for a given test case.
./runtests.py MyTestCase\n Run the tests for a given test method.
./runtests.py MyTestCase.test_this_method\n Shorter form to run the tests for a given test method.
./runtests.py test_this_method\n Note
The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
"},{"location":"community/contributing/#running-against-multiple-environments","title":"Running against multiple environments","text":"You can also use the excellent tox testing tool to run the tests against all supported versions of Python and Django. Install tox globally, and then simply run:
tox\n"},{"location":"community/contributing/#pull-requests","title":"Pull requests","text":"It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests.
It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.
GitHub's documentation for working on pull requests is available here.
Always run the tests before submitting pull requests, and ideally run tox in order to check that your modifications are compatible on all supported versions of Python and Django.
Once you've made a pull request take a look at the build status in the GitHub interface and make sure the tests are running as you'd expect.
Above: build notifications
"},{"location":"community/contributing/#managing-compatibility-issues","title":"Managing compatibility issues","text":"Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the compat.py module, and should provide a single common interface that the rest of the codebase can use.
The documentation for REST framework is built from the Markdown source files in the docs directory.
There are many great Markdown editors that make working with the documentation really easy. The Mou editor for Mac is one such editor that comes highly recommended.
"},{"location":"community/contributing/#building-the-documentation","title":"Building the documentation","text":"To build the documentation, install MkDocs with pip install mkdocs and then run the following command.
mkdocs build\n This will build the documentation into the site directory.
You can build the documentation and open a preview in a browser window by using the serve command.
mkdocs serve\n"},{"location":"community/contributing/#language-style","title":"Language style","text":"Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.
Some other tips:
There are a couple of conventions you should follow when working on the documentation.
"},{"location":"community/contributing/#1-headers","title":"1. Headers","text":"Headers should use the hash style. For example:
### Some important topic\n The underline style should not be used. Don't do this:
Some important topic\n====================\n"},{"location":"community/contributing/#2-links","title":"2. Links","text":"Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.
Here is a link to [some other thing][other-thing].\n\nMore text...\n\n[other-thing]: http://example.com/other/thing\n This style helps keep the documentation source consistent and readable.
If you are hyperlinking to another REST framework document, you should use a relative link, and link to the .md suffix. For example:
[authentication]: ../api-guide/authentication.md\n Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
"},{"location":"community/contributing/#3-notes","title":"3. Notes","text":"If you want to draw attention to a note or warning, use an admonition, like so:
!!! note\n A useful documentation note.\n The documentation theme styles info, warning, tip and danger admonition types, but more could be added if the need arise.
Looking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of our sponsors are hiring.
"},{"location":"community/jobs/#places-to-look-for-django-rest-framework-jobs","title":"Places to look for Django REST Framework Jobs","text":"Know of any other great resources for Django REST Framework jobs that are missing in our list? Please submit a pull request or email us.
Wonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for REST Framework sponsorship yet.
"},{"location":"community/kickstarter-announcement/","title":"Kickstarting Django REST framework 3","text":"In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.
"},{"location":"community/kickstarter-announcement/#project-details","title":"Project details","text":"This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following:
Full details are available now on the project page.
If you're interested in helping make sustainable open source development a reality please visit the Kickstarter page and consider funding the project.
I can't wait to see where this takes us!
Many thanks to everyone for your support so far,
Tom Christie :)
"},{"location":"community/kickstarter-announcement/#sponsors","title":"Sponsors","text":"We've now blazed way past all our goals, with a staggering \u00a330,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.
"},{"location":"community/kickstarter-announcement/#platinum-sponsors","title":"Platinum sponsors","text":"Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.
Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.
The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank\u00a0you to individuals who have chosen to privately support the project at this level.
Individual backers: Paul Hallett, Paul Whipp, Dylan Roy, Jannis Leidel, Xavier Ordoquy, Johannes Spielmann, Rob Spectre, Chris Heisel, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.
"},{"location":"community/kickstarter-announcement/#advocates","title":"Advocates","text":"The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you!
Individual backers: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, D\u00e9c\u00e9bal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkk\u00e4, Charalampos Papaloizou, Nikolai R\u00f8ed Kristiansen, Antoni Aloy L\u00f3pez, Celia Oakley, Micha\u0142 Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel.
Corporate backers: Savannah Informatics, Prism Skylabs, Musical Operating Devices.
"},{"location":"community/kickstarter-announcement/#supporters","title":"Supporters","text":"There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!
"},{"location":"community/mozilla-grant/","title":"Mozilla Grant","text":"We have recently been awarded a Mozilla grant, in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with.
Additionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications.
The Core API project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with any API that exposes a supported schema or hypermedia format.
Specifically, the work includes:
"},{"location":"community/mozilla-grant/#client-libraries","title":"Client libraries","text":"This work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation.
The next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints.
In order to ensure that I can be fully focused on trying to secure a sustainable & well-funded open source business I will be leaving my current role at DabApps at the end of May 2016.
I have formed a UK limited company, Encode, which will act as the business entity behind REST framework. I will be issuing monthly reports from Encode on progress both towards the Mozilla grant, and for development time funded via the REST framework paid plans.
Email Address"},{"location":"community/project-management/","title":"Project management","text":"\"No one can whistle a symphony; it takes a whole orchestra to play it\"
\u2014 Halford E. Luccock
This document outlines our project management processes for REST framework.
The aim is to ensure that the project has a high \"bus factor\", and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.
"},{"location":"community/project-management/#maintenance-team","title":"Maintenance team","text":"Participating actively in the REST framework project does not require being part of the maintenance team. Almost every important part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.
"},{"location":"community/project-management/#composition","title":"Composition","text":"The composition of the maintenance team is handled by @tomchristie. Team members will be added as collaborators to the repository.
"},{"location":"community/project-management/#responsibilities","title":"Responsibilities","text":"Team members have the following responsibilities.
mkdocs gh-deploy.Further notes for maintainers:
@tomchristie.Our PyPI releases will be handled by either the current release manager, or by @tomchristie. Every release should have an open issue tagged with the Release label and marked against the appropriate milestone.
The following template should be used for the description of the issue, and serves as a release checklist.
Release manager is @***.\nPull request is #***.\n\nChecklist:\n\n- [ ] Create pull request for [release notes](https://github.com/encode/django-rest-framework/blob/mains/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/encode/django-rest-framework/milestones/***).\n- [ ] Update supported versions:\n - [ ] `pyproject.toml` `python_requires` list\n - [ ] `pyproject.toml` Python & Django version trove classifiers\n - [ ] `README` Python & Django versions\n - [ ] `docs` Python & Django versions\n- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/main/rest_framework/__init__.py).\n- [ ] Ensure documentation validates\n - Build and serve docs `mkdocs serve`\n - Validate links `pylinkvalidate.py -P http://127.0.0.1:8000`\n- [ ] Confirm with @tomchristie that release is finalized and ready to go.\n- [ ] Ensure that release date is included in pull request.\n- [ ] Merge the release pull request.\n- [ ] Install the release tools: `pip install build twine`\n- [ ] Build the package: `python -m build`\n- [ ] Push the package to PyPI with `twine upload dist/*`\n- [ ] Tag the release, with `git tag -a *.*.* -m 'version *.*.*'; git push --tags`.\n- [ ] Deploy the documentation with `mkdocs gh-deploy`.\n- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).\n- [ ] Make a release announcement on twitter.\n- [ ] Close the milestone on GitHub.\n\nTo modify this process for future releases make a pull request to the [project management](https://www.django-rest-framework.org/topics/project-management/) documentation.\n When pushing the release to PyPI ensure that your environment has been installed from our development requirement.txt, so that documentation and PyPI installs are consistently being built against a pinned set of packages.
The PyPI package is owned by @tomchristie. As a backup @j4mie also has ownership of the package.
If @tomchristie ceases to participate in the project then @j4mie has responsibility for handing over ownership duties.
The following issues still need to be addressed:
@j4mie has back-up access to the django-rest-framework.org domain setup and admin.Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.
Medium version numbers (0.x.0) may include API changes, in line with the deprecation policy. You should read the release notes carefully before upgrading between medium point releases.
Major version numbers (x.0.0) are reserved for substantial project milestones.
As REST Framework is considered feature-complete, most releases are expected to be minor releases.
"},{"location":"community/release-notes/#deprecation-policy","title":"Deprecation policy","text":"REST framework releases follow a formal deprecation policy, which is in line with Django's deprecation policy.
The timeline for deprecation of a feature present in version 1.0 would work as follows:
Version 1.1 would remain fully backwards compatible with 1.0, but would raise RemovedInDRF13Warning warnings, subclassing PendingDeprecationWarning, if you use the feature that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using python -Wd manage.py test, you'll be warned of any API changes you need to make.
Version 1.2 would escalate these warnings to subclass DeprecationWarning, which is loud by default.
Version 1.3 would remove the deprecated bits of API entirely.
Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.
"},{"location":"community/release-notes/#upgrading","title":"Upgrading","text":"To upgrade Django REST framework to the latest version, use pip:
pip install -U djangorestframework\n You can determine your currently installed version using pip show:
pip show djangorestframework\n"},{"location":"community/release-notes/#316x-series","title":"3.16.x series","text":""},{"location":"community/release-notes/#3161","title":"3.16.1","text":"Date: 6th August 2025
This release fixes a few bugs, clean-up some old code paths for unsupported Python versions and improve translations.
"},{"location":"community/release-notes/#minor-changes","title":"Minor changes","text":"backports.zoneinfo dependency and conditions on unsupported Python 3.8 and lower in #9681. Python versions prior to 3.9 were already unsupported so this shouldn't be a breaking change.unique_together validation with SerializerMethodField in #9712UniqueTogetherValidator to handle fields with source attribute in #9688drf-restwind and update outdated images in browsable-api.md in #9680djangorestframework-guardian2 to djangorestframework-guardian in #9734request in serializer context when using HyperlinkedModelSerializer in #9732pyupgrade to pre-commit hooks in #9682pytz is available in #9715@araggohnxd made their first contribution in #9673@mbeijen made their first contribution in #9660@stefan6419846 made their first contribution in #9676@ren000thomas made their first contribution in #9675@ulgens made their first contribution in #9682@bukh-sal made their first contribution in #9595@rezatn0934 made their first contribution in #9576@Rohit10jr made their first contribution in #9693@kushibayev made their first contribution in #9713@alihassancods made their first contribution in #9732@kulikjak made their first contribution in #9715@Natgho made their first contribution in #9749Full Changelog: https://github.com/encode/django-rest-framework/compare/3.16.0...3.16.1
"},{"location":"community/release-notes/#3160","title":"3.16.0","text":"Date: 28th March 2025
This release is considered a significant release to improve upstream support with Django and Python. Some of these may change the behavior of existing features and pre-existing behavior. Specifically, some fixes were added to around the support of UniqueConstraint with nullable fields which will improve built-in serializer validation.
LoginRequiredMiddleware in #9514 and #9657UniqueConstraint in #9360UniqueConstraint in #9531unique_together validation with source in #9482AttributeError raised within properties in #9455get_template_context to handle also lists in #9467DecimalField in #9515open() in setup.py in #9661AutoSchema._get_reference method in #9525OperandHolder in #9437adrf third party package in #9198queryset attribute in #9528httpie call in docs in #9543<> in validators example in #9590strftime link in the docs in #9624action attribute in 'Introspecting ViewSet actions' docs section in #9633rest-framework-gm2m-relations package to the list of 3rd party libraries in #9063django-pyoidc as a third party authentication library in #9667@maerteijn made their first contribution in #9198@FraCata00 made their first contribution in #9444@AlvaroVega made their first contribution in #9451@james-mchugh made their first contribution in #9455@ifeanyidavid made their first contribution in #9479@p-schlickmann made their first contribution in #9480@akkuman made their first contribution in #9505@rafaelgramoschi made their first contribution in #9509@Sinaatkd made their first contribution in #9521@gtkacz made their first contribution in #9535@sliverc made their first contribution in #9556@gabrielromagnoli1987 made their first contribution in #9543@cheehong1030 made their first contribution in #9563@amansharma612 made their first contribution in #9590@Gluroda made their first contribution in #9616@deepakangadi made their first contribution in #9624@EXG1O made their first contribution in #9633@decadenza made their first contribution in #9640@mojtabaakbari221b made their first contribution in #9063@mikemanger made their first contribution in #9661@gbip made their first contribution in #9667Full Changelog: https://github.com/encode/django-rest-framework/compare/3.15.2...3.16.0
"},{"location":"community/release-notes/#315x-series","title":"3.15.x series","text":""},{"location":"community/release-notes/#3152","title":"3.15.2","text":"Date: 14th June 2024
Date: 22nd March 2024
SearchFilter handling of quoted and comma separated strings, when .get_search_terms is being called into by a custom class. See [#9338]Date: 15th March 2024
SearchFilter rendering search field with invalid value [#9023]timedelta [#9007]NamespaceVersioning ignoring DEFAULT_VERSION on non-None namespaces [#7278]field.choices that triggered full table load [#8950]BooleanField validation [#8970]BrowsableAPIRenderer for usage with ListSerializer. [#7530]OR of two permission classes [#7522]pytz [#8984]Serializer [#8001]OrderedDict with dict [#8964]__eq__ for validators [#8925]can_read_model permission in DjangoModelPermissions [#8009]basename is not unique [#8438]_ignore_model_permissions = True [#8772]__eq__ method for OperandHolder class [#8710]django.test package when not testing [#8699]examples and format to OpenAPI schema of CursorPagination [#8687] [#8686]Date: 22nd September 2022
--api-version CLI option to generateschema management command. [#8663]is_valid(raise_exception=False) as a keyword-only argument. [#7952]set_context on Validators. [#8589]NotImplemented from ErrorDetails.__ne__. [#8538]DateTimeField.default_timezone when a custom timezone is set. [#8531]ManyRelatedField falling back to the default value when the attribute specified by dot notation doesn't exist. Matches ManyRelatedField.get_attribute to Field.get_attribute. [#7574]schemas.openapi.get_reference public. [#7515]ReturnDict support dict union operators on Python 3.9 and later. [#8302]request.user is set before checking if the user is authenticated. [#8370]Date: 15th December 2021
@api_view. [#8297]Date: 13th December 2021
max_length and min_length options to ListSerializer. [#8165]get_request_serializer and get_response_serializer hooks to AutoSchema. [#7424]UNICODE_JSON setting in API schema outputs. [#7991]RemoteUserAuthentication. [#7158]Date: 26th March 2021
deque instead of list for tracking throttling .history. (Due to incompatibility with DjangoRedis cache backend. See #7870) [#7872]Date: 25th March 2021
COUNT query when LimitOffsetPagination is configured but pagination params are not included on the request. [#6098]allow_null=True on DecimalField. [#7718]\"Yes\"/\"No\" values with BooleanField. [#7739]PageNumberPagination.get_page_number() method for overriding behavior. [#7652]PrimaryKeyRelatedField fields, instead of casting to ints. [#7597]OrderingFilter. [#7609]deque instead of list for tracking throttling .history. [#7849]Date: 13th October 2020
rest_framework.authtoken.models is imported, but rest_framework.authtoken is not in INSTALLED_APPS. [#7571]get_queryset() methods are not masked. [#7480]Date: 28th September 2020
TokenProxy migration. [#7557]Date: 28th September 2020
--file option to generateschema command. [#7130]tags for OpenAPI schema generation. See the schema docs. [#7184]AutoSchema become public API: get_path_parameters, get_pagination_parameters, get_filter_parameters, get_request_body, get_responses, get_serializer, get_paginator, map_serializer, map_field, map_choice_field, map_field_validators, allows_filters. See the schema docsJSONField. [#7467]SearchFilter now supports nested search on JSONField and HStoreField model fields. [#7121]SearchFilter now supports searching on annotate() fields. [#6240]pk in the admin URL. [#7341]__repr__ for Request instances. [#7239]ListField schema output to include all available child information. [#7137]default=False to be included for BooleanField schema outputs. [#7165]\"type\" information in ChoiceField schema outputs. [#7161]\"type\": \"object\" on schema objects. [#7169]DecimalField. [#7254]ObtainAuthToken view. [#7211]context=... to view .get_serializer() methods. [#7298]PermissionDenied if permission class has one set. [#7306]ChoiceField to a schema output. [#7264]UniqueTogether handling when serializer fields use source=.... [#7143]HEAD requests now set self.action correctly on a ViewSet instance. [#7223]ModelSerializer[Author]. [#7385]charset=None portion in the request Content-Type header when using APIClient. [#7400]\\Z/\\z tokens in OpenAPI regexs. [#7389]PrimaryKeyRelatedField and HyperlinkedRelatedField when source field is actually a property. [#7142]Token.generate_key is now a class method. [#7502]@action warns if method is wrapped in a decorator that does not preserve information using @functools.wraps. [#7098]serializers.NullBooleanField in favor of serializers.BooleanField with allow_null=True [#7122]Date: 30th September 2020
urlize_quoted_links template tag in favor of Django's built-in urlize. Removes a XSS vulnerability for some kinds of content in the browsable API.Date: 5th August 2020
Date: 12th December 2019
.set_context API in favor of a requires_context marker.serializers.HStoreField in OpenAPI schemas. #6914int64 representation for large integers in OpenAPI schemas. #7018.to_representation implementation is provided on a field subclass. #6996Date: 4th September 2019
lowerInitialCamelCase style in OpenAPI operation IDs.minLength/maxLength/minItems/maxItems properties in OpenAPI schemas.FileField.url once in serialization, for improved performance.Date: 29th July 2019
OpenAPI schema fixes.Date: 17th July 2019
uritemplate for OpenAPI schema generation, but not coreapi.Date: 15th July 2019
generateschema --generator_class CLI optionpyyaml>=5.1 #6680user.get_username in templates, in preference to user.username.source=\"*\"SerializerMethodField field name arguments.detail_route decorator in favor of action, which accepts a detail bool. Use @action(detail=True) instead. gh6687list_route decorator in favor of action, which accepts a detail bool. Use @action(detail=False) instead. gh6687Date: 10th May 2019
This is a maintenance release that fixes an error handling bug under Python 2.
"},{"location":"community/release-notes/#393","title":"3.9.3","text":"Date: 29th April 2019
This is the last Django REST Framework release that will support Python 2. Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
Date: 3rd March 2019
_urls cache on register() #6407validators to accept non-list iterables. #6282RemovedInDRF\u2026Warning classes to simplify deprecations. #6480Date: 16th January 2019
limit_choices_to on foreign keys. #6371Date: 18th October 2018
action support for ViewSet suffixes #6081action docs sections #6060Router.register base_name argument in favor of basename. #5990Router.get_default_base_name method in favor of Router.get_default_basename. #5990CharField to disallow null bytes. #6073 To revert to the old behavior, subclass CharField and remove ProhibitNullCharactersValidator from the validators. class NullableCharField(serializers.CharField):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.validators = [\n v\n for v in self.validators\n if not isinstance(v, ProhibitNullCharactersValidator)\n ]\nOpenAPIRenderer and generate_schema management command. #6229e.indexOf is not a function error #5982DjangoObjectPermissionsFilter class, moved to the djangorestframework-guardian package. #6075Date: 6th April 2018
read_only + default unique_together validation. #5922Date: 4th April 2018
Use old url_name behavior in route decorators #5915
For list_route and detail_route maintain the old behavior of url_name, basing it on the url_path instead of the function name.
Date: 3rd April 2018
Breaking Change: Alter read_only plus default behavior. #5886
read_only fields will now always be excluded from writable fields.
Previously read_only fields with a default value would use the default for create and update operations.
In order to maintain the old behavior you may need to pass the value of read_only fields when calling save() in the view:
def perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n Alternatively you may override save() or create() or update() on the serializer as appropriate.
Correct allow_null behavior when required=False #5888
Without an explicit default, allow_null implies a default of null for outgoing serialization. Previously such fields were being skipped when read-only or otherwise not required.
Possible backwards compatibility break if you were relying on such fields being excluded from the outgoing representation. In order to restore the old behavior you can override data to exclude the field when None.
For example:
@property\ndef data(self):\n \"\"\"\n Drop `maybe_none` field if None.\n \"\"\"\n data = super().data\n if 'maybe_none' in data and data['maybe_none'] is None:\n del data['maybe_none']\n return data\n Refactor dynamic route generation and improve viewset action introspectibility. #5705
ViewSets have been provided with new attributes and methods that allow it to introspect its set of actions and the details of the current action.
list_route and detail_route into a single action decorator.ViewSet with .get_extra_actions().url_name and url_path on the decorated method.url_name is now based on the function name, instead of the url_path, as the path is not always suitable (e.g., capturing arguments in the path)..reverse_action() method (added in 3.7.4)self.reverse_action(self.custom_action.url_name)detail initkwarg to indicate if the current action is operating on a collection or a single instance.Additional changes:
list_route & detail_route in favor of action decorator with detail boolean.DynamicRoute with detail boolean.list_route and detail_route maintain the old behavior of url_name, basing it on the url_path instead of the function name.Fix formatting of the 3.7.4 release note #5704
compat._resolve_model() #5733iter(dict) over iter(dict.keys()) #5736python_requires argument to setuptools #5739pip show #5757fields docs #5783__eq__/__ne__ and __repr__ #5787background-attachment: fixed in docs #5777exceptions.APIException output #57630. #5834LimitOffsetPagination.get_count to allow method override #5846Date: 21st December 2017
Date: 21st December 2017
Date: 21st December 2017
Date: 20th December 2017
Schema: Extract method for manual_fields processing #5633
Allows for easier customization of manual_fields processing, for example to provide per-method manual fields. AutoSchema adds get_manual_fields, as the intended override point, and a utility method update_fields, to handle by-name field replacement from a list, which, in general, you are not expected to override.
Note: AutoSchema.__init__ now ensures manual_fields is a list. Previously may have been stored internally as None.
Remove ulrparse compatibility shim; use six instead #5579
TimeDelta.total_seconds() #5577set_rollback() from compat #5591__getattr__ #5617Serializer._declared_fields enable modifying fields on a serializer #5629allow_null=True should not imply a default value #5639allow_null serialization output note #5641Serializer.data for Browsable API rendering when provided invalid data #5646.basename and .reverse_action() to ViewSet #5648override_settings compat #5668required=False #5665UNAUTHENTICATED_USER = None note #5679to_representation docs #5682source=\u2018*\u2019 to custom field docs. #5688Date: 6th November 2017
AppRegistryNotReady error from contrib.auth view imports #5567Date: 6th November 2017
allow_null=True should imply a default serialization value #5518drf_create_token command #5550wheel] section to [bdist_wheel] as the former is legacy #5557Date: 16th October 2017
source fields #5489Date: 6th October 2017
DjangoModelPermissions to ensure user authentication before calling the view's get_queryset() method. As a side effect, this changes the order of the HTTP method permissions and authentication checks, and 405 responses will only be returned when authenticated. If you want to replicate the old behavior, see the PR for details. #5376exclude_from_schema on APIView and api_view decorator. Set schema = None or @schema(None) as appropriate. #5422Timezone-aware DateTimeFields now respect active or default timezone during serialization, instead of always using UTC. #5435
Resolves inconsistency whereby instances were serialized with supplied datetime for create but UTC for retrieve. #3732
Possible backwards compatibility break if you were relying on datetime strings being UTC. Have client interpret datetimes or set default or active timezone (docs) to UTC if needed.
Removed DjangoFilterBackend inline with deprecation policy. Use django_filters.rest_framework.FilterSet and/or django_filters.rest_framework.DjangoFilterBackend instead. #5273
time when encoding. Makes consistent with datetime. BC Change: Previously only milliseconds were encoded. #5440STRICT_JSON setting (default True) to raise exception for the extended float values (nan, inf, -inf) accepted by Python's json module. BC Change: Previously these values would converted to corresponding strings. Set STRICT_JSON to False to restore the previous behavior. #5265page_size parameter in CursorPaginator class #5250DEFAULT_PAGINATION_CLASS None by default. BC Change: If your were just setting PAGE_SIZE to enable pagination you will need to add DEFAULT_PAGINATION_CLASS. The previous default was rest_framework.pagination.PageNumberPagination. There is a system check warning to catch this case. You may silence that if you are setting pagination class on a per-view basis. #5170APIException from get_serializer_fields in schema generation. #5443include_docs_urls #5448get_queryset returned None #5348data description #5361ChoiceField.choices to be set dynamically #5426drf-openapi package in docs #5470data #5472is_list_view recognize RetrieveModel\u2026 views #5480SchemaGenerator.get_serializer_fields has been refactored as AutoSchema.get_serializer_fields and drops the view argument [#5354][gh5354]Date: 21st August 2017
HTML_CUTOFF is set to None. #5174multipart/form-data correctly. #5176test_hyperlinked_related_lookup_url_encoded_exists. #5179list_route & detail_route with kwargs contains curly bracket in url_path #5187Date: 12th May 2017
get_limit in LimitOffsetPagination to return all records. (#4437)page_size attribute. (#5086, #3692).as_view() to view instance. (#5053)extra_kwargs. (#4688)Date: 10th March 2017
mark_safe in API docs template tags. (#4952, #4953)Date: 9th March 2017
markdown dependency is optional. (#4947)Date: 9th March 2017
See the release announcement.
"},{"location":"community/release-notes/#35x-series","title":"3.5.x series","text":""},{"location":"community/release-notes/#354","title":"3.5.4","text":"Date: 10th February 2017
@list_route and @detail_route endpoints. (#4821)PUT requests when prefetch_related is used. (#4661, #4668)Date: 7th November 2016
autofocus support for input controls. (#4650)Date: 1st November 2016
Date: 21st October 2016
rest_framework/compat.py imports. (#4612, #4608, #4601)raise for Python 3.5 compat. (#4600)Date: 20th October 2016
"},{"location":"community/release-notes/#34x-series","title":"3.4.x series","text":""},{"location":"community/release-notes/#347","title":"3.4.7","text":"Date: 21st September 2016
RegexField. (#4489, #4490, #2617)admin.html causing CSRF error. (#4472, #4473)ResolverMatch.func_name of api_view decorated view. (#4465, #4462)APIClient.get() when path contains unicode arguments (#4458)Date: 23rd August 2016
AdminRenderer display of PK only related fields. (#4419, #4423)Date: 19th August 2016
Date: 12th August 2016
max_digits=None on DecimalField. (#4377, #4372)Date: 5th August 2016
Date: 5th August 2016
request.user.is_authenticated as property not method, under Django 1.10+ (#4358, #4354)Date: 28th July 2016
root_renderers argument to DefaultRouter. (#4323, #4268)url and schema_url arguments. (#4321, #4308, #4305)pagination_class = None. (#4314, #4289)get_serializer_class. (#4265, #4285)Accept and Content-Type headers. (#4287, #4313, #4281)Date: 14th July 2016
DecimalField. (#4233)must_call_distinct. (#4215)limit=0 should revert to default limit. (#4194).validated_data and .errors as lists not dicts for ListSerializer. (#4180)AUTH_USER_MODEL compat property. (#4176)OrderingFilter should call get_serializer_class() to determine default fields. (#3964)initial for any serializer.Field. (#3943)field.rel. (#3906)help_text in Browsable API forms. (#3812)lookup_type is deprecated in favor of lookup_expr. (#4259)Date: 14th March 2016.
BooleanField. Thanks to Mikalai Radchuk for the fix. (#3910)Token model as abstract when the authtoken application isn't declared. Thanks to Adam Thomas for the report. (#3860, #3858)QueryParameterVersioning does not use DEFAULT_VERSION setting. Thanks to Brad Montgomery for the fix. (#3833)on_delete on the models. Thanks to Mads Jensen for the fix. (#3832)DateField.to_representation to work with Python 2 unicode. Thanks to Mikalai Radchuk for the fix. (#3819)TimeField not handling string times. Thanks to Areski Belaid for the fix. (#3809)Meta.extra_kwargs. Thanks to Kevin Massey for the report and fix. (#3805, #3804)django-crispy-forms. Thanks to Emmanuelle Delescolle, Jos\u00e9 Padilla and Luis San Pablo for the report, analysis and fix. (#3787, #3636, #3637)Min/MaxValueValidator transfer from a model's DecimalField. Thanks to Kevin Brown for the fix. (#3774)AutoFilterSet to inherit from default_filter_set. Thanks to Tom Linford for the fix. (#3753)DateTimeField does not handle empty values correctly. Thanks to Mick Parker for the report and fix. (#3731, #3726)_get_reverse_relationships() to use correct to_field. Thanks to Benjamin Phillips for the fix. (#3696)get_queryset for RelatedField. Thanks to Ryan Hiebert for the fix. (#3605)Date: 14th December 2015.
ListField enforces input is a list. (#3513)pagination.PageNumberPagination. (#3631, #3684)to_fields attribute. (#3635, #3634)template.render deprecation warnings for Django 1.9. (#3654)NestedBoundField to also handle empty string when rendering its form. (#3677)Date: 4th November 2015.
request.POST (#3592)to_field referring to primary key. (#3593)filter_class is defined. (#3560)Date: 28th October 2015.
to_field when creating ModelSerializer relational fields. (#3526)FilePathField to a serializer field. (#3536)error_messages on ModelSerializer uniqueness constraints. (#3435)max_length constraint for ModelSerializer fields mapped from TextField. (#3509)Date: 27th October 2015.
username in optional logout tag. (#3550)Date: 21th September 2015.
ViewSet.search_fields attribute. (#3324, #3323)allow_empty not working on serializers with many=True. (#3361, #3364)DurationField accepts integers. (#3359)ListField truncation on HTTP PATCH (#3415, #2761)Date: 24th August 2015.
html_cutoff and html_cutoff_text for limiting select dropdowns. (#3313)SearchFilter. (#3316)IPAddressField. ([#3249gh3249) (#3250)LimitOffsetPagination when count=0, offset=0. (#3303)Date: 13th August 2015.
display_value() method for use when displaying relational field select inputs. (#3254)BooleanField checkboxes incorrectly displaying as checked. (#3258)BooleanField to False in all cases. (#2776)WSGIRequest.FILES property without raising incorrect deprecated error. (#3261)Date: 7th August 2015.
1, 0 rendering as true, false in the admin interface. #3227)request.FILES for compat with Django's HTTPRequest class. (#3239)Date: 6th August 2015.
AdminRenderer. (#2926)FilePathField. (#1854)allow_empty to ListField. (#2250)source=<method> on hyperlinked fields. (#2690)ListField(allow_null=True) now allows null as the list value, not null items in the list. (#2766)ManyToMany() maps to allow_empty=False, ManyToMany(blank=True) maps to allow_empty=True. (#2804)OPTIONS requests support nested representations. (#2915)view.action == \"metadata\" for viewsets with OPTIONS requests. (#3115)allow_blank on UUIDField. ([#3130][gh#3130])DecimalField validation. (#3139)allow_blank=False when used with trim_whitespace=True. (#2712)allow_blank argument. (#3011)UnicodeDecodeError when invalid characters included in header with TokenAuthentication. (#2928)@non_atomic_requests decorator. (#3016)SearchFilter. (#2935)\"url\": null in the representation. (#2759)HStoreField to include allow_blank=True in DictField mapping. (#2659)Date: 4th June 2015.
DurationField. (#2481, #2989)format argument to UUIDField. (#2788, #3000)MultipleChoiceField empties incorrectly on a partial update using multipart/form-data (#2993, #2894)RelatedField. (#2981, #2811)unique_together relations. (#2975)ChoiceField/MultipleChoiceField representations. (#2839, #2940)ATOMIC_REQUESTS is set. (#2887, #2034)DecimalField accepts 2E+2 as 200 and validates decimal place correctly. (#2948, #2947)UserModel that change username. (#2952)IPAddressField improvements. (#2747, #2618, #3008)DecimalField for easier subclassing. (#2695)Date: 13rd May 2015.
DateField.to_representation can handle str and empty values. (#2656, #2687, #2869)ModelSerializer used with abstract model. (#2757, #2630)HyperLinkedRelatedField (#2724, #2711).model attribute in permissions (#2818)IntegerField to use compiled decimal regex. (#2853)queryset to raise AssertionError. (#2862)DjangoModelPermissions rely on get_queryset. (#2863)AcceptHeaderVersioning with content negotiation in place. (#2868)DjangoObjectPermissions to use views that define get_queryset. (#2905)Date: 23rd March 2015.
serializer_class is used, even when get_serializer method does not exist on the view. (#2743)lookup_url_kwarg handling in viewsets. (#2685, #2591)rest_framework.views in apps.py (#2678)TypeError if PAGE_SIZE not set (#2667, #2700)min_value field error message references max_value. (#2645)MergeDict. (#2640)Date: 5th March 2015.
For full details see the 3.1 release announcement.
"},{"location":"community/release-notes/#30x-series","title":"3.0.x series","text":""},{"location":"community/release-notes/#305","title":"3.0.5","text":"Date: 10th February 2015.
_closable_objects breaks pickling. (#1850, #2492)User models with Throttling. (#2524)User.db_table in TokenAuthentication migration. (#2479)AttributeError tracebacks on Request objects. (#2530, #2108)ManyRelatedField.get_value clearing field on partial update. (#2475)detail_route and list_route mutable argument. (#2518)TokenAuthentication. (#2519)Date: 28th January 2015.
DictField and support Django 1.8 HStoreField. (#2451, #2106)UUIDField and support Django 1.8 UUIDField. (#2448, #2433, #2432)BaseRenderer.render now raises NotImplementedError. (#2434)ResultDict and ResultList now appear as standard dict/list. (#2421)HiddenField in the HTML form of the web browsable API page. (#2410)OrderedDict for RelatedField.choices. (#2408)HTTP_X_FORWARDED_FOR. (#2401)FileUploadParser with version 3.x. (#2399)ReturnDict. (#2360)Date: 8th January 2015.
MinValueValidator on models.DateField. (#2369)DefaultRouter. (#2351)required=False allows omission of value for output. (#2342)models.TextField. (#2340)ListSerializer for pagination if required. (#2331, #2327)exclude are model fields. (#2319)IntegerField and max_length argument incompatibility. (#2317)format_suffix_patterns to work with Django's i18n_patterns. (#2278)url_path. (#2010)Date: 17th December 2014.
request.user is made available to response middleware. (#2155)Client.logout() also cancels any existing force_authenticate. (#2218, #2259)min_length message for CharField. (#2255)UnicodeDecodeError, which can occur on serializer repr. (#2270, #2279)SlugRelatedField raising UnicodeEncodeError when used as a multiple choice input. (#2290)Date: 11th December 2014.
create() fails. (#2013)FileUploadParser breaks with empty file names and multiple upload handlers. (#2109)BindingDict to support standard dict-functions. (#2135, #2163)validate() to ListSerializer. (#2168, #2225, #2232)FileField. (#2172)ViewSet.as_view(). (#2175)allow_blank to ChoiceField. (#2184, #2239)fields on serializer is not a list of strings. (#2193, #2213)validated_attrs argument renamed to validated_data in Serializer create()/update(). (#2197)fields on serializer is not a list of strings. (#2213)Date: 1st December 2014
For full details see the 3.0 release announcement.
For older release notes, please see the version 2.x documentation.
"},{"location":"community/third-party-packages/","title":"Third Party Packages","text":"Software ecosystems [\u2026] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.
\u2014 Jan Bosch.
"},{"location":"community/third-party-packages/#about-third-party-packages","title":"About Third Party Packages","text":"Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.
We support, encourage and strongly favor the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.
We aim to make creating third party packages as easy as possible, whilst keeping a simple and well maintained core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.
If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the Mailing List.
"},{"location":"community/third-party-packages/#creating-a-third-party-package","title":"Creating a Third Party Package","text":""},{"location":"community/third-party-packages/#version-compatibility","title":"Version compatibility","text":"Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a compat.py module, and should provide a single common interface that the rest of the codebase can use.
Check out Django REST framework's compat.py for an example.
"},{"location":"community/third-party-packages/#once-your-package-is-available","title":"Once your package is available","text":"Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful.
"},{"location":"community/third-party-packages/#adding-to-the-django-rest-framework-grid","title":"Adding to the Django REST framework grid","text":"We suggest adding your package to the REST Framework grid on Django Packages.
"},{"location":"community/third-party-packages/#adding-to-the-django-rest-framework-docs","title":"Adding to the Django REST framework docs","text":"Create a Pull Request on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under Third party packages of the API Guide section that best applies, like Authentication or Permissions. You can also link your package under the Third Party Packages section.
"},{"location":"community/third-party-packages/#announce-on-the-discussion-group","title":"Announce on the discussion group.","text":"You can also let others know about your package through the discussion group.
"},{"location":"community/third-party-packages/#existing-third-party-packages","title":"Existing Third Party Packages","text":"Django REST Framework has a growing community of developers, packages, and resources.
Check out a grid detailing all the packages and ecosystem around Django REST Framework at Django Packages.
To submit new content, create a pull request.
"},{"location":"community/third-party-packages/#async-support","title":"Async Support","text":"ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here.ModelViewSet's Queryset in a clean, simple and configurable way. It also supports validations on incoming query params and their values.DjangoObjectPermissionsFilter previously found in DRF.ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here.There are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.
"},{"location":"community/tutorials-and-resources/#books","title":"Books","text":""},{"location":"community/tutorials-and-resources/#courses","title":"Courses","text":"Want your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please submit a pull request or email us!
"},{"location":"theme/src/","title":"DRF logos","text":"This folder contains the source file for the DRF logos as Figma file.
"},{"location":"topics/ajax-csrf-cors/","title":"Working with AJAX, CSRF & CORS","text":"\"Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability \u2014 very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one.\"
\u2014 Jeff Atwood
"},{"location":"topics/ajax-csrf-cors/#javascript-clients","title":"Javascript clients","text":"If you\u2019re building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.
AJAX requests that are made within the same context as the API they are interacting with will typically use SessionAuthentication. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.
AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as TokenAuthentication.
Cross Site Request Forgery protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.
To guard against these type of attacks, you need to do two things:
GET, HEAD and OPTIONS cannot be used to alter any server-side state.POST, PUT, PATCH and DELETE, always require a valid CSRF token.If you're using SessionAuthentication you'll need to include valid CSRF tokens for any POST, PUT, PATCH or DELETE operations.
In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.
"},{"location":"topics/ajax-csrf-cors/#cors","title":"CORS","text":"Cross-Origin Resource Sharing is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.
The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
Adam Johnson maintains the django-cors-headers package, which is known to work correctly with REST framework APIs.
"},{"location":"topics/browsable-api/","title":"The Browsable API","text":"It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.
\u2014 Alfred North Whitehead, An Introduction to Mathematics (1911)
API may stand for Application Programming Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the HTML format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using POST, PUT, and DELETE.
If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The rest_framework package includes a reverse helper for this purpose.
By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using ?format= in the request, so you can look at the raw JSON response in a browser by adding ?format=json to the URL. There are helpful extensions for viewing JSON in Firefox and Chrome.
To quickly add authentication to the browesable api, add a routes named \"login\" and \"logout\" under the namespace \"rest_framework\". DRF provides default routes for this which you can add to your urlconf:
from django.urls import include, path\n\nurlpatterns = [\n # ...\n path(\"api-auth/\", include(\"rest_framework.urls\", namespace=\"rest_framework\"))\n]\n"},{"location":"topics/browsable-api/#customizing","title":"Customizing","text":"The browsable API is built with Twitter's Bootstrap (v 3.4.1), making it easy to customize the look-and-feel.
To customize the default style, create a template called rest_framework/api.html that extends from rest_framework/base.html. For example:
templates/rest_framework/api.html
{% extends \"rest_framework/base.html\" %}\n\n... # Override blocks with required customizations\n"},{"location":"topics/browsable-api/#overriding-the-default-theme","title":"Overriding the default theme","text":"To replace the default theme, add a bootstrap_theme block to your api.html and insert a link to the desired Bootstrap theme css file. This will completely replace the included theme.
{% block bootstrap_theme %}\n <link rel=\"stylesheet\" href=\"/path/to/my/bootstrap.css\" type=\"text/css\">\n{% endblock %}\n Suitable pre-made replacement themes are available at Bootswatch. To use any of the Bootswatch themes, simply download the theme's bootstrap.min.css file, add it to your project, and replace the default one as described above. Make sure that the Bootstrap version of the new theme matches that of the default theme.
You can also change the navbar variant, which by default is navbar-inverse, using the bootstrap_navbar_variant block. The empty {% block bootstrap_navbar_variant %}{% endblock %} will use the original Bootstrap navbar style.
Full example:
{% extends \"rest_framework/base.html\" %}\n\n{% block bootstrap_theme %}\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootswatch@3.4.1/flatly/bootstrap.min.css\" type=\"text/css\">\n{% endblock %}\n\n{% block bootstrap_navbar_variant %}{% endblock %}\n For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the style block.
Screenshot of the bootswatch 'Cerulean' theme
Screenshot of the bootswatch 'Slate' theme
"},{"location":"topics/browsable-api/#third-party-packages-for-customization","title":"Third party packages for customization","text":"You can use a third party package for customization, rather than doing it by yourself. Here is 3 packages for customizing the API:
Screenshots of the drf-restwind
Screenshot of the drf-redesign
Screenshot of the drf-material
"},{"location":"topics/browsable-api/#blocks","title":"Blocks","text":"All of the blocks available in the browsable API base template that can be used in your api.html.
body - The entire html <body>.bodyclass - Class attribute for the <body> tag, empty by default.bootstrap_theme - CSS for the Bootstrap theme.bootstrap_navbar_variant - CSS class for the navbar.branding - Branding section of the navbar, see Bootstrap components.breadcrumbs - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.script - JavaScript files for the page.style - CSS stylesheets for the page.title - Title of the page.userlinks - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links.All of the standard Bootstrap components are available.
"},{"location":"topics/browsable-api/#tooltips","title":"Tooltips","text":"The browsable API makes use of the Bootstrap tooltips component. Any element with the js-tooltip class and a title attribute has that title content will display a tooltip on hover events.
To add branding and customize the look-and-feel of the login template, create a template called login.html and add it to your project, eg: templates/rest_framework/login.html. The template should extend from rest_framework/login_base.html.
You can add your site name or branding by including the branding block:
{% extends \"rest_framework/login_base.html\" %}\n\n{% block branding %}\n <h3 style=\"margin: 0 0 20px;\">My Site Name</h3>\n{% endblock %}\n You can also customize the style by adding the bootstrap_theme or style block similar to api.html.
The context that's available to the template:
allowed_methods : A list of methods allowed by the resourceapi_settings : The API settingsavailable_formats : A list of formats allowed by the resourcebreadcrumblist : The list of links following the chain of nested resourcescontent : The content of the API responsedescription : The description of the resource, generated from its docstringname : The name of the resourcepost_form : A form instance for use by the POST form (if allowed)put_form : A form instance for use by the PUT form (if allowed)display_edit_forms : A boolean indicating whether or not POST, PUT and PATCH forms will be displayedrequest : The request objectresponse : The response objectversion : The version of Django REST Frameworkview : The view handling the requestFORMAT_PARAM : The view can accept a format overrideMETHOD_PARAM : The view can accept a method overrideYou can override the BrowsableAPIRenderer.get_context() method to customize the context that gets passed to the template.
For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have api.html extend base.html. Then the page content and capabilities are entirely up to you.
ChoiceField with large numbers of items.","text":"When a relationship or ChoiceField has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly.
The simplest option in this case is to replace the select input with a standard text input. For example:
author = serializers.HyperlinkedRelatedField(\n queryset=User.objects.all(),\n style={'base_template': 'input.html'}\n)\n"},{"location":"topics/browsable-api/#autocomplete","title":"Autocomplete","text":"An alternative, but more complex option would be to replace the input with an autocomplete widget, that only loads and renders a subset of the available options as needed. If you need to do this you'll need to do some work to build a custom autocomplete HTML template yourself.
There are a variety of packages for autocomplete widgets, such as django-autocomplete-light, that you may want to refer to. Note that you will not be able to simply include these components as standard widgets, but will need to write the HTML template explicitly. This is because REST framework 3.0 no longer supports the widget keyword argument since it now uses templated HTML generation.
\"There are two noncontroversial uses for overloaded POST. The first is to simulate HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE\"
\u2014 RESTful Web Services, Leonard Richardson & Sam Ruby.
In order to allow the browsable API to function, there are a couple of browser enhancements that REST framework needs to provide.
As of version 3.3.0 onwards these are enabled with javascript, using the ajax-form library.
"},{"location":"topics/browser-enhancements/#browser-based-put-delete-etc","title":"Browser based PUT, DELETE, etc...","text":"The AJAX form library supports browser-based PUT, DELETE and other methods on HTML forms.
After including the library, use the data-method attribute on the form, like so:
<form action=\"/\" data-method=\"PUT\">\n <input name='foo'/>\n ...\n</form>\n Note that prior to 3.3.0, this support was server-side rather than javascript based. The method overloading style (as used in Ruby on Rails) is no longer supported due to subtle issues that it introduces in request parsing.
"},{"location":"topics/browser-enhancements/#browser-based-submission-of-non-form-content","title":"Browser based submission of non-form content","text":"Browser-based submission of content types such as JSON are supported by the AJAX form library, using form fields with data-override='content-type' and data-override='content' attributes.
For example:
<form action=\"/\">\n <input data-override='content-type' value='application/json' type='hidden'/>\n <textarea data-override='content'>{}</textarea>\n <input type=\"submit\"/>\n </form>\n Note that prior to 3.3.0, this support was server-side rather than javascript based.
"},{"location":"topics/browser-enhancements/#url-based-format-suffixes","title":"URL based format suffixes","text":"REST framework can take ?format=json style URL parameters, which can be a useful shortcut for determining which content type should be returned from the view.
This behavior is controlled using the URL_FORMAT_OVERRIDE setting.
Prior to version 3.3.0 the semi extension header X-HTTP-Method-Override was supported for overriding the request method. This behavior is no longer in core, but can be adding if needed using middleware.
For example:
METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'\n\nclass MethodOverrideMiddleware:\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n if request.method == 'POST' and METHOD_OVERRIDE_HEADER in request.META:\n request.method = request.META[METHOD_OVERRIDE_HEADER]\n return self.get_response(request)\n"},{"location":"topics/browser-enhancements/#url-based-accept-headers","title":"URL based accept headers","text":"Until version 3.3.0 REST framework included built-in support for ?accept=application/json style URL parameters, which would allow the Accept header to be overridden.
Since the introduction of the content negotiation API this behavior is no longer included in core, but may be added using a custom content negotiation class, if needed.
For example:
class AcceptQueryParamOverride()\n def get_accept_list(self, request):\n header = request.META.get('HTTP_ACCEPT', '*/*')\n header = request.query_params.get('_accept', header)\n return [token.strip() for token in header.split(',')]\n"},{"location":"topics/browser-enhancements/#doesnt-html5-support-put-and-delete-forms","title":"Doesn't HTML5 support PUT and DELETE forms?","text":"Nope. It was at one point intended to support PUT and DELETE forms, but was later dropped from the spec. There remains ongoing discussion about adding support for PUT and DELETE, as well as how to support content types other than form-encoded data.
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.
\u2014 Roy Fielding, REST APIs must be hypertext driven
REST framework provides a range of different choices for documenting your API. The following is a non-exhaustive list of some of the most popular options.
"},{"location":"topics/documenting-your-api/#third-party-packages-for-openapi-support","title":"Third-party packages for OpenAPI support","text":"REST framework recommends using third-party packages for generating and presenting OpenAPI schemas, as they provide more features and flexibility than the built-in (deprecated) implementation.
"},{"location":"topics/documenting-your-api/#drf-spectacular","title":"drf-spectacular","text":"drf-spectacular is an OpenAPI 3 schema generation library with explicit focus on extensibility, customizability and client generation. It is the recommended way for generating and presenting OpenAPI schemas.
The library aims to extract as much schema information as possible, while providing decorators and extensions for easy customization. There is explicit support for swagger-codegen, SwaggerUI and Redoc, i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters, documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
"},{"location":"topics/documenting-your-api/#drf-yasg","title":"drf-yasg","text":"drf-yasg is a Swagger / OpenAPI 2 generation tool implemented without using the schema generation provided by Django Rest Framework.
It aims to implement as much of the OpenAPI 2 specification as possible - nested schemas, named models, response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code generation tools like swagger-codegen.
This also translates into a very useful interactive documentation viewer in the form of swagger-ui:
Warning
Deprecation notice: REST framework's built-in support for generating OpenAPI schemas is deprecated in favor of third-party packages that provide this functionality instead. As a replacement, we recommend using drf-spectacular.
There are a number of packages available that allow you to generate HTML documentation pages from OpenAPI schemas.
Two popular options are Swagger UI and ReDoc.
Both require little more than the location of your static schema file or dynamic SchemaView endpoint.
Assuming you've followed the example from the schemas documentation for routing a dynamic SchemaView, a minimal Django template for using Swagger UI might be this:
<!DOCTYPE html>\n<html>\n <head>\n <title>Swagger</title>\n <meta charset=\"utf-8\"/>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"//unpkg.com/swagger-ui-dist@3/swagger-ui.css\" />\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js\"></script>\n <script>\n const ui = SwaggerUIBundle({\n url: \"{% url schema_url %}\",\n dom_id: '#swagger-ui',\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n ],\n layout: \"BaseLayout\",\n requestInterceptor: (request) => {\n request.headers['X-CSRFToken'] = \"{{ csrf_token }}\"\n return request;\n }\n })\n </script>\n </body>\n</html>\n Save this in your templates folder as swagger-ui.html. Then route a TemplateView in your project's URL conf:
from django.views.generic import TemplateView\n\nurlpatterns = [\n # ...\n # Route TemplateView to serve Swagger UI template.\n # * Provide `extra_context` with view name of `SchemaView`.\n path(\n \"swagger-ui/\",\n TemplateView.as_view(\n template_name=\"swagger-ui.html\",\n extra_context={\"schema_url\": \"openapi-schema\"},\n ),\n name=\"swagger-ui\",\n ),\n]\n See the Swagger UI documentation for advanced usage.
"},{"location":"topics/documenting-your-api/#a-minimal-example-with-redoc","title":"A minimal example with ReDoc.","text":"Assuming you've followed the example from the schemas documentation for routing a dynamic SchemaView, a minimal Django template for using ReDoc might be this:
<!DOCTYPE html>\n<html>\n <head>\n <title>ReDoc</title>\n <!-- needed for adaptive design -->\n <meta charset=\"utf-8\"/>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link href=\"https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700\" rel=\"stylesheet\">\n <!-- ReDoc doesn't change outer page styles -->\n <style>\n body {\n margin: 0;\n padding: 0;\n }\n </style>\n </head>\n <body>\n <redoc spec-url='{% url schema_url %}'></redoc>\n <script src=\"https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js\"> </script>\n </body>\n</html>\n Save this in your templates folder as redoc.html. Then route a TemplateView in your project's URL conf:
from django.views.generic import TemplateView\n\nurlpatterns = [\n # ...\n # Route TemplateView to serve the ReDoc template.\n # * Provide `extra_context` with view name of `SchemaView`.\n path(\n \"redoc/\",\n TemplateView.as_view(\n template_name=\"redoc.html\", extra_context={\"schema_url\": \"openapi-schema\"}\n ),\n name=\"redoc\",\n ),\n]\n See the ReDoc documentation for advanced usage.
"},{"location":"topics/documenting-your-api/#self-describing-apis","title":"Self describing APIs","text":"The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.
"},{"location":"topics/documenting-your-api/#setting-the-title","title":"Setting the title","text":"The title that is used in the browsable API is generated from the view class name or function name. Any trailing View or ViewSet suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.
For example, the view UserListView, will be named User List when presented in the browsable API.
When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set UserViewSet will generate views named User List and User Instance.
The description in the browsable API is generated from the docstring of the view or viewset.
If the python Markdown library is installed, then markdown syntax may be used in the docstring, and will be converted to HTML in the browsable API. For example:
class AccountListView(views.APIView):\n \"\"\"\n Returns a list of all **active** accounts in the system.\n\n For more details on how accounts are activated please [see here][ref].\n\n [ref]: http://example.com/activating-accounts\n \"\"\"\n Note that when using viewsets the basic docstring is used for all generated views. To provide descriptions for each view, such as for the list and retrieve views, use docstring sections as described in Schemas as documentation: Examples.
"},{"location":"topics/documenting-your-api/#the-options-method","title":"TheOPTIONS method","text":"REST framework APIs also support programmatically accessible descriptions, using the OPTIONS HTTP method. A view will respond to an OPTIONS request with metadata including the name, description, and the various media types it accepts and responds with.
When using the generic views, any OPTIONS requests will additionally respond with metadata regarding any POST or PUT actions available, describing which fields are on the serializer.
You can modify the response behavior to OPTIONS requests by overriding the options view method and/or by providing a custom Metadata class. For example:
def options(self, request, *args, **kwargs):\n \"\"\"\n Don't include the view description in OPTIONS responses.\n \"\"\"\n meta = self.metadata_class()\n data = meta.determine_metadata(request, self)\n data.pop('description')\n return Response(data=data, status=status.HTTP_200_OK)\n See the Metadata docs for more details.
"},{"location":"topics/documenting-your-api/#the-hypermedia-approach","title":"The hypermedia approach","text":"To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.
In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the media types that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.
To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The REST, Hypermedia & HATEOAS section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.
"},{"location":"topics/html-and-forms/","title":"HTML & Forms","text":"REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates.
"},{"location":"topics/html-and-forms/#rendering-html","title":"Rendering HTML","text":"In order to return HTML responses you'll need to use either TemplateHTMLRenderer, or StaticHTMLRenderer.
The TemplateHTMLRenderer class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
The StaticHTMLRender class expects the response to contain a string of the pre-rendered HTML content.
Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.
Here's an example of a view that returns a list of \"Profile\" instances, rendered in an HTML template:
views.py:
from my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass ProfileList(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_list.html'\n\n def get(self, request):\n queryset = Profile.objects.all()\n return Response({'profiles': queryset})\n profile_list.html:
<html><body>\n<h1>Profiles</h1>\n<ul>\n {% for profile in profiles %}\n <li>{{ profile.name }}</li>\n {% endfor %}\n</ul>\n</body></html>\n"},{"location":"topics/html-and-forms/#rendering-forms","title":"Rendering Forms","text":"Serializers may be rendered as forms by using the render_form template tag, and including the serializer instance as context to the template.
The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
views.py:
from django.shortcuts import get_object_or_404\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileDetail(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_detail.html'\n\n def get(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile)\n return Response({'serializer': serializer, 'profile': profile})\n\n def post(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile, data=request.data)\n if not serializer.is_valid():\n return Response({'serializer': serializer, 'profile': profile})\n serializer.save()\n return redirect('profile-list')\n profile_detail.html:
{% load rest_framework %}\n\n<html><body>\n\n<h1>Profile - {{ profile.name }}</h1>\n\n<form action=\"{% url 'profile-detail' pk=profile.pk %}\" method=\"POST\">\n {% csrf_token %}\n {% render_form serializer %}\n <input type=\"submit\" value=\"Save\">\n</form>\n\n</body></html>\n"},{"location":"topics/html-and-forms/#using-template-packs","title":"Using template packs","text":"The render_form tag takes an optional template_pack argument, that specifies which template directory should be used for rendering the form and form fields.
REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are horizontal, vertical, and inline. The default style is horizontal. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.
The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
<head>\n \u2026\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\">\n</head>\n Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.
Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a \"Login\" form.
class LoginSerializer(serializers.Serializer):\n email = serializers.EmailField(\n max_length=100,\n style={'placeholder': 'Email', 'autofocus': True}\n )\n password = serializers.CharField(\n max_length=100,\n style={'input_type': 'password', 'placeholder': 'Password'}\n )\n remember_me = serializers.BooleanField()\n"},{"location":"topics/html-and-forms/#rest_frameworkvertical","title":"rest_framework/vertical","text":"Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.
This is the default template pack.
{% load rest_framework %}\n\n...\n\n<form action=\"{% url 'login' %}\" method=\"post\" novalidate>\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/vertical' %}\n <button type=\"submit\" class=\"btn btn-default\">Sign in</button>\n</form>\n "},{"location":"topics/html-and-forms/#rest_frameworkhorizontal","title":"rest_framework/horizontal","text":"Presents labels and controls alongside each other, using a 2/10 column split.
This is the form style used in the browsable API and admin renderers.
{% load rest_framework %}\n\n...\n\n<form class=\"form-horizontal\" action=\"{% url 'login' %}\" method=\"post\" novalidate>\n {% csrf_token %}\n {% render_form serializer %}\n <div class=\"form-group\">\n <div class=\"col-sm-offset-2 col-sm-10\">\n <button type=\"submit\" class=\"btn btn-default\">Sign in</button>\n </div>\n </div>\n</form>\n "},{"location":"topics/html-and-forms/#rest_frameworkinline","title":"rest_framework/inline","text":"A compact form style that presents all the controls inline.
{% load rest_framework %}\n\n...\n\n<form class=\"form-inline\" action=\"{% url 'login' %}\" method=\"post\" novalidate>\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/inline' %}\n <button type=\"submit\" class=\"btn btn-default\">Sign in</button>\n</form>\n "},{"location":"topics/html-and-forms/#field-styles","title":"Field styles","text":"Serializer fields can have their rendering style customized by using the style keyword argument. This argument is a dictionary of options that control the template and layout used.
The most common way to customize the field style is to use the base_template style keyword argument to select which template in the template pack should be use.
For example, to render a CharField as an HTML textarea rather than the default HTML input, you would use something like this:
details = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html'}\n)\n If you instead want a field to be rendered using a custom template that is not part of an included template pack, you can instead use the template style option, to fully specify a template name:
details = serializers.CharField(\n max_length=1000,\n style={'template': 'my-field-templates/custom-input.html'}\n)\n Field templates can also use additional style properties, depending on their type. For example, the textarea.html template also accepts a rows property that can be used to affect the sizing of the control.
details = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html', 'rows': 10}\n)\n The complete list of base_template options and their associated style options is listed below.
CharField rows, placeholder, hide_label select.html ChoiceField or relational field types hide_label radio.html ChoiceField or relational field types inline, hide_label select_multiple.html MultipleChoiceField or relational fields with many=True hide_label checkbox_multiple.html MultipleChoiceField or relational fields with many=True inline, hide_label checkbox.html BooleanField hide_label fieldset.html Nested serializer hide_label list_fieldset.html ListField or nested serializer with many=True hide_label"},{"location":"topics/internationalization/","title":"Internationalization","text":"Supporting internationalization is not optional. It must be a core feature.
\u2014 Jannis Leidel, speaking at Django Under the Hood, 2015.
REST framework ships with translatable error messages. You can make these appear in your language enabling Django's standard translation mechanisms.
Doing so will allow you to:
LANGUAGE_CODE Django setting.LocaleMiddleware included with Django. A typical usage for API clients would be to include an Accept-Language request header.You can change the default language by using the standard Django LANGUAGE_CODE setting:
LANGUAGE_CODE = \"es-es\"\n You can turn on per-request language requests by adding LocalMiddleware to your MIDDLEWARE setting:
MIDDLEWARE = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n]\n When per-request internationalization is enabled, client requests will respect the Accept-Language header where possible. For example, let's make a request for an unsupported media type:
Request
GET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org\n Response
HTTP/1.0 406 NOT ACCEPTABLE\n\n{\"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"}\n REST framework includes these built-in translations both for standard exception cases, and for serializer validation errors.
Note that the translations only apply to the error strings themselves. The format of error messages, and the keys of field names will remain the same. An example 400 Bad Request response body might look like this:
{\"detail\": {\"username\": [\"Esse campo deve ser \u00fanico.\"]}}\n If you want to use different string for parts of the response such as detail and non_field_errors then you can modify this behavior by using a custom exception handler.
By default all available languages will be supported.
If you only wish to support a subset of the available languages, use Django's standard LANGUAGES setting:
LANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n]\n"},{"location":"topics/internationalization/#adding-new-translations","title":"Adding new translations","text":"REST framework translations are managed on GitHub. You can contribute new translation languages or update existing ones by following the guidelines in the Contributing to REST Framework section and submitting a pull request.
Sometimes you may need to add translation strings to your project locally. You may need to do this if:
This guide assumes you are already familiar with how to translate a Django app. If you're not, start by reading Django's translation docs.
If you're translating a new language you'll need to translate the existing REST framework error messages:
Make a new folder where you want to store the internationalization resources. Add this path to your LOCALE_PATHS setting.
Now create a subfolder for the language you want to translate. The folder should be named using locale name notation. For example: de, pt_BR, es_AR.
Now copy the base translations file from the REST framework source code into your translations folder.
Edit the django.po file you've just copied, translating all the error messages.
Run manage.py compilemessages -l pt_BR to make the translations available for Django to use. You should see a message like processing file django.po in <...>/locale/pt_BR/LC_MESSAGES.
Restart your development server to see the changes take effect.
If you're only translating custom error messages that exist inside your project codebase you don't need to copy the REST framework source django.po file into a LOCALE_PATHS folder, and can instead simply run Django's standard makemessages process.
If you want to allow per-request language preferences you'll need to include django.middleware.locale.LocaleMiddleware in your MIDDLEWARE setting.
You can find more information on how the language preference is determined in the Django documentation. For reference, the method is:
LANGUAGE_SESSION_KEY key in the current user\u2019s session.Accept-Language HTTP header.LANGUAGE_CODE setting.For API clients the most appropriate of these will typically be to use the Accept-Language header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an Accept-Language header for API clients rather than using language URL prefixes.
You keep using that word \"REST\". I do not think it means what you think it means.
\u2014 Mike Amundsen, REST fest 2012 keynote.
First off, the disclaimer. The name \"Django REST framework\" was decided back in early 2011 and was chosen simply to ensure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of \"Web APIs\".
If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.
The following fall into the \"required reading\" category.
For a more thorough background, check out Klabnik's Hypermedia API reading list.
"},{"location":"topics/rest-hypermedia-hateoas/#building-hypermedia-apis-with-rest-framework","title":"Building Hypermedia APIs with REST framework","text":"REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.
"},{"location":"topics/rest-hypermedia-hateoas/#what-rest-framework-provides","title":"What REST framework provides.","text":"It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.
REST framework also includes serialization and parser/renderer components that make it easy to build appropriate media types, hyperlinked relations for building well-connected systems, and great support for content negotiation.
"},{"location":"topics/rest-hypermedia-hateoas/#what-rest-framework-doesnt-provide","title":"What REST framework doesn't provide.","text":"What REST framework doesn't do is give you machine readable hypermedia formats such as HAL, Collection+JSON, JSON API or HTML microformats by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labeled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
"},{"location":"topics/writable-nested-serializers/","title":"Writable nested serializers","text":"To save HTTP requests, it may be convenient to send related documents along with the request.
\u2014 JSON API specification for Ember Data.
"},{"location":"topics/writable-nested-serializers/#writable-nested-serializers","title":"Writable nested serializers","text":"Although flat data structures serve to properly delineate between the individual entities in your service, there are cases where it may be more appropriate or convenient to use nested data structures.
Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependencies between the various model instances, and the need to save or delete multiple instances in a single action.
"},{"location":"topics/writable-nested-serializers/#one-to-many-data-structures","title":"One-to-many data structures","text":"Example of a read-only nested serializer. Nothing complex to worry about here.
class ToDoItemSerializer(serializers.ModelSerializer):\n class Meta:\n model = ToDoItem\n fields = ['text', 'is_completed']\n\nclass ToDoListSerializer(serializers.ModelSerializer):\n items = ToDoItemSerializer(many=True, read_only=True)\n\n class Meta:\n model = ToDoList\n fields = ['title', 'items']\n Some example output from our serializer.
{\n 'title': 'Leaving party preparations',\n 'items': [\n {'text': 'Compile playlist', 'is_completed': True},\n {'text': 'Send invites', 'is_completed': False},\n {'text': 'Clean house', 'is_completed': False}\n ]\n}\n Let's take a look at updating our nested one-to-many data structure.
"},{"location":"topics/writable-nested-serializers/#validation-errors","title":"Validation errors","text":""},{"location":"topics/writable-nested-serializers/#adding-and-removing-items","title":"Adding and removing items","text":""},{"location":"topics/writable-nested-serializers/#making-patch-requests","title":"Making PATCH requests","text":""},{"location":"tutorial/1-serialization/","title":"Tutorial 1: Serialization","text":""},{"location":"tutorial/1-serialization/#introduction","title":"Introduction","text":"This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.
The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the quickstart documentation instead.
Note
The code for this tutorial is available in the encode/rest-framework-tutorial repository on GitHub. Feel free to clone the repository and see the code in action.
"},{"location":"tutorial/1-serialization/#setting-up-a-new-environment","title":"Setting up a new environment","text":"Before we do anything else we'll create a new virtual environment called .venv, using venv. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.
python3 -m venv .venv\nsource .venv/bin/activate\n If you use Bash for Windows
python3 -m venv .venv\nsource .venv\\Scripts\\activate\n Now that we're inside a virtual environment, we can install our package requirements.
pip install django\npip install djangorestframework\npip install pygments # We'll be using this for the code highlighting\n Tip
To exit the virtual environment at any time, just type deactivate. For more information see the venv documentation.
Okay, we're ready to get coding. To get started, let's create a new project to work with.
cd ~\ndjango-admin startproject tutorial\ncd tutorial\n Once that's done we can create an app that we'll use to create a simple Web API.
python manage.py startapp snippets\n We'll need to add our new snippets app and the rest_framework app to INSTALLED_APPS. Let's edit the tutorial/settings.py file:
INSTALLED_APPS = [\n ...\n 'rest_framework',\n 'snippets',\n]\n Okay, we're ready to roll.
"},{"location":"tutorial/1-serialization/#creating-a-model-to-work-with","title":"Creating a model to work with","text":"For the purposes of this tutorial we're going to start by creating a simple Snippet model that is used to store code snippets. Go ahead and edit the snippets/models.py file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
from django.db import models\nfrom pygments.lexers import get_all_lexers\nfrom pygments.styles import get_all_styles\n\nLEXERS = [item for item in get_all_lexers() if item[1]]\nLANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])\nSTYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])\n\n\nclass Snippet(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n title = models.CharField(max_length=100, blank=True, default=\"\")\n code = models.TextField()\n linenos = models.BooleanField(default=False)\n language = models.CharField(\n choices=LANGUAGE_CHOICES, default=\"python\", max_length=100\n )\n style = models.CharField(choices=STYLE_CHOICES, default=\"friendly\", max_length=100)\n\n class Meta:\n ordering = [\"created\"]\n We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
python manage.py makemigrations snippets\npython manage.py migrate snippets\n"},{"location":"tutorial/1-serialization/#creating-a-serializer-class","title":"Creating a Serializer class","text":"The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as json. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the snippets directory named serializers.py and add the following.
from rest_framework import serializers\nfrom snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass SnippetSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n title = serializers.CharField(required=False, allow_blank=True, max_length=100)\n code = serializers.CharField(style={\"base_template\": \"textarea.html\"})\n linenos = serializers.BooleanField(required=False)\n language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default=\"python\")\n style = serializers.ChoiceField(choices=STYLE_CHOICES, default=\"friendly\")\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Snippet` instance, given the validated data.\n \"\"\"\n return Snippet.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Snippet` instance, given the validated data.\n \"\"\"\n instance.title = validated_data.get(\"title\", instance.title)\n instance.code = validated_data.get(\"code\", instance.code)\n instance.linenos = validated_data.get(\"linenos\", instance.linenos)\n instance.language = validated_data.get(\"language\", instance.language)\n instance.style = validated_data.get(\"style\", instance.style)\n instance.save()\n return instance\n The first part of the serializer class defines the fields that get serialized/deserialized. The create() and update() methods define how fully fledged instances are created or modified when calling serializer.save()
A serializer class is very similar to a Django Form class, and includes similar validation flags on the various fields, such as required, max_length and default.
The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The {'base_template': 'textarea.html'} flag above is equivalent to using widget=widgets.Textarea on a Django Form class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.
We can actually also save ourselves some time by using the ModelSerializer class, as we'll see later, but for now we'll keep our serializer definition explicit.
Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.
python manage.py shell\n Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
>>> from snippets.models import Snippet\n>>> from snippets.serializers import SnippetSerializer\n>>> from rest_framework.renderers import JSONRenderer\n>>> from rest_framework.parsers import JSONParser\n\n>>> snippet = Snippet(code='foo = \"bar\"\\n')\n>>> snippet.save()\n\n>>> snippet = Snippet(code='print(\"hello, world\")\\n')\n>>> snippet.save()\n We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
>>> serializer = SnippetSerializer(snippet)\n>>> serializer.data\n{'id': 2, 'title': '', 'code': 'print(\"hello, world\")\\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}\n At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into json.
>>> content = JSONRenderer().render(serializer.data)\n>>> content\nb'{\"id\":2,\"title\":\"\",\"code\":\"print(\\\\\"hello, world\\\\\")\\\\n\",\"linenos\":false,\"language\":\"python\",\"style\":\"friendly\"}'\n Deserialization is similar. First we parse a stream into Python native datatypes...
>>> import io\n\n>>> stream = io.BytesIO(content)\n>>> data = JSONParser().parse(stream)\n ...then we restore those native datatypes into a fully populated object instance.
>>> serializer = SnippetSerializer(data=data)\n>>> serializer.is_valid()\nTrue\n>>> serializer.validated_data\n{'title': '', 'code': 'print(\"hello, world\")', 'linenos': False, 'language': 'python', 'style': 'friendly'}\n>>> serializer.save()\n<Snippet: Snippet object>\n Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.
We can also serialize querysets instead of model instances. To do so we simply add a many=True flag to the serializer arguments.
>>> serializer = SnippetSerializer(Snippet.objects.all(), many=True)\n>>> serializer.data\n[{'id': 1, 'title': '', 'code': 'foo = \"bar\"\\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 2, 'title': '', 'code': 'print(\"hello, world\")\\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 3, 'title': '', 'code': 'print(\"hello, world\")', 'linenos': False, 'language': 'python', 'style': 'friendly'}]\n"},{"location":"tutorial/1-serialization/#using-modelserializers","title":"Using ModelSerializers","text":"Our SnippetSerializer class is replicating a lot of information that's also contained in the Snippet model. It would be nice if we could keep our code a bit more concise.
In the same way that Django provides both Form classes and ModelForm classes, REST framework includes both Serializer classes, and ModelSerializer classes.
Let's look at refactoring our serializer using the ModelSerializer class. Open the file snippets/serializers.py again, and replace the SnippetSerializer class with the following.
from rest_framework import serializers\nfrom snippets.models import Snippet\n\n\nclass SnippetSerializer(serializers.ModelSerializer):\n class Meta:\n model = Snippet\n fields = [\"id\", \"title\", \"code\", \"linenos\", \"language\", \"style\"]\n One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with python manage.py shell, then try the following:
>>> from snippets.serializers import SnippetSerializer\n\n>>> serializer = SnippetSerializer()\n>>> print(repr(serializer))\nSnippetSerializer():\n id = IntegerField(label='ID', read_only=True)\n title = CharField(allow_blank=True, max_length=100, required=False)\n code = CharField(style={'base_template': 'textarea.html'})\n linenos = BooleanField(required=False)\n language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...\n style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...\n It's important to remember that ModelSerializer classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:
create() and update() methods.Let's see how we can write some API views using our new Serializer class. For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.
Edit the snippets/views.py file, and add the following.
from django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
@csrf_exempt\ndef snippet_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == \"GET\":\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == \"POST\":\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
@csrf_exempt\ndef snippet_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == \"GET\":\n serializer = SnippetSerializer(snippet)\n return JsonResponse(serializer.data)\n\n elif request.method == \"PUT\":\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(snippet, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == \"DELETE\":\n snippet.delete()\n return HttpResponse(status=204)\n Finally we need to wire these views up. Create the snippets/urls.py file:
from django.urls import path\nfrom snippets import views\n\nurlpatterns = [\n path(\"snippets/\", views.snippet_list),\n path(\"snippets/<int:pk>/\", views.snippet_detail),\n]\n We also need to wire up the root urlconf, in the tutorial/urls.py file, to include our snippet app's URLs.
from django.urls import path, include\n\nurlpatterns = [\n path(\"\", include(\"snippets.urls\")),\n]\n It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed json, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 \"server error\" response. Still, this'll do for now.
Now we can start up a sample server that serves our snippets.
Quit out of the shell...
>>> quit()\n ...and start up Django's development server.
python manage.py runserver\n\nValidating models...\n\n0 errors found\nDjango version 5.0, using settings 'tutorial.settings'\nStarting Development server at http://127.0.0.1:8000/\nQuit the server with CONTROL-C.\n In another terminal window, we can test the server.
We can test our API using curl or HTTPie. HTTPie is a user-friendly http client that's written in Python. Let's install that.
You can install HTTPie using pip:
pip install httpie\n Finally, we can get a list of all of the snippets:
http GET http://127.0.0.1:8000/snippets/ --unsorted\n\nHTTP/1.1 200 OK\n...\n[\n {\n \"id\": 1,\n \"title\": \"\",\n \"code\": \"foo = \\\"bar\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print(\\\"hello, world\\\")\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 3,\n \"title\": \"\",\n \"code\": \"print(\\\"hello, world\\\")\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n }\n]\n Or we can get a particular snippet by referencing its id:
http GET http://127.0.0.1:8000/snippets/2/ --unsorted\n\nHTTP/1.1 200 OK\n...\n{\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print(\\\"hello, world\\\")\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n Similarly, you can have the same json displayed by visiting these URLs in a web browser.
"},{"location":"tutorial/1-serialization/#where-are-we-now","title":"Where are we now","text":"We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.
Our API views don't do anything particularly special at the moment, beyond serving json responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.
We'll see how we can start to improve things in part 2 of the tutorial.
"},{"location":"tutorial/2-requests-and-responses/","title":"Tutorial 2: Requests and Responses","text":"From this point we're going to really start covering the core of REST framework. Let's introduce a couple of essential building blocks.
"},{"location":"tutorial/2-requests-and-responses/#request-objects","title":"Request objects","text":"REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing. The core functionality of the Request object is the request.data attribute, which is similar to request.POST, but more useful for working with Web APIs.
request.POST # Only handles form data. Only works for 'POST' method.\nrequest.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.\n"},{"location":"tutorial/2-requests-and-responses/#response-objects","title":"Response objects","text":"REST framework also introduces a Response object, which is a type of TemplateResponse that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.
return Response(data) # Renders to content type as requested by the client.\n"},{"location":"tutorial/2-requests-and-responses/#status-codes","title":"Status codes","text":"Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as HTTP_400_BAD_REQUEST in the status module. It's a good idea to use these throughout rather than using numeric identifiers.
REST framework provides two wrappers you can use to write API views.
@api_view decorator for working with function based views.APIView class for working with class-based views.These wrappers provide a few bits of functionality such as making sure you receive Request instances in your view, and adding context to Response objects so that content negotiation can be performed.
The wrappers also provide behavior such as returning 405 Method Not Allowed responses when appropriate, and handling any ParseError exceptions that occur when accessing request.data with malformed input.
Okay, let's go ahead and start using these new components to refactor our views slightly.
from rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\n@api_view([\"GET\", \"POST\"])\ndef snippet_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == \"GET\":\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return Response(serializer.data)\n\n elif request.method == \"POST\":\n serializer = SnippetSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
Here is the view for an individual snippet, in the views.py module.
@api_view([\"GET\", \"PUT\", \"DELETE\"])\ndef snippet_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == \"GET\":\n serializer = SnippetSerializer(snippet)\n return Response(serializer.data)\n\n elif request.method == \"PUT\":\n serializer = SnippetSerializer(snippet, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == \"DELETE\":\n snippet.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n This should all feel very familiar - it is not a lot different from working with regular Django views.
Notice that we're no longer explicitly tying our requests or responses to a given content type. request.data can handle incoming json requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as http://example.com/api/items/4.json.
Start by adding a format keyword argument to both of the views, like so. def snippet_list(request, format=None): and def snippet_detail(request, pk, format=None):
Now update the snippets/urls.py file slightly, to append a set of format_suffix_patterns in addition to the existing URLs.
from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n path(\"snippets/\", views.snippet_list),\n path(\"snippets/<int:pk>/\", views.snippet_detail),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.
"},{"location":"tutorial/2-requests-and-responses/#hows-it-looking","title":"How's it looking?","text":"Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
We can get a list of all of the snippets, as before.
http http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n {\n \"id\": 1,\n \"title\": \"\",\n \"code\": \"foo = \\\"bar\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print(\\\"hello, world\\\")\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n }\n]\n We can control the format of the response that we get back, either by using the Accept header:
http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON\nhttp http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML\n Or by appending a format suffix:
http http://127.0.0.1:8000/snippets.json # JSON suffix\nhttp http://127.0.0.1:8000/snippets.api # Browsable API suffix\n Similarly, we can control the format of the request that we send, using the Content-Type header.
# POST using form data\nhttp --form POST http://127.0.0.1:8000/snippets/ code=\"print(123)\"\n\n{\n \"id\": 3,\n \"title\": \"\",\n \"code\": \"print(123)\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n\n# POST using JSON\nhttp --json POST http://127.0.0.1:8000/snippets/ code=\"print(456)\"\n\n{\n \"id\": 4,\n \"title\": \"\",\n \"code\": \"print(456)\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n If you add a --debug switch to the http requests above, you will be able to see the request type in request headers.
Now go and open the API in a web browser, by visiting http://127.0.0.1:8000/snippets/.
"},{"location":"tutorial/2-requests-and-responses/#browsability","title":"Browsability","text":"Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.
See the browsable api topic for more information about the browsable API feature and how to customize it.
"},{"location":"tutorial/2-requests-and-responses/#whats-next","title":"What's next?","text":"In tutorial part 3, we'll start using class-based views, and see how generic views reduce the amount of code we need to write.
"},{"location":"tutorial/3-class-based-views/","title":"Tutorial 3: Class-based Views","text":"We can also write our API views using class-based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code DRY.
"},{"location":"tutorial/3-class-based-views/#rewriting-our-api-using-class-based-views","title":"Rewriting our API using class-based views","text":"We'll start by rewriting the root view as a class-based view. All this involves is a little bit of refactoring of views.py.
from snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom django.http import Http404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n\nclass SnippetList(APIView):\n \"\"\"\n List all snippets, or create a new snippet.\n \"\"\"\n\n def get(self, request, format=None):\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return Response(serializer.data)\n\n def post(self, request, format=None):\n serializer = SnippetSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in views.py.
class SnippetDetail(APIView):\n \"\"\"\n Retrieve, update or delete a snippet instance.\n \"\"\"\n\n def get_object(self, pk):\n try:\n return Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n raise Http404\n\n def get(self, request, pk, format=None):\n snippet = self.get_object(pk)\n serializer = SnippetSerializer(snippet)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n snippet = self.get_object(pk)\n serializer = SnippetSerializer(snippet, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n snippet = self.get_object(pk)\n snippet.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n That's looking good. Again, it's still pretty similar to the function based view right now.
We'll also need to refactor our snippets/urls.py slightly now that we're using class-based views.
from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n path(\"snippets/\", views.SnippetList.as_view()),\n path(\"snippets/<int:pk>/\", views.SnippetDetail.as_view()),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n Okay, we're done. If you run the development server everything should be working just as before.
"},{"location":"tutorial/3-class-based-views/#using-mixins","title":"Using mixins","text":"One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior.
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behavior are implemented in REST framework's mixin classes.
Let's take a look at how we can compose the views by using the mixin classes. Here's our views.py module again.
from snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework import mixins\nfrom rest_framework import generics\n\n\nclass SnippetList(\n mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView\n):\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n\n def get(self, request, *args, **kwargs):\n return self.list(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n return self.create(request, *args, **kwargs)\n We'll take a moment to examine exactly what's happening here. We're building our view using GenericAPIView, and adding in ListModelMixin and CreateModelMixin.
The base class provides the core functionality, and the mixin classes provide the .list() and .create() actions. We're then explicitly binding the get and post methods to the appropriate actions. Simple enough stuff so far.
class SnippetDetail(\n mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n mixins.DestroyModelMixin,\n generics.GenericAPIView,\n):\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n\n def get(self, request, *args, **kwargs):\n return self.retrieve(request, *args, **kwargs)\n\n def put(self, request, *args, **kwargs):\n return self.update(request, *args, **kwargs)\n\n def delete(self, request, *args, **kwargs):\n return self.destroy(request, *args, **kwargs)\n Pretty similar. Again we're using the GenericAPIView class to provide the core functionality, and adding in mixins to provide the .retrieve(), .update() and .destroy() actions.
Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our views.py module even more.
from snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework import generics\n\n\nclass SnippetList(generics.ListCreateAPIView):\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n\n\nclass SnippetDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.
Next we'll move onto part 4 of the tutorial, where we'll take a look at how we can deal with authentication and permissions for our API.
"},{"location":"tutorial/4-authentication-and-permissions/","title":"Tutorial 4: Authentication & Permissions","text":"Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:
We're going to make a couple of changes to our Snippet model class. First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.
Add the following two fields to the Snippet model in models.py.
owner = models.ForeignKey(\n \"auth.User\", related_name=\"snippets\", on_delete=models.CASCADE\n)\nhighlighted = models.TextField()\n We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the pygments code highlighting library.
We'll need some extra imports:
from pygments.lexers import get_lexer_by_name\nfrom pygments.formatters.html import HtmlFormatter\nfrom pygments import highlight\n And now we can add a .save() method to our model class:
def save(self, *args, **kwargs):\n \"\"\"\n Use the `pygments` library to create a highlighted HTML\n representation of the code snippet.\n \"\"\"\n lexer = get_lexer_by_name(self.language)\n linenos = \"table\" if self.linenos else False\n options = {\"title\": self.title} if self.title else {}\n formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)\n self.highlighted = highlight(self.code, lexer, formatter)\n super().save(*args, **kwargs)\n When that's all done we'll need to update our database tables. Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
rm -f db.sqlite3\nrm -r snippets/migrations\npython manage.py makemigrations snippets\npython manage.py migrate\n You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the createsuperuser command.
python manage.py createsuperuser\n"},{"location":"tutorial/4-authentication-and-permissions/#adding-endpoints-for-our-user-models","title":"Adding endpoints for our User models","text":"Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In serializers.py add:
from django.contrib.auth.models import User\n\n\nclass UserSerializer(serializers.ModelSerializer):\n snippets = serializers.PrimaryKeyRelatedField(\n many=True, queryset=Snippet.objects.all()\n )\n\n class Meta:\n model = User\n fields = [\"id\", \"username\", \"snippets\"]\n Because 'snippets' is a reverse relationship on the User model, it will not be included by default when using the ModelSerializer class, so we needed to add an explicit field for it.
We'll also add a couple of views to views.py. We'd like to just use read-only views for the user representations, so we'll use the ListAPIView and RetrieveAPIView generic class-based views.
from django.contrib.auth.models import User\n\n\nclass UserList(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass UserDetail(generics.RetrieveAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n Make sure to also import the UserSerializer class
from snippets.serializers import UserSerializer\n Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in snippets/urls.py.
path(\"users/\", views.UserList.as_view()),\npath(\"users/<int:pk>/\", views.UserDetail.as_view()),\n"},{"location":"tutorial/4-authentication-and-permissions/#associating-snippets-with-users","title":"Associating Snippets with Users","text":"Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.
The way we deal with that is by overriding a .perform_create() method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.
On the SnippetList view class, add the following method:
def perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n The create() method of our serializer will now be passed an additional 'owner' field, along with the validated data from the request.
Now that snippets are associated with the user that created them, let's update our SnippetSerializer to reflect that. Add the following field to the serializer definition in serializers.py:
owner = serializers.ReadOnlyField(source=\"owner.username\")\n Note
Make sure you also add 'owner', to the list of fields in the inner Meta class.
This field is doing something quite interesting. The source argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.
The field we've added is the untyped ReadOnlyField class, in contrast to the other typed fields, such as CharField, BooleanField etc... The untyped ReadOnlyField is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used CharField(read_only=True) here.
Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.
REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is IsAuthenticatedOrReadOnly, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.
First add the following import in the views module
from rest_framework import permissions\n Then, add the following property to both the SnippetList and SnippetDetail view classes.
permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n"},{"location":"tutorial/4-authentication-and-permissions/#adding-login-to-the-browsable-api","title":"Adding login to the Browsable API","text":"If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
We can add a login view for use with the browsable API, by editing the URLconf in our project-level urls.py file.
Add the following import at the top of the file:
from django.urls import path, include\n And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
urlpatterns += [\n path(\"api-auth/\", include(\"rest_framework.urls\")),\n]\n The 'api-auth/' part of pattern can actually be whatever URL you want to use.
Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.
Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet ids that are associated with each user, in each user's 'snippets' field.
"},{"location":"tutorial/4-authentication-and-permissions/#object-level-permissions","title":"Object level permissions","text":"Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.
To do that we're going to need to create a custom permission.
In the snippets app, create a new file, permissions.py
from rest_framework import permissions\n\n\nclass IsOwnerOrReadOnly(permissions.BasePermission):\n \"\"\"\n Custom permission to only allow owners of an object to edit it.\n \"\"\"\n\n def has_object_permission(self, request, view, obj):\n # Read permissions are allowed to any request,\n # so we'll always allow GET, HEAD or OPTIONS requests.\n if request.method in permissions.SAFE_METHODS:\n return True\n\n # Write permissions are only allowed to the owner of the snippet.\n return obj.owner == request.user\n Now we can add that custom permission to our snippet instance endpoint, by editing the permission_classes property on the SnippetDetail view class:
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]\n Make sure to also import the IsOwnerOrReadOnly class.
from snippets.permissions import IsOwnerOrReadOnly\n Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
"},{"location":"tutorial/4-authentication-and-permissions/#authenticating-with-the-api","title":"Authenticating with the API","text":"Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are SessionAuthentication and BasicAuthentication.
When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.
If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.
If we try to create a snippet without authenticating, we'll get an error:
http POST http://127.0.0.1:8000/snippets/ code=\"print(123)\"\n\n{\n \"detail\": \"Authentication credentials were not provided.\"\n}\n We can make a successful request by including the username and password of one of the users we created earlier.
http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code=\"print(789)\"\n\n{\n \"id\": 1,\n \"owner\": \"admin\",\n \"title\": \"foo\",\n \"code\": \"print(789)\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n"},{"location":"tutorial/4-authentication-and-permissions/#summary","title":"Summary","text":"We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.
In part 5 of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
"},{"location":"tutorial/5-relationships-and-hyperlinked-apis/","title":"Tutorial 5: Relationships & Hyperlinked APIs","text":"At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.
"},{"location":"tutorial/5-relationships-and-hyperlinked-apis/#creating-an-endpoint-for-the-root-of-our-api","title":"Creating an endpoint for the root of our API","text":"Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the @api_view decorator we introduced earlier. In your snippets/views.py add:
from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\n\n\n@api_view([\"GET\"])\ndef api_root(request, format=None):\n return Response(\n {\n \"users\": reverse(\"user-list\", request=request, format=format),\n \"snippets\": reverse(\"snippet-list\", request=request, format=format),\n }\n )\n Two things should be noticed here. First, we're using REST framework's reverse function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our snippets/urls.py.
The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.
Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.
The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own .get() method. In your snippets/views.py add:
from rest_framework import renderers\n\n\nclass SnippetHighlight(generics.GenericAPIView):\n queryset = Snippet.objects.all()\n renderer_classes = [renderers.StaticHTMLRenderer]\n\n def get(self, request, *args, **kwargs):\n snippet = self.get_object()\n return Response(snippet.highlighted)\n As usual we need to add the new views that we've created in to our URLconf. We'll add a url pattern for our new API root in snippets/urls.py:
path(\"\", views.api_root),\n And then add a url pattern for the snippet highlights:
path(\"snippets/<int:pk>/highlight/\", views.SnippetHighlight.as_view()),\n"},{"location":"tutorial/5-relationships-and-hyperlinked-apis/#hyperlinking-our-api","title":"Hyperlinking our API","text":"Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:
REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.
In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend HyperlinkedModelSerializer instead of the existing ModelSerializer.
The HyperlinkedModelSerializer has the following differences from ModelSerializer:
id field by default.url field, using HyperlinkedIdentityField.HyperlinkedRelatedField, instead of PrimaryKeyRelatedField.We can easily re-write our existing serializers to use hyperlinking. In your snippets/serializers.py add:
class SnippetSerializer(serializers.HyperlinkedModelSerializer):\n owner = serializers.ReadOnlyField(source=\"owner.username\")\n highlight = serializers.HyperlinkedIdentityField(\n view_name=\"snippet-highlight\", format=\"html\"\n )\n\n class Meta:\n model = Snippet\n fields = [\n \"url\",\n \"id\",\n \"highlight\",\n \"owner\",\n \"title\",\n \"code\",\n \"linenos\",\n \"language\",\n \"style\",\n ]\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n snippets = serializers.HyperlinkedRelatedField(\n many=True, view_name=\"snippet-detail\", read_only=True\n )\n\n class Meta:\n model = User\n fields = [\"url\", \"id\", \"username\", \"snippets\"]\n Notice that we've also added a new 'highlight' field. This field is of the same type as the url field, except that it points to the 'snippet-highlight' url pattern, instead of the 'snippet-detail' url pattern.
Because we've included format suffixed URLs such as '.json', we also need to indicate on the highlight field that any format suffixed hyperlinks it returns should use the '.html' suffix.
Note
When you are manually instantiating these serializers inside your views (e.g., in SnippetDetail or SnippetList), you must pass context={'request': request} so the serializer knows how to build absolute URLs. For example, instead of:
serializer = SnippetSerializer(snippet)\n You must write:
serializer = SnippetSerializer(snippet, context={\"request\": request})\n If your view is a subclass of GenericAPIView, you may use the get_serializer_context() as a convenience method.
If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.
'user-list' and 'snippet-list'.'snippet-highlight'.'snippet-detail'.'url' fields that by default will refer to '{model_name}-detail', which in this case will be 'snippet-detail' and 'user-detail'.After adding all those names into our URLconf, our final snippets/urls.py file should look like this:
from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\n# API endpoints\nurlpatterns = format_suffix_patterns(\n [\n path(\"\", views.api_root),\n path(\"snippets/\", views.SnippetList.as_view(), name=\"snippet-list\"),\n path(\n \"snippets/<int:pk>/\", views.SnippetDetail.as_view(), name=\"snippet-detail\"\n ),\n path(\n \"snippets/<int:pk>/highlight/\",\n views.SnippetHighlight.as_view(),\n name=\"snippet-highlight\",\n ),\n path(\"users/\", views.UserList.as_view(), name=\"user-list\"),\n path(\"users/<int:pk>/\", views.UserDetail.as_view(), name=\"user-detail\"),\n ]\n)\n"},{"location":"tutorial/5-relationships-and-hyperlinked-apis/#adding-pagination","title":"Adding pagination","text":"The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.
We can change the default list style to use pagination, by modifying our tutorial/settings.py file slightly. Add the following setting:
REST_FRAMEWORK = {\n \"DEFAULT_PAGINATION_CLASS\": \"rest_framework.pagination.PageNumberPagination\",\n \"PAGE_SIZE\": 10,\n}\n Note that settings in REST framework are all namespaced into a single dictionary setting, named REST_FRAMEWORK, which helps keep them well separated from your other project settings.
We could also customize the pagination style if we needed to, but in this case we'll just stick with the default.
"},{"location":"tutorial/5-relationships-and-hyperlinked-apis/#browsing-the-api","title":"Browsing the API","text":"If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.
You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.
In part 6 of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.
"},{"location":"tutorial/6-viewsets-and-routers/","title":"Tutorial 6: ViewSets & Routers","text":"REST framework includes an abstraction for dealing with ViewSets, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.
ViewSet classes are almost the same thing as View classes, except that they provide operations such as retrieve, or update, and not method handlers such as get or put.
A ViewSet class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a Router class which handles the complexities of defining the URL conf for you.
Let's take our current set of views, and refactor them into view sets.
First of all let's refactor our UserList and UserDetail classes into a single UserViewSet class. In the snippets/views.py file, we can remove the two view classes and replace them with a single ViewSet class:
from rest_framework import viewsets\n\n\nclass UserViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n This viewset automatically provides `list` and `retrieve` actions.\n \"\"\"\n\n queryset = User.objects.all()\n serializer_class = UserSerializer\n Here we've used the ReadOnlyModelViewSet class to automatically provide the default 'read-only' operations. We're still setting the queryset and serializer_class attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.
Next we're going to replace the SnippetList, SnippetDetail and SnippetHighlight view classes. We can remove the three views, and again replace them with a single class.
from rest_framework import permissions\nfrom rest_framework import renderers\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\n\n\nclass SnippetViewSet(viewsets.ModelViewSet):\n \"\"\"\n This ViewSet automatically provides `list`, `create`, `retrieve`,\n `update` and `destroy` actions.\n\n Additionally we also provide an extra `highlight` action.\n \"\"\"\n\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]\n\n @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])\n def highlight(self, request, *args, **kwargs):\n snippet = self.get_object()\n return Response(snippet.highlighted)\n\n def perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n This time we've used the ModelViewSet class in order to get the complete set of default read and write operations.
Notice that we've also used the @action decorator to create a custom action, named highlight. This decorator can be used to add any custom endpoints that don't fit into the standard create/update/delete style.
Custom actions which use the @action decorator will respond to GET requests by default. We can use the methods argument if we wanted an action that responded to POST requests.
The URLs for custom actions by default depend on the method name itself. If you want to change the way url should be constructed, you can include url_path as a decorator keyword argument.
The handler methods only get bound to the actions when we define the URLConf. To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.
In the snippets/urls.py file we bind our ViewSet classes into a set of concrete views.
from rest_framework import renderers\n\nfrom snippets.views import api_root, SnippetViewSet, UserViewSet\n\nsnippet_list = SnippetViewSet.as_view({\"get\": \"list\", \"post\": \"create\"})\nsnippet_detail = SnippetViewSet.as_view(\n {\"get\": \"retrieve\", \"put\": \"update\", \"patch\": \"partial_update\", \"delete\": \"destroy\"}\n)\nsnippet_highlight = SnippetViewSet.as_view(\n {\"get\": \"highlight\"}, renderer_classes=[renderers.StaticHTMLRenderer]\n)\nuser_list = UserViewSet.as_view({\"get\": \"list\"})\nuser_detail = UserViewSet.as_view({\"get\": \"retrieve\"})\n Notice how we're creating multiple views from each ViewSet class, by binding the HTTP methods to the required action for each view.
Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.
urlpatterns = format_suffix_patterns(\n [\n path(\"\", api_root),\n path(\"snippets/\", snippet_list, name=\"snippet-list\"),\n path(\"snippets/<int:pk>/\", snippet_detail, name=\"snippet-detail\"),\n path(\n \"snippets/<int:pk>/highlight/\", snippet_highlight, name=\"snippet-highlight\"\n ),\n path(\"users/\", user_list, name=\"user-list\"),\n path(\"users/<int:pk>/\", user_detail, name=\"user-detail\"),\n ]\n)\n"},{"location":"tutorial/6-viewsets-and-routers/#using-routers","title":"Using Routers","text":"Because we're using ViewSet classes rather than View classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a Router class. All we need to do is register the appropriate view sets with a router, and let it do the rest.
Here's our re-wired snippets/urls.py file.
from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n\nfrom snippets import views\n\n# Create a router and register our ViewSets with it.\nrouter = DefaultRouter()\nrouter.register(r\"snippets\", views.SnippetViewSet, basename=\"snippet\")\nrouter.register(r\"users\", views.UserViewSet, basename=\"user\")\n\n# The API URLs are now determined automatically by the router.\nurlpatterns = [\n path(\"\", include(router.urls)),\n]\n Registering the ViewSets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the view set itself.
The DefaultRouter class we're using also automatically creates the API root view for us, so we can now delete the api_root function from our views module.
Using ViewSets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function-based views. Using ViewSets is less explicit than building your API views individually.
"},{"location":"tutorial/quickstart/","title":"Quickstart","text":"We're going to create a simple API to allow admin users to view and edit the users and groups in the system.
"},{"location":"tutorial/quickstart/#project-setup","title":"Project setup","text":"Create a new Django project named tutorial, then start a new app called quickstart.
# Create the project directory\nmkdir tutorial\ncd tutorial\n\n# Create a virtual environment to isolate our package dependencies locally\npython3 -m venv .venv\nsource .venv/bin/activate\n\n# Install Django and Django REST framework into the virtual environment\npip install djangorestframework\n\n# Set up a new project with a single application\ndjango-admin startproject tutorial . # Note the trailing '.' character\ncd tutorial\ndjango-admin startapp quickstart\ncd ..\n If you use Bash for Windows
# Create the project directory\nmkdir tutorial\ncd tutorial\n\n# Create a virtual environment to isolate our package dependencies locally\npython3 -m venv .venv\nsource .venv\\Scripts\\activate\n\n# Install Django and Django REST framework into the virtual environment\npip install djangorestframework\n\n# Set up a new project with a single application\ndjango-admin startproject tutorial . # Note the trailing '.' character\ncd tutorial\ndjango-admin startapp quickstart\ncd ..\n The project layout should look like:
$ pwd\n<some path>/tutorial\n$ find .\n.\n./tutorial\n./tutorial/asgi.py\n./tutorial/__init__.py\n./tutorial/quickstart\n./tutorial/quickstart/migrations\n./tutorial/quickstart/migrations/__init__.py\n./tutorial/quickstart/models.py\n./tutorial/quickstart/__init__.py\n./tutorial/quickstart/apps.py\n./tutorial/quickstart/admin.py\n./tutorial/quickstart/tests.py\n./tutorial/quickstart/views.py\n./tutorial/settings.py\n./tutorial/urls.py\n./tutorial/wsgi.py\n./env\n./env/...\n./manage.py\n It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).
Now sync your database for the first time:
python manage.py migrate\n We'll also create an initial user named admin with a password. We'll authenticate as that user later in our example.
python manage.py createsuperuser --username admin --email admin@example.com\n Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...
"},{"location":"tutorial/quickstart/#serializers","title":"Serializers","text":"First up we're going to define some serializers. Let's create a new module named tutorial/quickstart/serializers.py that we'll use for our data representations.
from django.contrib.auth.models import Group, User\nfrom rest_framework import serializers\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = [\"url\", \"username\", \"email\", \"groups\"]\n\n\nclass GroupSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Group\n fields = [\"url\", \"name\"]\n Notice that we're using hyperlinked relations in this case with HyperlinkedModelSerializer. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
Right, we'd better write some views then. Open tutorial/quickstart/views.py and get typing.
from django.contrib.auth.models import Group, User\nfrom rest_framework import permissions, viewsets\n\nfrom tutorial.quickstart.serializers import GroupSerializer, UserSerializer\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n\n queryset = User.objects.all().order_by(\"-date_joined\")\n serializer_class = UserSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n\nclass GroupViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows groups to be viewed or edited.\n \"\"\"\n\n queryset = Group.objects.all().order_by(\"name\")\n serializer_class = GroupSerializer\n permission_classes = [permissions.IsAuthenticated]\n Rather than write multiple views we're grouping together all the common behavior into classes called ViewSets.
We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.
"},{"location":"tutorial/quickstart/#urls","title":"URLs","text":"Okay, now let's wire up the API URLs. On to tutorial/urls.py...
from django.urls import include, path\nfrom rest_framework import routers\n\nfrom tutorial.quickstart import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r\"users\", views.UserViewSet)\nrouter.register(r\"groups\", views.GroupViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n path(\"\", include(router.urls)),\n path(\"api-auth/\", include(\"rest_framework.urls\", namespace=\"rest_framework\")),\n]\n Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.
Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
"},{"location":"tutorial/quickstart/#pagination","title":"Pagination","text":"Pagination allows you to control how many objects per page are returned. To enable it add the following lines to tutorial/settings.py
REST_FRAMEWORK = {\n \"DEFAULT_PAGINATION_CLASS\": \"rest_framework.pagination.PageNumberPagination\",\n \"PAGE_SIZE\": 10,\n}\n"},{"location":"tutorial/quickstart/#settings","title":"Settings","text":"Add 'rest_framework' to INSTALLED_APPS. The settings module will be in tutorial/settings.py
INSTALLED_APPS = [\n ...\n 'rest_framework',\n]\n Okay, we're done.
"},{"location":"tutorial/quickstart/#testing-our-api","title":"Testing our API","text":"We're now ready to test the API we've built. Let's fire up the server from the command line.
python manage.py runserver\n We can now access our API, both from the command-line, using tools like curl...
bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/\nEnter host password for user 'admin':\n{\n \"count\": 1,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"url\": \"http://127.0.0.1:8000/users/1/\",\n \"username\": \"admin\",\n \"email\": \"admin@example.com\",\n \"groups\": []\n }\n ]\n}\n Or using the httpie, command line tool...
bash: http -a admin http://127.0.0.1:8000/users/\nhttp: password for admin@127.0.0.1:8000:: \n$HTTP/1.1 200 OK\n...\n{\n \"count\": 1,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://127.0.0.1:8000/users/1/\",\n \"username\": \"admin\"\n }\n ]\n}\n Or directly through the browser, by going to the URL http://127.0.0.1:8000/users/...
If you're working through the browser, make sure to login using the control in the top right corner.
Great, that was easy!
If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial, or start browsing the API guide.
"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"","title":"Home","text":"Django REST FrameworkDjango REST framework is a powerful and flexible toolkit for building Web APIs.
Some reasons you might want to use REST framework:
REST framework requires the following:
We highly recommend and only officially support the latest patch release of each Python and Django series.
The following packages are optional:
Install using pip, including any optional packages you want...
pip install djangorestframework\npip install markdown # Markdown support for the browsable API.\npip install django-filter # Filtering support\n ...or clone the project from github.
git clone https://github.com/encode/django-rest-framework\n Add 'rest_framework' to your INSTALLED_APPS setting.
INSTALLED_APPS = [\n # ...\n \"rest_framework\",\n]\n 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 = [\n # ...\n path(\"api-auth/\", include(\"rest_framework.urls\"))\n]\n Note that the URL path can be whatever you want.
"},{"location":"#example","title":"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 = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n \"DEFAULT_PERMISSION_CLASSES\": [\n \"rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly\"\n ]\n}\n 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.urls import path, include\nfrom django.contrib.auth.models import User\nfrom rest_framework import routers, serializers, viewsets\n\n\n# Serializers define the API representation.\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = [\"url\", \"username\", \"email\", \"is_staff\"]\n\n\n# ViewSets define the view behavior.\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\n# Routers provide an easy way of automatically determining the URL conf.\nrouter = routers.DefaultRouter()\nrouter.register(r\"users\", UserViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n path(\"\", include(router.urls)),\n path(\"api-auth/\", include(\"rest_framework.urls\", namespace=\"rest_framework\")),\n]\n 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.
"},{"location":"#quickstart","title":"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.
"},{"location":"#development","title":"Development","text":"See the Contribution guidelines for information on how to clone the repository, run the test suite and help maintain the code base of REST Framework.
"},{"location":"#support","title":"Support","text":"For support please see the REST framework discussion group, try the #restframework channel on irc.libera.chat, or raise a question on Stack Overflow, making sure to include the 'django-rest-framework' tag.
Please report security issues by emailing security@encode.io.
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
"},{"location":"#license","title":"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.
"},{"location":"api-guide/authentication/","title":"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 several authentication schemes out of the box, and also allows you to implement custom schemes.
Authentication always runs 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 set up the permission policies for your API please see the permissions documentation.
"},{"location":"api-guide/authentication/#how-authentication-is-determined","title":"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.
The default authentication schemes may be set globally, using the DEFAULT_AUTHENTICATION_CLASSES setting. For example.
REST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n ]\n}\n 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\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n authentication_classes = [SessionAuthentication, BasicAuthentication]\n permission_classes = [IsAuthenticated]\n\n def get(self, request, format=None):\n content = {\n 'user': str(request.user), # `django.contrib.auth.User` instance.\n 'auth': str(request.auth), # None\n }\n return Response(content)\n Or, if you're using the @api_view decorator with function based views.
@api_view(['GET'])\n@authentication_classes([SessionAuthentication, BasicAuthentication])\n@permission_classes([IsAuthenticated])\ndef example_view(request, format=None):\n content = {\n 'user': str(request.user), # `django.contrib.auth.User` instance.\n 'auth': str(request.auth), # None\n }\n return Response(content)\n"},{"location":"api-guide/authentication/#unauthorized-and-forbidden-responses","title":"Unauthorized and Forbidden responses","text":"When an unauthenticated request is denied permission there are two different error codes that may be appropriate.
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.
LoginRequiredMiddleware","text":"If you're running Django 5.1+ and use the LoginRequiredMiddleware, please note that all views from DRF are opted-out of this middleware. This is because the authentication in DRF is based on authentication and permissions classes, which may be determined after the middleware has been applied. Additionally, when the request is not authenticated, the middleware redirects the user to the login page, which is not suitable for API requests, where it's preferable to return a 401 status code.
REST framework offers an equivalent mechanism for DRF views via the global settings, DEFAULT_AUTHENTICATION_CLASSES and DEFAULT_PERMISSION_CLASSES. They should be changed accordingly if you need to enforce that API requests are logged in.
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\nWSGIPassAuthorization On\n"},{"location":"api-guide/authentication/#api-reference","title":"API Reference","text":""},{"location":"api-guide/authentication/#basicauthentication","title":"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\"\n 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.
Note
The token authentication provided by Django REST framework is a fairly simple implementation.
For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the Django REST Knox third party package.
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 = [\n ...\n 'rest_framework.authtoken'\n]\n 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\n\ntoken = Token.objects.create(user=...)\nprint(token.key)\n 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\n 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\n 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'\n Note
If you use TokenAuthentication in production you must ensure that your API is only available over https.
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\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom rest_framework.authtoken.models import Token\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n 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\nfrom rest_framework.authtoken.models import Token\n\nfor user in User.objects.all():\n Token.objects.get_or_create(user=user)\n"},{"location":"api-guide/authentication/#by-exposing-an-api-endpoint","title":"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\nurlpatterns += [\n path('api-token-auth/', views.obtain_auth_token)\n]\n 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' }\n 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\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\n\nclass CustomAuthToken(ObtainAuthToken):\n\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data,\n context={'request': request})\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data['user']\n token, created = Token.objects.get_or_create(user=user)\n return Response({\n 'token': token.key,\n 'user_id': user.pk,\n 'email': user.email\n })\n And in your urls.py:
urlpatterns += [\n path('api-token-auth/', CustomAuthToken.as_view())\n]\n"},{"location":"api-guide/authentication/#with-django-admin","title":"With Django admin","text":"It is also possible to create Tokens manually through the 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\n\nTokenAdmin.raw_id_fields = ['user']\n"},{"location":"api-guide/authentication/#using-django-managepy-command","title":"Using Django manage.py command","text":"Since version 3.6.4 it's possible to generate a user token using the following command:
./manage.py drf_create_token <username>\n this command will return the API token for the given user, creating it if it doesn't exist:
Generated token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b for user user1\n 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 <username>\n"},{"location":"api-guide/authentication/#sessionauthentication","title":"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 from 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 behavior is not suitable for login views, which should always have CSRF validation applied.
"},{"location":"api-guide/authentication/#remoteuserauthentication","title":"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 behavior, 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, for example:
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:
None. Any other authentication schemes also in use will still be checked.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.
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\nfrom rest_framework import authentication\nfrom rest_framework import exceptions\n\nclass ExampleAuthentication(authentication.BaseAuthentication):\n def authenticate(self, request):\n username = request.META.get('HTTP_X_USERNAME')\n if not username:\n return None\n\n try:\n user = User.objects.get(username=username)\n except User.DoesNotExist:\n raise exceptions.AuthenticationFailed('No such user')\n\n return (user, None)\n"},{"location":"api-guide/authentication/#third-party-packages","title":"Third party packages","text":"The following third-party packages are also available.
"},{"location":"api-guide/authentication/#django-rest-knox","title":"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).
"},{"location":"api-guide/authentication/#django-oauth-toolkit","title":"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 jazzband and uses the excellent OAuthLib. The package is well documented, and well supported and is currently our recommended package for OAuth 2.0 support.
"},{"location":"api-guide/authentication/#installation-configuration","title":"Installation & configuration","text":"Install using pip.
pip install django-oauth-toolkit\n Add the package to your INSTALLED_APPS and modify your REST framework settings.
INSTALLED_APPS = [\n ...\n 'oauth2_provider',\n]\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',\n ]\n}\n For more details see the Django REST framework - Getting started documentation.
"},{"location":"api-guide/authentication/#django-rest-framework-oauth","title":"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 the REST framework but is now supported and maintained as a third-party package.
"},{"location":"api-guide/authentication/#installation-configuration_1","title":"Installation & configuration","text":"Install the package using pip.
pip install djangorestframework-oauth\n For details on configuration and usage see the Django REST framework OAuth documentation for authentication and permissions.
"},{"location":"api-guide/authentication/#json-web-token-authentication","title":"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.
"},{"location":"api-guide/authentication/#hawk-http-authentication","title":"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).
"},{"location":"api-guide/authentication/#http-signature-authentication","title":"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.
"},{"location":"api-guide/authentication/#djoser","title":"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 uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
"},{"location":"api-guide/authentication/#drf-auth-kit","title":"DRF Auth Kit","text":"DRF Auth Kit library provides a modern REST authentication solution with JWT cookies, social login, multi-factor authentication, and comprehensive user management. The package offers full type safety, automatic OpenAPI schema generation with DRF Spectacular. It supports multiple authentication types (JWT, DRF Token, or Custom) and includes built-in internationalization for 50+ languages.
"},{"location":"api-guide/authentication/#django-rest-auth-dj-rest-auth","title":"django-rest-auth / dj-rest-auth","text":"This 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.
There are currently two forks of this project.
Drf-social-oauth2 is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup.
"},{"location":"api-guide/authentication/#drfpasswordless","title":"drfpasswordless","text":"drfpasswordless adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
"},{"location":"api-guide/authentication/#django-rest-authemail","title":"django-rest-authemail","text":"django-rest-authemail provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included.
"},{"location":"api-guide/authentication/#django-rest-durin","title":"Django-Rest-Durin","text":"Django-Rest-Durin is built with the idea to have one library that does token auth for multiple Web/CLI/Mobile API clients via one interface but allows different token configuration for each API Client that consumes the API. It provides support for multiple tokens per user via custom models, views, permissions that work with Django-Rest-Framework. The token expiration time can be different per API client and is customizable via the Django Admin Interface.
More information can be found in the Documentation.
"},{"location":"api-guide/authentication/#django-pyoidc","title":"django-pyoidc","text":"django_pyoidc adds support for OpenID Connect (OIDC) authentication. This allows you to delegate user management to an Identity Provider, which can be used to implement Single-Sign-On (SSO). It provides support for most uses-cases, such as customizing how token info are mapped to user models, using OIDC audiences for access control, etc.
More information can be found in the Documentation.
"},{"location":"api-guide/caching/","title":"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.
"},{"location":"api-guide/caching/#using-cache-with-apiview-and-viewsets","title":"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, vary_on_cookie and vary_on_headers.
from django.utils.decorators import method_decorator\nfrom django.views.decorators.cache import cache_page\nfrom django.views.decorators.vary import vary_on_cookie, vary_on_headers\n\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework import viewsets\n\n\nclass UserViewSet(viewsets.ViewSet):\n # With cookie: cache requested url for each user for 2 hours\n @method_decorator(cache_page(60 * 60 * 2))\n @method_decorator(vary_on_cookie)\n def list(self, request, format=None):\n content = {\n \"user_feed\": request.user.get_user_feed(),\n }\n return Response(content)\n\n\nclass ProfileView(APIView):\n # With auth: cache requested url for each user for 2 hours\n @method_decorator(cache_page(60 * 60 * 2))\n @method_decorator(vary_on_headers(\"Authorization\"))\n def get(self, request, format=None):\n content = {\n \"user_feed\": request.user.get_user_feed(),\n }\n return Response(content)\n\n\nclass PostView(APIView):\n # Cache page for the requested url\n @method_decorator(cache_page(60 * 60 * 2))\n def get(self, request, format=None):\n content = {\n \"title\": \"Post title\",\n \"body\": \"Post content\",\n }\n return Response(content)\n"},{"location":"api-guide/caching/#using-cache-with-api_view-decorator","title":"Using cache with @api_view decorator","text":"When using @api_view decorator, the Django-provided method-based cache decorators such as cache_page, vary_on_cookie and vary_on_headers can be called directly.
from django.views.decorators.cache import cache_page\nfrom django.views.decorators.vary import vary_on_cookie\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\n\n@cache_page(60 * 15)\n@vary_on_cookie\n@api_view([\"GET\"])\ndef get_user_list(request):\n content = {\"user_feed\": request.user.get_user_feed()}\n return Response(content)\n Note
The cache_page decorator only caches the GET and HEAD responses with status 200.
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.
"},{"location":"api-guide/content-negotiation/#determining-the-accepted-renderer","title":"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.
For example, given the following Accept header:
application/json; indent=4, application/json, application/yaml, text/html, */*\n The priorities for each of the given media types would be:
application/json; indent=4application/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.
"},{"location":"api-guide/content-negotiation/#custom-content-negotiation","title":"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.
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\n\nclass IgnoreClientContentNegotiation(BaseContentNegotiation):\n def select_parser(self, request, parsers):\n \"\"\"\n Select the first parser in the `.parser_classes` list.\n \"\"\"\n return parsers[0]\n\n def select_renderer(self, request, renderers, format_suffix):\n \"\"\"\n Select the first renderer in the `.renderer_classes` list.\n \"\"\"\n return (renderers[0], renderers[0].media_type)\n"},{"location":"api-guide/content-negotiation/#setting-the-content-negotiation","title":"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 = {\n 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation',\n}\n 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\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass NoNegotiationView(APIView):\n \"\"\"\n An example view that does not perform content negotiation.\n \"\"\"\n content_negotiation_class = IgnoreClientContentNegotiation\n\n def get(self, request, format=None):\n return Response({\n 'accepted media type': request.accepted_renderer.media_type\n })\n"},{"location":"api-guide/exceptions/","title":"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
"},{"location":"api-guide/exceptions/#exception-handling-in-rest-framework-views","title":"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:
APIException raised inside REST framework.Http404 exception.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\nAccept: application/json\n Might receive an error response indicating that the DELETE method is not allowed on that resource:
HTTP/1.1 405 Method Not Allowed\nContent-Type: application/json\nContent-Length: 42\n\n{\"detail\": \"Method 'DELETE' not allowed.\"}\n 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.
An example validation error might look like this:
HTTP/1.1 400 Bad Request\nContent-Type: application/json\nContent-Length: 94\n\n{\"amount\": [\"A valid integer is required.\"], \"description\": [\"This field may not be blank.\"]}\n"},{"location":"api-guide/exceptions/#custom-exception-handling","title":"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\nContent-Type: application/json\nContent-Length: 62\n\n{\"status_code\": 405, \"detail\": \"Method 'DELETE' not allowed.\"}\n In order to alter the style of the response, you could write the following custom exception handler:
from rest_framework.views import exception_handler\n\ndef custom_exception_handler(exc, context):\n # Call REST framework's default exception handler first,\n # to get the standard error response.\n response = exception_handler(exc, context)\n\n #\u00a0Now add the HTTP status code to the response.\n if response is not None:\n response.data['status_code'] = response.status_code\n\n return response\n 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 = {\n 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'\n}\n If not specified, the 'EXCEPTION_HANDLER' setting defaults to the standard exception handler provided by REST framework:
REST_FRAMEWORK = {\n 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'\n}\n 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.
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\n\nclass ServiceUnavailable(APIException):\n status_code = 503\n default_detail = 'Service temporarily unavailable, try again later.'\n default_code = 'service_unavailable'\n"},{"location":"api-guide/exceptions/#inspecting-api-exceptions","title":"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)\nYou do not have permission to perform this action.\n>>> print(exc.get_codes())\npermission_denied\n>>> print(exc.get_full_details())\n{'message':'You do not have permission to perform this action.','code':'permission_denied'}\n In the case of validation errors the error detail will be either a list or dictionary of items:
>>> print(exc.detail)\n{\"name\":\"This field is required.\",\"age\":\"A valid integer is required.\"}\n>>> print(exc.get_codes())\n{\"name\":\"required\",\"age\":\"invalid\"}\n>>> print(exc.get_full_details())\n{\"name\":{\"message\":\"This field is required.\",\"code\":\"required\"},\"age\":{\"message\":\"A valid integer is required.\",\"code\":\"invalid\"}}\n"},{"location":"api-guide/exceptions/#parseerror","title":"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\".
"},{"location":"api-guide/exceptions/#authenticationfailed","title":"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.
"},{"location":"api-guide/exceptions/#notauthenticated","title":"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.
"},{"location":"api-guide/exceptions/#permissiondenied","title":"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\".
"},{"location":"api-guide/exceptions/#notfound","title":"NotFound","text":"Signature: NotFound(detail=None, code=None)
Raised when a resource does not exist 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\".
"},{"location":"api-guide/exceptions/#methodnotallowed","title":"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\".
"},{"location":"api-guide/exceptions/#notacceptable","title":"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\".
"},{"location":"api-guide/exceptions/#unsupportedmediatype","title":"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\".
"},{"location":"api-guide/exceptions/#throttled","title":"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\".
"},{"location":"api-guide/exceptions/#validationerror","title":"ValidationError","text":"Signature: ValidationError(detail=None, code=None)
The ValidationError exception is slightly different from the other APIException classes:
detail argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the validate() method of a serializer. For example. raise serializers.ValidationError({'name': 'Please enter a valid name.'})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)\n 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\".
"},{"location":"api-guide/exceptions/#generic-error-views","title":"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.
"},{"location":"api-guide/exceptions/#rest_frameworkexceptionsserver_error","title":"rest_framework.exceptions.server_error","text":"Returns a response with status code 500 and application/json content type.
Set as handler500:
handler500 = 'rest_framework.exceptions.server_error'\n"},{"location":"api-guide/exceptions/#rest_frameworkexceptionsbad_request","title":"rest_framework.exceptions.bad_request","text":"Returns a response with status code 400 and application/json content type.
Set as handler400:
handler400 = 'rest_framework.exceptions.bad_request'\n"},{"location":"api-guide/exceptions/#third-party-packages","title":"Third party packages","text":"The following third-party packages are also available.
"},{"location":"api-guide/exceptions/#drf-standardized-errors","title":"DRF Standardized Errors","text":"The drf-standardized-errors package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.
"},{"location":"api-guide/fields/","title":"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.<FieldName>.
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:
"},{"location":"api-guide/fields/#read_only","title":"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
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
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. If you're using Model Serializer, the default value will be False when you have specified a default, or when the corresponding Model field has blank=True or null=True and is not part of a unique constraint at the same time. (Note that without a default value, unique constraints will cause the field to be required.)
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 behavior 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 requires_context = True attribute, then the serializer field will be passed as an argument.
For example:
class CurrentUserDefault:\n \"\"\"\n May be applied as a `default=...` value on a serializer field.\n Returns the current user.\n \"\"\"\n requires_context = True\n\n def __call__(self, serializer_field):\n return serializer_field.context['request'].user\n When serializing the instance, default will be used if 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","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
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. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example:
class CommentSerializer(serializers.Serializer):\n email = serializers.EmailField(source=\"user.email\")\n This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using prefetch_related and select_related methods appropriately. For more information about the methods refer to django documentation.
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.
"},{"location":"api-guide/fields/#validators","title":"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.
error_messages","text":"A dictionary of error codes to error messages.
"},{"location":"api-guide/fields/#label","title":"label","text":"A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
"},{"location":"api-guide/fields/#help_text","title":"help_text","text":"A text string that may be used as a description of the field in HTML form fields or other descriptive elements.
"},{"location":"api-guide/fields/#initial","title":"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\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n day = serializers.DateField(initial=datetime.date.today)\n"},{"location":"api-guide/fields/#style","title":"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 <input type=\"password\"> for the input.\npassword = serializers.CharField(\n style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'green', 'blue'],\n style={'base_template': 'radio.html'}\n)\n For more details see the HTML & Forms documentation.
"},{"location":"api-guide/fields/#boolean-fields","title":"Boolean fields","text":""},{"location":"api-guide/fields/#booleanfield","title":"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 behavior 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()
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.
A text representation, validates the text to be a valid email address.
Corresponds to django.db.models.fields.EmailField
Signature: EmailField(max_length=None, min_length=None, allow_blank=False)
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.
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)
A RegexField that validates the input against a URL matching pattern. Expects fully qualified URLs of the form http://<host>/<path>.
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)
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\"\n 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_valueA 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.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'.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.A biginteger representation.
Corresponds to django.db.models.fields.BigIntegerField.
Signature: BigIntegerField(max_value=None, min_value=None, coerce_to_string=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.coerce_to_string Set to True if string values should be returned for the representation, or False if BigInteger objects should be returned. Defaults to the same value as the COERCE_BIGINT_TO_STRING settings key, which will be False unless overridden. If BigInteger objects are returned by the serializer, then the final output format will be determined by the renderer.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.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. Should be an integer or Decimal object.min_value Validate that the number provided is no less than this value. Should be an integer or Decimal object.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 quantizing to the configured precision. Valid values are decimal module rounding modes. Defaults to None.normalize_output Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without losing data. Defaults to False.To validate numbers up to 999 with a resolution of 2 decimal places, you would use:
serializers.DecimalField(max_digits=5, decimal_places=2)\n 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)\n"},{"location":"api-guide/fields/#date-and-time-fields","title":"Date and time fields","text":""},{"location":"api-guide/fields/#datetimefield","title":"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 tzinfo subclass (zoneinfo or pytz) 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.","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 be determined by the renderer class.
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):\n created = serializers.DateTimeField()\n\n class Meta:\n model = Comment\n"},{"location":"api-guide/fields/#datefield","title":"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'].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')
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","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')
A Duration representation. Corresponds to django.db.models.fields.DurationField
The validated_data for these fields will contain a datetime.timedelta instance.
Signature: DurationField(format=api_settings.DURATION_FORMAT, max_value=None, min_value=None)
format - A string representing the output format. If not specified, this defaults to the same value as the DURATION_FORMAT settings key, which will be 'django' unless set. Formats are described below. Setting this value to None indicates that Python timedelta objects should be returned by to_representation. In this case the date encoding will be determined by the renderer.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.DurationField formats","text":"Format may either be the special string 'iso-8601', which indicates that ISO 8601 style intervals should be used (eg 'P4DT1H15M20S'), or 'django' which indicates that Django interval format '[DD] [HH:[MM:]]ss[.uuuuuu]' should be used (eg: '4 1:15:20').
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.
A field that can accept a list of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. to_internal_value returns a list containing the selected values, deduplicated.
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.
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.
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.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.
A field class that validates a list of objects.
Signature: ListField(child=<A_FIELD_INSTANCE>, 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(\n child=serializers.IntegerField(min_value=0, max_value=100)\n)\n The ListField class also supports a declarative style that allows you to write reusable list field classes.
class StringListField(serializers.ListField):\n child = serializers.CharField()\n We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it.
A field class that validates a dictionary of objects. The keys in DictField are always assumed to be string values.
Signature: DictField(child=<A_FIELD_INSTANCE>, 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())\n You can also use the declarative style, as with ListField. For example:
class DocumentField(DictField):\n child = CharField()\n"},{"location":"api-guide/fields/#hstorefield","title":"HStoreField","text":"A preconfigured DictField that is compatible with Django's postgres HStoreField.
Signature: HStoreField(child=<A_FIELD_INSTANCE>, 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.
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.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):\n class Meta:\n model = Account\n fields = ['id', 'account_name', 'has_expired']\n"},{"location":"api-guide/fields/#hiddenfield","title":"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)\n 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.
Note
HiddenField() does not appear in partial=True serializer (when making PATCH request).
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=<Django ModelField instance>)
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'))
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_<field_name>.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\nfrom django.utils.timezone import now\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.ModelSerializer):\n days_since_joined = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n fields = '__all__'\n\n def get_days_since_joined(self, obj):\n return (now() - obj.date_joined).days\n"},{"location":"api-guide/fields/#custom-fields","title":"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.
Let's look at an example of serializing a class that represents an RGB color value:
class Color:\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red >= 0 and green >= 0 and blue >= 0)\n assert(red < 256 and green < 256 and blue < 256)\n self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n \"\"\"\n Color objects are serialized into 'rgb(#, #, #)' notation.\n \"\"\"\n def to_representation(self, value):\n return \"rgb(%d, %d, %d)\" % (value.red, value.green, value.blue)\n\n def to_internal_value(self, data):\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n return Color(red, green, blue)\n 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):\n def get_attribute(self, instance):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return instance\n\n def to_representation(self, value):\n \"\"\"\n Serialize the value's class name.\n \"\"\"\n return value.__class__.__name__\n"},{"location":"api-guide/fields/#raising-validation-errors","title":"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):\n if not isinstance(data, str):\n msg = 'Incorrect type. Expected a string, but got %s'\n raise ValidationError(msg % type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col > 255 or col < 0 for col in (red, green, blue)]):\n raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n return Color(red, green, blue)\n The .fail() method is a shortcut for raising ValidationError that takes a message string from the error_messages dictionary. For example:
default_error_messages = {\n 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n 'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n if not isinstance(data, str):\n self.fail('incorrect_type', input_type=type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n self.fail('incorrect_format')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col > 255 or col < 0 for col in (red, green, blue)]):\n self.fail('out_of_range')\n\n return Color(red, green, blue)\n This style keeps your error messages cleaner and more separated from your code, and should be preferred.
"},{"location":"api-guide/fields/#using-source","title":"Usingsource='*'","text":"Here we'll take an example of a flat DataPoint model with x_coordinate and y_coordinate attributes.
class DataPoint(models.Model):\n label = models.CharField(max_length=50)\n x_coordinate = models.SmallIntegerField()\n y_coordinate = models.SmallIntegerField()\n Using a custom field and source='*' we can provide a nested representation of the coordinate pair:
class CoordinateField(serializers.Field):\n\n def to_representation(self, value):\n ret = {\n \"x\": value.x_coordinate,\n \"y\": value.y_coordinate\n }\n return ret\n\n def to_internal_value(self, data):\n ret = {\n \"x_coordinate\": data[\"x\"],\n \"y_coordinate\": data[\"y\"],\n }\n return ret\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = CoordinateField(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates']\n 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 serializer 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)\n>>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})])\n 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 = {\n... \"label\": \"Second Example\",\n... \"coordinates\": {\n... \"x\": 3,\n... \"y\": 4,\n... }\n... }\n>>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'Second Example'),\n ('y_coordinate', 4),\n ('x_coordinate', 3)])\n For completeness let's do the same thing again but with the nested serializer approach suggested above:
class NestedCoordinateSerializer(serializers.Serializer):\n x = serializers.IntegerField(source='x_coordinate')\n y = serializers.IntegerField(source='y_coordinate')\n\n\nclass DataPointSerializer(serializers.ModelSerializer):\n coordinates = NestedCoordinateSerializer(source='*')\n\n class Meta:\n model = DataPoint\n fields = ['label', 'coordinates']\n 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 behavior as the custom field approach.
Serializing:
>>> out_serializer = DataPointSerializer(instance)\n>>> out_serializer.data\nReturnDict([('label', 'testing'),\n ('coordinates', OrderedDict([('x', 1), ('y', 2)]))])\n Deserializing:
>>> in_serializer = DataPointSerializer(data=data)\n>>> in_serializer.is_valid()\nTrue\n>>> in_serializer.validated_data\nOrderedDict([('label', 'still testing'),\n ('x_coordinate', 3),\n ('y_coordinate', 4)])\n But we also get the built-in validation for free:
>>> invalid_data = {\n... \"label\": \"still testing\",\n... \"coordinates\": {\n... \"x\": 'a',\n... \"y\": 'b',\n... }\n... }\n>>> invalid_serializer = DataPointSerializer(data=invalid_data)\n>>> invalid_serializer.is_valid()\nFalse\n>>> invalid_serializer.errors\nReturnDict([('coordinates',\n {'x': ['A valid integer is required.'],\n 'y': ['A valid integer is required.']})])\n For this reason, the nested serializer approach would be the first to try. You would use the custom field approach when the nested serializer becomes infeasible or overly complex.
"},{"location":"api-guide/fields/#third-party-packages","title":"Third party packages","text":"The following third party packages are also available.
"},{"location":"api-guide/fields/#drf-compound-fields","title":"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.
The drf-extra-fields package provides extra serializer fields for REST framework, including Base64ImageField and PointField classes.
the djangorestframework-recursive package provides a RecursiveField for serializing and deserializing recursive structures
The django-rest-framework-gis package provides geographic addons for django rest framework like a GeometryField field and a GeoJSON serializer.
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.
"},{"location":"api-guide/filtering/#filtering-against-the-current-user","title":"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\nfrom myapp.serializers import PurchaseSerializer\nfrom rest_framework import generics\n\nclass PurchaseList(generics.ListAPIView):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the purchases\n for the currently authenticated user.\n \"\"\"\n user = self.request.user\n return Purchase.objects.filter(purchaser=user)\n"},{"location":"api-guide/filtering/#filtering-against-the-url","title":"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:
re_path('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),\n You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
class PurchaseList(generics.ListAPIView):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the purchases for\n the user as determined by the username portion of the URL.\n \"\"\"\n username = self.kwargs['username']\n return Purchase.objects.filter(purchaser__username=username)\n"},{"location":"api-guide/filtering/#filtering-against-query-parameters","title":"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):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n Optionally restricts the returned purchases to a given user,\n by filtering against a `username` query parameter in the URL.\n \"\"\"\n queryset = Purchase.objects.all()\n username = self.request.query_params.get('username')\n if username is not None:\n queryset = queryset.filter(purchaser__username=username)\n return queryset\n"},{"location":"api-guide/filtering/#generic-filtering","title":"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.
"},{"location":"api-guide/filtering/#setting-filter-backends","title":"Setting filter backends","text":"The default filter backends may be set globally, using the DEFAULT_FILTER_BACKENDS setting. For example.
REST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']\n}\n 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\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import generics\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = [django_filters.rest_framework.DjangoFilterBackend]\n"},{"location":"api-guide/filtering/#filtering-and-object-lookups","title":"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\n"},{"location":"api-guide/filtering/#overriding-the-initial-queryset","title":"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):\n \"\"\"\n Return a list of all the products that the authenticated\n user has ever purchased, with optional filtering.\n \"\"\"\n model = Product\n serializer_class = ProductSerializer\n filterset_class = ProductFilter\n\n def get_queryset(self):\n user = self.request.user\n return user.purchase_set.all()\n"},{"location":"api-guide/filtering/#api-guide","title":"API Guide","text":""},{"location":"api-guide/filtering/#djangofilterbackend","title":"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.
pip install django-filter\n Then add 'django_filters' to Django's INSTALLED_APPS:
INSTALLED_APPS = [\n ...\n 'django_filters',\n ...\n]\n You should now either add the filter backend to your settings:
REST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']\n}\n Or add the filter backend to an individual View or ViewSet.
from django_filters.rest_framework import DjangoFilterBackend\n\nclass UserListView(generics.ListAPIView):\n ...\n filter_backends = [DjangoFilterBackend]\n 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):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n filter_backends = [DjangoFilterBackend]\n filterset_fields = ['category', 'in_stock']\n 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\n For more advanced filtering requirements you can specify a FilterSet class that should be used by the view. You can read more about FilterSets in the django-filter documentation. It's also recommended that you read the section on DRF integration.
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\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = [filters.SearchFilter]\n search_fields = ['username', 'email']\n This will allow the client to filter the items in the list by making queries such as:
http://example.com/api/users?search=russell\n 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']\n For JSONField and HStoreField fields you can filter based on nested values within the data structure using the same double-underscore notation:
search_fields = ['data__breed', 'data__owner__other_pets__0__name']\n 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. Searches may contain quoted phrases with spaces, each phrase is considered as a single search term.
The search behavior may be specified by prefixing field names in search_fields with one of the following characters (which is equivalent to adding __<lookup> to the field):
^ istartswith Starts-with search. = iexact Exact matches. $ iregex Regex search. @ search Full-text search (Currently only supported Django's PostgreSQL backend). None icontains Contains search (Default). For example:
search_fields = ['=username', '=email']\n By default, the search parameter is named 'search', but this may be overridden with the SEARCH_PARAM setting in the REST_FRAMEWORK configuration.
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\n\nclass CustomSearchFilter(filters.SearchFilter):\n def get_search_fields(self, view, request):\n if request.query_params.get('title_only'):\n return ['title']\n return super().get_search_fields(view, request)\n For more details, see the Django documentation.
"},{"location":"api-guide/filtering/#orderingfilter","title":"OrderingFilter","text":"The OrderingFilter class supports simple query parameter controlled ordering of results.
By default, the query parameter is named 'ordering', but this may be overridden with the ORDERING_PARAM setting in the REST_FRAMEWORK configuration.
For example, to order users by username:
http://example.com/api/users?ordering=username\n The client may also specify reverse orderings by prefixing the field name with '-', like so:
http://example.com/api/users?ordering=-username\n Multiple orderings may also be specified:
http://example.com/api/users?ordering=account,username\n"},{"location":"api-guide/filtering/#specifying-which-fields-may-be-ordered-against","title":"Specifying which fields may be ordered against","text":"It's recommended that you explicitly specify which fields the API should allow in the ordering filter. You can do this by setting an ordering_fields attribute on the view, like so:
class UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = [filters.OrderingFilter]\n ordering_fields = ['username', 'email']\n 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):\n queryset = Booking.objects.all()\n serializer_class = BookingSerializer\n filter_backends = [filters.OrderingFilter]\n ordering_fields = '__all__'\n"},{"location":"api-guide/filtering/#specifying-a-default-ordering","title":"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):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = [filters.OrderingFilter]\n ordering_fields = ['username', 'email']\n ordering = ['username']\n The ordering attribute may be either a string or a list/tuple of strings.
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.
"},{"location":"api-guide/filtering/#example","title":"Example","text":"For example, you might need to restrict users to only being able to see objects they created.
class IsOwnerFilterBackend(filters.BaseFilterBackend):\n \"\"\"\n Filter that only allows users to see their own objects.\n \"\"\"\n def filter_queryset(self, request, queryset, view):\n return queryset.filter(owner=request.user)\n 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.
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.
"},{"location":"api-guide/filtering/#third-party-packages","title":"Third party packages","text":"The following third party packages provide additional filter implementations.
"},{"location":"api-guide/filtering/#django-rest-framework-filters-package","title":"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.
The djangorestframework-word-filter developed as alternative to filters.SearchFilter which will search full word in text, or exact match.
django-url-filter provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django QuerySets.
drf-url-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.
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.
"},{"location":"api-guide/format-suffixes/#format_suffix_patterns","title":"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:
False, meaning that suffixes are optional by default.Example:
from rest_framework.urlpatterns import format_suffix_patterns\nfrom blog import views\n\nurlpatterns = [\n path('', views.apt_root),\n path('comments/', views.comment_list),\n path('comments/<int:pk>/', views.comment_detail)\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])\n 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'])\ndef comment_list(request, format=None):\n # do stuff...\n Or with class-based views:
class CommentList(APIView):\n def get(self, request, format=None):\n # do stuff...\n\n def post(self, request, format=None):\n # do stuff...\n 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.
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:
urlpatterns = [\n \u2026\n]\n\nurlpatterns = i18n_patterns(\n format_suffix_patterns(urlpatterns, allowed=['json', 'html'])\n)\n"},{"location":"api-guide/format-suffixes/#query-parameter-formats","title":"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.
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.
"},{"location":"api-guide/generic-views/","title":"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.
Typically when using the generic views, you'll override the view, and set several class attributes.
from django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import generics\nfrom rest_framework.permissions import IsAdminUser\n\nclass UserList(generics.ListCreateAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = [IsAdminUser]\n For more complex cases you might also want to override various methods on the view class. For example.
class UserList(generics.ListCreateAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = [IsAdminUser]\n\n def list(self, request):\n # Note the use of `get_queryset()` instead of `self.queryset`\n queryset = self.get_queryset()\n serializer = UserSerializer(queryset, many=True)\n return Response(serializer.data)\n For very simple cases you might want to pass through any class attributes using the .as_view() method. For example, your URLconf might include something like the following entry:
path('users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')\n"},{"location":"api-guide/generic-views/#api-reference","title":"API Reference","text":""},{"location":"api-guide/generic-views/#genericapiview","title":"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.
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 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.Base methods:
"},{"location":"api-guide/generic-views/#get_querysetself","title":"get_queryset(self)","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):\n user = self.request.user\n return user.accounts.all()\n Tip
If the serializer_class used in the generic view spans ORM relations, leading to an N+1 problem, you could optimize your queryset in this method using select_related and prefetch_related. To get more information about N+1 problem and use cases of the mentioned methods refer to related section in django documentation.
When listing objects (e.g. using ListAPIView or ModelViewSet), serializers may trigger an N+1 query pattern if related objects are accessed individually for each item.
To prevent this, optimize the queryset in get_queryset() or by setting the queryset class attribute using select_related() and prefetch_related(), depending on the type of relationship.
For ForeignKey and OneToOneField:
Use select_related() to fetch related objects in the same query:
def get_queryset(self):\n return Order.objects.select_related(\"customer\", \"billing_address\")\n For reverse and many-to-many relationships:
Use prefetch_related() to efficiently load collections of related objects:
def get_queryset(self):\n return Book.objects.prefetch_related(\"categories\", \"reviews__user\")\n Combining both:
def get_queryset(self):\n return (\n Order.objects\n .select_related(\"customer\")\n .prefetch_related(\"items__product\")\n )\n These optimizations reduce repeated database access and improve list view performance.
"},{"location":"api-guide/generic-views/#get_objectself","title":"get_object(self)","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):\n queryset = self.get_queryset()\n filter = {}\n for field in self.multiple_lookup_fields:\n filter[field] = self.kwargs[field]\n\n obj = get_object_or_404(queryset, **filter)\n self.check_object_permissions(self.request, obj)\n return obj\n 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)","text":"Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
For example:
def filter_queryset(self, queryset):\n filter_backends = [CategoryFilter]\n\n if 'geo_route' in self.request.query_params:\n filter_backends = [GeoRouteFilter, CategoryFilter]\n elif 'geo_point' in self.request.query_params:\n filter_backends = [GeoPointFilter, CategoryFilter]\n\n for backend in list(filter_backends):\n queryset = backend().filter_queryset(self.request, queryset, view=self)\n\n return queryset\n"},{"location":"api-guide/generic-views/#get_serializer_classself","title":"get_serializer_class(self)","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):\n if self.request.user.is_staff:\n return FullAccountSerializer\n return BasicAccountSerializer\n 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):\n serializer.save(user=self.request.user)\n 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):\n instance = serializer.save()\n send_email_confirmation(user=self.request.user, modified=instance)\n 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):\n queryset = SignupRequest.objects.filter(user=self.request.user)\n if queryset.exists():\n raise ValidationError('You have already signed up')\n serializer.save(user=self.request.user)\n 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.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.
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.
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.
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.
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.
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.
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.
Used for create-only endpoints.
Provides a post method handler.
Extends: GenericAPIView, CreateModelMixin
"},{"location":"api-guide/generic-views/#listapiview","title":"ListAPIView","text":"Used for read-only endpoints to represent a collection of model instances.
Provides a get method handler.
Extends: GenericAPIView, ListModelMixin
"},{"location":"api-guide/generic-views/#retrieveapiview","title":"RetrieveAPIView","text":"Used for read-only endpoints to represent a single model instance.
Provides a get method handler.
Extends: GenericAPIView, RetrieveModelMixin
"},{"location":"api-guide/generic-views/#destroyapiview","title":"DestroyAPIView","text":"Used for delete-only endpoints for a single model instance.
Provides a delete method handler.
Extends: GenericAPIView, DestroyModelMixin
"},{"location":"api-guide/generic-views/#updateapiview","title":"UpdateAPIView","text":"Used for update-only endpoints for a single model instance.
Provides put and patch method handlers.
Extends: GenericAPIView, UpdateModelMixin
"},{"location":"api-guide/generic-views/#listcreateapiview","title":"ListCreateAPIView","text":"Used for read-write endpoints to represent a collection of model instances.
Provides get and post method handlers.
Extends: GenericAPIView, ListModelMixin, CreateModelMixin
"},{"location":"api-guide/generic-views/#retrieveupdateapiview","title":"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
"},{"location":"api-guide/generic-views/#retrievedestroyapiview","title":"RetrieveDestroyAPIView","text":"Used for read or delete endpoints to represent a single model instance.
Provides get and delete method handlers.
Extends: GenericAPIView, RetrieveModelMixin, DestroyModelMixin
"},{"location":"api-guide/generic-views/#retrieveupdatedestroyapiview","title":"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
"},{"location":"api-guide/generic-views/#customizing-the-generic-views","title":"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.
"},{"location":"api-guide/generic-views/#creating-custom-mixins","title":"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:\n \"\"\"\n Apply this mixin to any view or viewset to get multiple field filtering\n based on a `lookup_fields` attribute, instead of the default single field filtering.\n \"\"\"\n def get_object(self):\n queryset = self.get_queryset() # Get the base queryset\n queryset = self.filter_queryset(queryset) # Apply any filter backends\n filter = {}\n for field in self.lookup_fields:\n if self.kwargs.get(field): # Ignore empty fields.\n filter[field] = self.kwargs[field]\n obj = get_object_or_404(queryset, **filter) # Lookup the object\n self.check_object_permissions(self.request, obj)\n return obj\n 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):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n lookup_fields = ['account', 'username']\n Using custom mixins is a good option if you have custom behavior that needs to be used.
"},{"location":"api-guide/generic-views/#creating-custom-base-classes","title":"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,\n generics.RetrieveAPIView):\n pass\n\nclass BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,\n generics.RetrieveUpdateDestroyAPIView):\n pass\n 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.
"},{"location":"api-guide/generic-views/#put-as-create","title":"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.
The following third party packages provide additional generic view implementations.
"},{"location":"api-guide/generic-views/#django-rest-multiple-models","title":"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.
"},{"location":"api-guide/metadata/","title":"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\nAllow: GET, POST, HEAD, OPTIONS\nContent-Type: application/json\n\n{\n \"name\": \"To Do List\",\n \"description\": \"List existing 'To Do' items, or create a new item.\",\n \"renders\": [\n \"application/json\",\n \"text/html\"\n ],\n \"parses\": [\n \"application/json\",\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\"\n ],\n \"actions\": {\n \"POST\": {\n \"note\": {\n \"type\": \"string\",\n \"required\": false,\n \"read_only\": false,\n \"label\": \"title\",\n \"max_length\": 100\n }\n }\n }\n}\n"},{"location":"api-guide/metadata/#setting-the-metadata-scheme","title":"Setting the metadata scheme","text":"You can set the metadata class globally using the 'DEFAULT_METADATA_CLASS' settings key:
REST_FRAMEWORK = {\n 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata'\n}\n Or you can set the metadata class individually for a view:
class APIRoot(APIView):\n metadata_class = APIRootMetadata\n\n def get(self, request, format=None):\n return Response({\n ...\n })\n 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.
If you have specific requirements for creating schema endpoints that are accessed with regular GET requests, you might consider reusing 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)\ndef api_schema(self, request):\n meta = self.metadata_class()\n data = meta.determine_metadata(request, self)\n return Response(data)\n There are a couple of reasons that you might choose to take this approach, including that OPTIONS responses are not cacheable.
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.
"},{"location":"api-guide/metadata/#example","title":"Example","text":"The following class could be used to limit the information that is returned to OPTIONS requests.
class MinimalMetadata(BaseMetadata):\n \"\"\"\n Don't include field and other information for `OPTIONS` requests.\n Just return the name and description.\n \"\"\"\n def determine_metadata(self, request, view):\n return {\n 'name': view.get_view_name(),\n 'description': view.get_view_description()\n }\n Then configure your settings to use this custom class:
REST_FRAMEWORK = {\n 'DEFAULT_METADATA_CLASS': 'myproject.apps.core.MinimalMetadata'\n}\n"},{"location":"api-guide/metadata/#third-party-packages","title":"Third party packages","text":"The following third party packages provide additional metadata implementations.
"},{"location":"api-guide/metadata/#drf-schema-adapter","title":"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.
"},{"location":"api-guide/pagination/","title":"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:
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.
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 = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',\n 'PAGE_SIZE': 100\n}\n 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.
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):\n page_size = 1000\n page_size_query_param = 'page_size'\n max_page_size = 10000\n\nclass StandardResultsSetPagination(PageNumberPagination):\n page_size = 100\n page_size_query_param = 'page_size'\n max_page_size = 1000\n You can then apply your new style to a view using the pagination_class attribute:
class BillingRecordsView(generics.ListAPIView):\n queryset = Billing.objects.all()\n serializer_class = BillingRecordsSerializer\n pagination_class = LargeResultsSetPagination\n Or apply the style globally, using the DEFAULT_PAGINATION_CLASS settings key. For example:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination'\n}\n"},{"location":"api-guide/pagination/#api-reference","title":"API Reference","text":""},{"location":"api-guide/pagination/#pagenumberpagination","title":"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\n Response:
HTTP 200 OK\n{\n \"count\": 1023,\n \"next\": \"https://api.example.org/accounts/?page=5\",\n \"previous\": \"https://api.example.org/accounts/?page=3\",\n \"results\": [\n \u2026\n ]\n}\n"},{"location":"api-guide/pagination/#setup","title":"Setup","text":"To enable the PageNumberPagination style globally, use the following configuration, and set the PAGE_SIZE as desired:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n}\n On GenericAPIView subclasses you may also set the pagination_class attribute to select PageNumberPagination on a per-view basis.
By default, the query parameter name used for pagination is page. This can be customized by subclassing PageNumberPagination and overriding the page_query_param attribute.
For example:
from rest_framework.pagination import PageNumberPagination\n\nclass CustomPagination(PageNumberPagination):\n page_query_param = 'p'\n With this configuration, clients would request pages using ?p=2 instead of ?page=2.
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',). For example, use ?page=last to go directly to the last page.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\".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\n Response:
HTTP 200 OK\n{\n \"count\": 1023,\n \"next\": \"https://api.example.org/accounts/?limit=100&offset=500\",\n \"previous\": \"https://api.example.org/accounts/?limit=100&offset=300\",\n \"results\": [\n \u2026\n ]\n}\n"},{"location":"api-guide/pagination/#setup_1","title":"Setup","text":"To enable the LimitOffsetPagination style globally, use the following configuration:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'\n}\n 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.
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\".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:
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.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:
CursorPagination subclass that uses decimals to limit precision is available here.)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.
"},{"location":"api-guide/pagination/#setup_2","title":"Setup","text":"To enable the CursorPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',\n 'PAGE_SIZE': 100\n}\n On GenericAPIView subclasses you may also set the pagination_class attribute to select CursorPagination on a per-view basis.
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\".To create a custom pagination serializer class, you should inherit the subclass pagination.BasePagination, override the paginate_queryset(self, queryset, request, view=None), and get_paginated_response(self, data) methods:
paginate_queryset method is passed to the initial queryset and should return an iterable object. That object contains only the data in the requested page.get_paginated_response method is passed to 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.
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):\n def get_paginated_response(self, data):\n return Response({\n 'links': {\n 'next': self.get_next_link(),\n 'previous': self.get_previous_link()\n },\n 'count': self.page.paginator.count,\n 'results': data\n })\n We'd then need to set up the custom class in our configuration:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination',\n 'PAGE_SIZE': 100\n}\n 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.
To have your custom pagination class be used by default, use the DEFAULT_PAGINATION_CLASS setting:
REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',\n 'PAGE_SIZE': 100\n}\n 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
"},{"location":"api-guide/pagination/#html-pagination-controls","title":"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.
You can override the templates that render the HTML pagination controls. The two built-in styles are:
rest_framework/pagination/numbers.htmlrest_framework/pagination/previous_and_next.htmlProviding 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.
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.
The following third party packages are also available.
"},{"location":"api-guide/pagination/#drf-extensions","title":"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.
The drf-proxy-pagination package includes a ProxyPagination class which allows to choose pagination class with a query parameter.
The django-rest-framework-link-header-pagination package includes a LinkHeaderPagination class which provides pagination via an HTTP Link header as described in GitHub REST API documentation.
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.
"},{"location":"api-guide/parsers/#how-the-parser-is-determined","title":"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 want.
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.
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 = {\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework.parsers.JSONParser',\n ]\n}\n 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\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n \"\"\"\n A view that can accept POST requests with JSON content.\n \"\"\"\n parser_classes = [JSONParser]\n\n def post(self, request, format=None):\n return Response({'received data': request.data})\n Or, if you're using the @api_view decorator with function based views.
from rest_framework.decorators import api_view\nfrom rest_framework.decorators import parser_classes\nfrom rest_framework.parsers import JSONParser\n\n@api_view(['POST'])\n@parser_classes([JSONParser])\ndef example_view(request, format=None):\n \"\"\"\n A view that can accept POST requests with JSON content.\n \"\"\"\n return Response({'received data': request.data})\n"},{"location":"api-guide/parsers/#api-reference","title":"API Reference","text":""},{"location":"api-guide/parsers/#jsonparser","title":"JSONParser","text":"Parses JSON request content. request.data will be populated with a dictionary of data.
.media_type: application/json
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
Parses multipart HTML form content, which supports file uploads. request.data and request.FILES will be populated with a QueryDict and MultiValueDict respectively.
You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data.
.media_type: multipart/form-data
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: */*
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.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.# views.py\nclass FileUploadView(views.APIView):\n parser_classes = [FileUploadParser]\n\n def put(self, request, filename, format=None):\n file_obj = request.data['file']\n # ...\n # do some stuff with uploaded file\n # ...\n return Response(status=204)\n\n# urls.py\nurlpatterns = [\n # ...\n re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())\n]\n"},{"location":"api-guide/parsers/#custom-parsers","title":"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:
A stream-like object representing the body of the request.
"},{"location":"api-guide/parsers/#media_type","title":"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\".
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.
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):\n \"\"\"\n Plain text parser.\n \"\"\"\n media_type = 'text/plain'\n\n def parse(self, stream, media_type=None, parser_context=None):\n \"\"\"\n Simply return a string representing the body of the request.\n \"\"\"\n return stream.read()\n"},{"location":"api-guide/parsers/#third-party-packages","title":"Third party packages","text":"The following third party packages are also available.
"},{"location":"api-guide/parsers/#yaml","title":"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.
"},{"location":"api-guide/parsers/#installation-configuration","title":"Installation & configuration","text":"Install using pip.
$ pip install djangorestframework-yaml\n Modify your REST framework settings.
REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework_yaml.parsers.YAMLParser',\n ],\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ],\n}\n"},{"location":"api-guide/parsers/#xml","title":"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.
"},{"location":"api-guide/parsers/#installation-configuration_1","title":"Installation & configuration","text":"Install using pip.
$ pip install djangorestframework-xml\n Modify your REST framework settings.
REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework_xml.parsers.XMLParser',\n ],\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework_xml.renderers.XMLRenderer',\n ],\n}\n"},{"location":"api-guide/parsers/#messagepack","title":"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.
"},{"location":"api-guide/parsers/#camelcase-json","title":"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.
"},{"location":"api-guide/permissions/","title":"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.
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 permission checks fail, either a \"403 Forbidden\" or a \"401 Unauthorized\" response will be returned, according to the following rules:
WWW-Authenticate headers. \u2014 An HTTP 403 Forbidden response will be returned.WWW-Authenticate headers. \u2014 An HTTP 401 Unauthorized response, with an appropriate WWW-Authenticate header will be returned.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):\n obj = get_object_or_404(self.get_queryset(), pk=self.kwargs[\"pk\"])\n self.check_object_permissions(self.request, obj)\n return obj\n 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).
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.
Because the get_object() method is not called, object level permissions from the has_object_permission() method are not applied when creating objects. In order to restrict object creation you need to implement the permission check either in your Serializer class or override the perform_create() method of your ViewSet class.
The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting. For example.
REST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.IsAuthenticated',\n ]\n}\n If not specified, this setting defaults to allowing unrestricted access:
'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.AllowAny',\n]\n 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\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n permission_classes = [IsAuthenticated]\n\n def get(self, request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n Or, if you're using the @api_view decorator with function based views.
from rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef example_view(request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n Note
When you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in 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\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ReadOnly(BasePermission):\n def has_permission(self, request, view):\n return request.method in SAFE_METHODS\n\nclass ExampleView(APIView):\n permission_classes = [IsAuthenticated | ReadOnly]\n\n def get(self, request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n Note
Composition of permissions supports the & (and), | (or) and ~ (not) operators, and also allows the use of brackets ( ) to group expressions.
Operators follow the same precedence and associativity rules as standard logical operators (~ highest, then &, then |).
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.
"},{"location":"api-guide/permissions/#isauthenticated","title":"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.
"},{"location":"api-guide/permissions/#isadminuser","title":"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.
"},{"location":"api-guide/permissions/#isauthenticatedorreadonly","title":"IsAuthenticatedOrReadOnly","text":"The IsAuthenticatedOrReadOnly will allow authenticated users to perform any request. Requests for unauthenticated 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.
"},{"location":"api-guide/permissions/#djangomodelpermissions","title":"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 or get_queryset() method. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned. The appropriate model is determined by checking get_queryset().model or queryset.model.
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 behavior 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.
Similar to DjangoModelPermissions, but also allows unauthenticated users to have read-only access to the API.
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.
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:\n # Check permissions for read-only request\nelse:\n # Check permissions for write request\n 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. Similarly, to change the code identifier associated with the exception, implement a code attribute directly on your custom permission - otherwise the default_code attribute from PermissionDenied will be used.
from rest_framework import permissions\n\nclass CustomerAccessPermission(permissions.BasePermission):\n message = 'Adding customers not allowed.'\n\n def has_permission(self, request, view):\n ...\n"},{"location":"api-guide/permissions/#examples","title":"Examples","text":"The following is an example of a permission class that checks the incoming request's IP address against a blocklist, and denies the request if the IP has been blocked.
from rest_framework import permissions\n\nclass BlocklistPermission(permissions.BasePermission):\n \"\"\"\n Global permission check for blocked IPs.\n \"\"\"\n\n def has_permission(self, request, view):\n ip_addr = request.META['REMOTE_ADDR']\n blocked = Blocklist.objects.filter(ip_addr=ip_addr).exists()\n return not blocked\n 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):\n \"\"\"\n Object-level permission to only allow owners of an object to edit it.\n Assumes the model instance has an `owner` attribute.\n \"\"\"\n\n def has_object_permission(self, request, view, obj):\n # Read permissions are allowed to any request,\n # so we'll always allow GET, HEAD or OPTIONS requests.\n if request.method in permissions.SAFE_METHODS:\n return True\n\n # Instance must have an attribute named `owner`.\n return obj.owner == request.user\n 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.
"},{"location":"api-guide/permissions/#overview-of-access-restriction-methods","title":"Overview of access restriction methods","text":"REST framework offers three different methods to customize access restrictions on a case-by-case basis. These apply in different scenarios and have different effects and limitations.
queryset/get_queryset(): Limits the general visibility of existing objects from the database. The queryset limits which objects will be listed and which objects can be modified or deleted. The get_queryset() method can apply different querysets based on the current action.permission_classes/get_permissions(): General permission checks based on the current action, request and targeted object. Object level permissions can only be applied to retrieve, modify and deletion actions. Permission checks for list and create will be applied to the entire object type. (In case of list: subject to restrictions in the queryset.)serializer_class/get_serializer(): Instance level restrictions that apply to all objects on input and output. The serializer may have access to the request context. The get_serializer() method can apply different serializers based on the current action.The following table lists the access restriction methods and the level of control they offer over which actions.
queryset permission_classes serializer_class Action: list global global object-level* Action: create no global object-level Action: retrieve global object-level object-level Action: update global object-level object-level Action: partial_update global object-level object-level Action: destroy global object-level no Can reference action in decision no** yes no** Can reference request in decision no** yes yes * A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned. ** The get_*() methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action.
The following third party packages are also available.
"},{"location":"api-guide/permissions/#drf-access-policy","title":"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.
"},{"location":"api-guide/permissions/#composed-permissions","title":"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.
"},{"location":"api-guide/permissions/#rest-condition","title":"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.
"},{"location":"api-guide/permissions/#dry-rest-permissions","title":"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.
"},{"location":"api-guide/permissions/#django-rest-framework-roles","title":"Django Rest Framework Roles","text":"The Django Rest Framework Roles package makes it easier to parameterize your API over multiple types of users.
"},{"location":"api-guide/permissions/#rest-framework-roles","title":"Rest Framework Roles","text":"The Rest Framework Roles makes it super easy to protect views based on roles. Most importantly allows you to decouple accessibility logic from models and views in a clean human-readable way.
"},{"location":"api-guide/permissions/#django-rest-framework-api-key","title":"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.
"},{"location":"api-guide/permissions/#django-rest-framework-role-filters","title":"Django Rest Framework Role Filters","text":"The Django Rest Framework Role Filters package provides simple filtering over multiple types of roles.
"},{"location":"api-guide/permissions/#django-rest-framework-psq","title":"Django Rest Framework PSQ","text":"The Django Rest Framework PSQ package is an extension that gives support for having action-based permission_classes, serializer_class, and queryset dependent on permission-based rules.
"},{"location":"api-guide/permissions/#axioms-drf-py","title":"Axioms DRF PY","text":"The Axioms DRF PY package is an extension that provides support for authentication and claim-based fine-grained authorization (scopes, roles, groups, permissions, etc. including object-level checks) using JWT tokens issued by an OAuth2/OIDC Authorization Server including AWS Cognito, Auth0, Okta, Microsoft Entra, etc.
"},{"location":"api-guide/relations/","title":"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.<FieldName>.
Note
REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of select_related and prefetch_related since it would be too much magic. A serializer with a field spanning an ORM relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
class AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.SlugRelatedField(\n many=True,\n read_only=True,\n slug_field='title'\n )\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n\n# For each album object, tracks should be fetched from database\nqs = Album.objects.all()\nprint(AlbumSerializer(qs, many=True).data)\n If AlbumSerializer is used to serialize a fairly large queryset with many=True then it could be a serious performance problem. Optimizing the queryset passed to AlbumSerializer with:
qs = Album.objects.prefetch_related('tracks')\n# No additional database hits required\nprint(AlbumSerializer(qs, many=True).data)\n would solve the issue.
"},{"location":"api-guide/relations/#inspecting-relationships","title":"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\n>>> serializer = AccountSerializer()\n>>> print(repr(serializer))\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n"},{"location":"api-guide/relations/#api-reference","title":"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):\n album_name = models.CharField(max_length=100)\n artist = models.CharField(max_length=100)\n\nclass Track(models.Model):\n album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)\n order = models.IntegerField()\n title = models.CharField(max_length=100)\n duration = models.IntegerField()\n\n class Meta:\n unique_together = ['album', 'order']\n ordering = ['order']\n\n def __str__(self):\n return '%d: %s' % (self.order, self.title)\n"},{"location":"api-guide/relations/#stringrelatedfield","title":"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):\n tracks = serializers.StringRelatedField(many=True)\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n Would serialize to the following representation:
{\n 'album_name': 'Things We Lost In The Fire',\n 'artist': 'Low',\n 'tracks': [\n '1: Sunflower',\n '2: Whitetail',\n '3: Dinosaur Act',\n ...\n ]\n}\n This field is read only.
Arguments:
many - If applied to a to-many relationship, you should set this argument to True.PrimaryKeyRelatedField may be used to represent the target of the relationship using its primary key.
For example, the following serializer:
class AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n Would serialize to a representation like this:
{\n 'album_name': 'Undun',\n 'artist': 'The Roots',\n 'tracks': [\n 89,\n 90,\n 91,\n ...\n ]\n}\n 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 may be used to represent the target of the relationship using a hyperlink.
For example, the following serializer:
class AlbumSerializer(serializers.ModelSerializer):\n tracks = serializers.HyperlinkedRelatedField(\n many=True,\n read_only=True,\n view_name='track-detail'\n )\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n Would serialize to a representation like this:
{\n 'album_name': 'Graceland',\n 'artist': 'Paul Simon',\n 'tracks': [\n 'http://www.example.com/api/tracks/45/',\n 'http://www.example.com/api/tracks/46/',\n 'http://www.example.com/api/tracks/47/',\n ...\n ]\n}\n 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 <modelname>-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 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):\n tracks = serializers.SlugRelatedField(\n many=True,\n read_only=True,\n slug_field='title'\n )\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n Would serialize to a representation like this:
{\n 'album_name': 'Dear John',\n 'artist': 'Loney Dear',\n 'tracks': [\n 'Airport Surroundings',\n 'Everything Turns to You',\n 'I Was Only Going Out',\n ...\n ]\n}\n 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. requiredqueryset - 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.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):\n track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'track_listing']\n Would serialize to a representation like this:
{\n 'album_name': 'The Eraser',\n 'artist': 'Thom Yorke',\n 'track_listing': 'http://www.example.com/api/track_list/12/',\n}\n 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 <model_name>-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.As opposed to previously discussed references to another entity, the referred entity can instead also be embedded or nested in the representation of the object that refers to it. Such 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.
For example, the following serializer:
class TrackSerializer(serializers.ModelSerializer):\n class Meta:\n model = Track\n fields = ['order', 'title', 'duration']\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackSerializer(many=True, read_only=True)\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n Would serialize to a nested representation like this:
>>> album = Album.objects.create(album_name=\"The Gray Album\", artist='Danger Mouse')\n>>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)\n<Track: Track object>\n>>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)\n<Track: Track object>\n>>> Track.objects.create(album=album, order=3, title='Encore', duration=159)\n<Track: Track object>\n>>> serializer = AlbumSerializer(instance=album)\n>>> serializer.data\n{\n 'album_name': 'The Gray Album',\n 'artist': 'Danger Mouse',\n 'tracks': [\n {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n {'order': 3, 'title': 'Encore', 'duration': 159},\n ...\n ],\n}\n"},{"location":"api-guide/relations/#writable-nested-serializers","title":"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):\n class Meta:\n model = Track\n fields = ['order', 'title', 'duration']\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackSerializer(many=True)\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n\n def create(self, validated_data):\n tracks_data = validated_data.pop('tracks')\n album = Album.objects.create(**validated_data)\n for track_data in tracks_data:\n Track.objects.create(album=album, **track_data)\n return album\n\n>>> data = {\n 'album_name': 'The Gray Album',\n 'artist': 'Danger Mouse',\n 'tracks': [\n {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},\n {'order': 2, 'title': 'What More Can I Say', 'duration': 264},\n {'order': 3, 'title': 'Encore', 'duration': 159},\n ],\n}\n>>> serializer = AlbumSerializer(data=data)\n>>> serializer.is_valid()\nTrue\n>>> serializer.save()\n<Album: Album object>\n"},{"location":"api-guide/relations/#custom-relational-fields","title":"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.
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\n\nclass TrackListingField(serializers.RelatedField):\n def to_representation(self, value):\n duration = time.strftime('%M:%S', time.gmtime(value.duration))\n return 'Track %d: %s (%s)' % (value.order, value.name, duration)\n\nclass AlbumSerializer(serializers.ModelSerializer):\n tracks = TrackListingField(many=True)\n\n class Meta:\n model = Album\n fields = ['album_name', 'artist', 'tracks']\n This custom field would then serialize to the following representation:
{\n 'album_name': 'Sometimes I Wish We Were an Eagle',\n 'artist': 'Bill Callahan',\n 'tracks': [\n 'Track 1: Jim Cain (04:39)',\n 'Track 2: Eid Ma Clack Shaw (04:19)',\n 'Track 3: The Wind and the Dove (04:34)',\n ...\n ]\n}\n"},{"location":"api-guide/relations/#custom-hyperlinked-fields","title":"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.
Say we have a URL for a customer object that takes two keyword arguments, like so:
/api/<organization_slug>/customers/<customer_pk>/\n 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\nfrom rest_framework.reverse import reverse\n\nclass CustomerHyperlink(serializers.HyperlinkedRelatedField):\n # We define these as class attributes, so we don't need to pass them as arguments.\n view_name = 'customer-detail'\n queryset = Customer.objects.all()\n\n def get_url(self, obj, view_name, request, format):\n url_kwargs = {\n 'organization_slug': obj.organization.slug,\n 'customer_pk': obj.pk\n }\n return reverse(view_name, kwargs=url_kwargs, request=request, format=format)\n\n def get_object(self, view_name, view_args, view_kwargs):\n lookup_kwargs = {\n 'organization__slug': view_kwargs['organization_slug'],\n 'pk': view_kwargs['customer_pk']\n }\n return self.get_queryset().get(**lookup_kwargs)\n 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.
"},{"location":"api-guide/relations/#further-notes","title":"Further notes","text":""},{"location":"api-guide/relations/#the-queryset-argument","title":"Thequeryset 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.
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):\n def display_value(self, instance):\n return 'Track: %s' % (instance.title)\n"},{"location":"api-guide/relations/#select-field-cutoffs","title":"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(\n queryset=User.objects.all(),\n slug_field='username',\n style={'base_template': 'input.html'}\n)\n"},{"location":"api-guide/relations/#reverse-relations","title":"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):\n class Meta:\n fields = ['tracks', ...]\n 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):\n album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)\n ...\n 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):\n class Meta:\n fields = ['track_set', ...]\n See the Django documentation on reverse relationships for more details.
"},{"location":"api-guide/relations/#generic-relationships","title":"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):\n \"\"\"\n Tags arbitrary model instances using a generic relation.\n\n See: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/\n \"\"\"\n tag_name = models.SlugField()\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n object_id = models.PositiveIntegerField()\n tagged_object = GenericForeignKey('content_type', 'object_id')\n\n def __str__(self):\n return self.tag_name\n And the following two models, which may have associated tags:
class Bookmark(models.Model):\n \"\"\"\n A bookmark consists of a URL, and 0 or more descriptive tags.\n \"\"\"\n url = models.URLField()\n tags = GenericRelation(TaggedItem)\n\n\nclass Note(models.Model):\n \"\"\"\n A note consists of some text, and 0 or more descriptive tags.\n \"\"\"\n text = models.CharField(max_length=1000)\n tags = GenericRelation(TaggedItem)\n 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):\n \"\"\"\n A custom field to use for the `tagged_object` generic relationship.\n \"\"\"\n\n def to_representation(self, value):\n \"\"\"\n Serialize tagged objects to a simple textual representation.\n \"\"\"\n if isinstance(value, Bookmark):\n return 'Bookmark: ' + value.url\n elif isinstance(value, Note):\n return 'Note: ' + value.text\n raise Exception('Unexpected type of tagged object')\n 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):\n \"\"\"\n Serialize bookmark instances using a bookmark serializer,\n and note instances using a note serializer.\n \"\"\"\n if isinstance(value, Bookmark):\n serializer = BookmarkSerializer(value)\n elif isinstance(value, Note):\n serializer = NoteSerializer(value)\n else:\n raise Exception('Unexpected type of tagged object')\n\n return serializer.data\n 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.
"},{"location":"api-guide/relations/#manytomanyfields-with-a-through-model","title":"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.
"},{"location":"api-guide/relations/#third-party-packages","title":"Third Party Packages","text":"The following third party packages are also available.
"},{"location":"api-guide/relations/#drf-nested-routers","title":"DRF Nested Routers","text":"The drf-nested-routers package provides routers and relationship fields for working with nested resources.
"},{"location":"api-guide/relations/#rest-framework-generic-relations","title":"Rest Framework Generic Relations","text":"The rest-framework-generic-relations library provides read/write serialization for generic foreign keys.
The rest-framework-gm2m-relations library provides read/write serialization for django-gm2m.
"},{"location":"api-guide/renderers/","title":"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.
"},{"location":"api-guide/renderers/#how-the-renderer-is-determined","title":"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.
"},{"location":"api-guide/renderers/#setting-the-renderers","title":"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 = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n ]\n}\n 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\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass UserCountView(APIView):\n \"\"\"\n A view that returns the count of active users in JSON.\n \"\"\"\n renderer_classes = [JSONRenderer]\n\n def get(self, request, format=None):\n user_count = User.objects.filter(active=True).count()\n content = {'user_count': user_count}\n return Response(content)\n Or, if you're using the @api_view decorator with function based views.
@api_view(['GET'])\n@renderer_classes([JSONRenderer])\ndef user_count_view(request, format=None):\n \"\"\"\n A view that returns the count of active users in JSON.\n \"\"\"\n user_count = User.objects.filter(active=True).count()\n content = {'user_count': user_count}\n return Response(content)\n"},{"location":"api-guide/renderers/#ordering-of-renderer-classes","title":"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.
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}\n 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.
{\n \"unicode black star\": \"\u2605\",\n \"value\": 999\n}\n 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
Renders data to HTML, using Django's standard template rendering. Unlike other renderers, the data passed to the Response does not need to be serialized. Also, unlike other renderers, you may want to include a template_name argument when creating the Response.
The TemplateHTMLRenderer will create a RequestContext, using the response.data as the context dict, and determine a template name to use to render the context.
Note
When used with a view that makes use of a serializer the Response sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
response.data = {'results': response.data}\n The template name is determined by (in order of preference):
template_name argument passed to the response..template_name attribute set on this class.view.get_template_names().An example of a view that uses TemplateHTMLRenderer:
class UserDetail(generics.RetrieveAPIView):\n \"\"\"\n A view that returns a templated HTML representation of a given user.\n \"\"\"\n queryset = User.objects.all()\n renderer_classes = [TemplateHTMLRenderer]\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n return Response({'user': self.object}, template_name='user_detail.html')\n 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 prioritized 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
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'])\n@renderer_classes([StaticHTMLRenderer])\ndef simple_html_view(request):\n data = '<html><body><h1>Hello, world</h1></body></html>'\n return Response(data)\n 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
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'
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):\n def get_default_renderer(self, view):\n return JSONRenderer()\n"},{"location":"api-guide/renderers/#adminrenderer","title":"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):\n url = serializers.CharField(source='get_absolute_url', read_only=True)\n\n class Meta:\n model = Account\n .media_type: text/html
.format: 'admin'
.charset: utf-8
.template: 'rest_framework/admin.html'
Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing <form> tags, a hidden CSRF input or any submit buttons.
This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the render_form template tag.
{% load rest_framework %}\n\n<form action=\"/submit-report/\" method=\"post\">\n {% csrf_token %}\n {% render_form serializer %}\n <input type=\"submit\" value=\"Save\" />\n</form>\n For more information see the HTML & Forms documentation.
.media_type: text/html
.format: 'form'
.charset: utf-8
.template: 'rest_framework/horizontal/form.html'
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
To implement a custom renderer, you should override BaseRenderer, set the .media_type and .format properties, and implement the .render(self, data, accepted_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","text":"The request data, as set by the Response() instantiation.
accepted_media_type=None","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\".
renderer_context=None","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.
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_str\nfrom rest_framework import renderers\n\n\nclass PlainTextRenderer(renderers.BaseRenderer):\n media_type = 'text/plain'\n format = 'txt'\n\n def render(self, data, accepted_media_type=None, renderer_context=None):\n return smart_str(data, encoding=self.charset)\n"},{"location":"api-guide/renderers/#setting-the-character-set","title":"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):\n media_type = 'text/plain'\n format = 'txt'\n charset = 'iso-8859-1'\n\n def render(self, data, accepted_media_type=None, renderer_context=None):\n return data.encode(self.charset)\n 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):\n media_type = 'image/jpeg'\n format = 'jpg'\n charset = None\n render_style = 'binary'\n\n def render(self, data, accepted_media_type=None, renderer_context=None):\n return data\n"},{"location":"api-guide/renderers/#advanced-renderer-usage","title":"Advanced renderer usage","text":"You can do some pretty flexible things using REST framework's renderers. Some examples...
media_type = 'image/*', and use the Accept header to vary the encoding of the response.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'])\n@renderer_classes([TemplateHTMLRenderer, JSONRenderer])\ndef list_users(request):\n \"\"\"\n A view that can return JSON or HTML representations\n of the users in the system.\n \"\"\"\n queryset = Users.objects.filter(active=True)\n\n if request.accepted_renderer.format == 'html':\n # TemplateHTMLRenderer takes a context dict,\n # and additionally requires a 'template_name'.\n # It does not require serialization.\n data = {'users': queryset}\n return Response(data, template_name='list_users.html')\n\n # JSONRenderer requires serialized data as normal.\n serializer = UserSerializer(instance=queryset)\n data = serializer.data\n return Response(data)\n"},{"location":"api-guide/renderers/#underspecifying-the-media-type","title":"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')\n"},{"location":"api-guide/renderers/#designing-your-media-types","title":"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.
"},{"location":"api-guide/renderers/#html-error-views","title":"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.
{status_code}.html.api_exception.html.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.
The following third party packages are also available.
"},{"location":"api-guide/renderers/#yaml","title":"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.
"},{"location":"api-guide/renderers/#installation-configuration","title":"Installation & configuration","text":"Install using pip.
$ pip install djangorestframework-yaml\n Modify your REST framework settings.
REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework_yaml.parsers.YAMLParser',\n ],\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ],\n}\n"},{"location":"api-guide/renderers/#xml","title":"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.
"},{"location":"api-guide/renderers/#installation-configuration_1","title":"Installation & configuration","text":"Install using pip.
$ pip install djangorestframework-xml\n Modify your REST framework settings.
REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework_xml.parsers.XMLParser',\n ],\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework_xml.renderers.XMLRenderer',\n ],\n}\n"},{"location":"api-guide/renderers/#jsonp","title":"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.
Install using pip.
$ pip install djangorestframework-jsonp\n Modify your REST framework settings.
REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework_jsonp.renderers.JSONPRenderer',\n ],\n}\n"},{"location":"api-guide/renderers/#messagepack","title":"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.
"},{"location":"api-guide/renderers/#microsoft-excel-xlsx-binary-spreadsheet-endpoints","title":"Microsoft Excel: XLSX (Binary Spreadsheet Endpoints)","text":"XLSX is the world's most popular binary spreadsheet format. Tim Allen of The Wharton School maintains drf-excel, 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.
"},{"location":"api-guide/renderers/#installation-configuration_3","title":"Installation & configuration","text":"Install using pip.
$ pip install drf-excel\n Modify your REST framework settings.
REST_FRAMEWORK = {\n ...\n\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n 'drf_excel.renderers.XLSXRenderer',\n ],\n}\n 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\nfrom drf_excel.mixins import XLSXFileMixin\nfrom drf_excel.renderers import XLSXRenderer\n\nfrom .models import MyExampleModel\nfrom .serializers import MyExampleSerializer\n\nclass MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):\n queryset = MyExampleModel.objects.all()\n serializer_class = MyExampleSerializer\n renderer_classes = [XLSXRenderer]\n filename = 'my_export.xlsx'\n"},{"location":"api-guide/renderers/#csv","title":"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.
"},{"location":"api-guide/renderers/#ultrajson","title":"UltraJSON","text":"UltraJSON is an optimized C JSON encoder which can give significantly faster JSON rendering. Adam Mertz maintains drf_ujson2, a fork of the now unmaintained drf-ujson-renderer, which implements JSON rendering using the UJSON package.
"},{"location":"api-guide/renderers/#camelcase-json","title":"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.
"},{"location":"api-guide/renderers/#pandas-csv-excel-png","title":"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.
Rest Framework Latex provides a renderer that outputs PDFs using Lualatex. It is maintained by Pebble (S/F Software).
"},{"location":"api-guide/requests/","title":"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.
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.
"},{"location":"api-guide/requests/#data","title":".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:
POST, meaning that you can access the content of PUT and PATCH requests.For more details see the parsers documentation.
"},{"location":"api-guide/requests/#query_params","title":".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.
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.
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types.
"},{"location":"api-guide/requests/#accepted_renderer","title":".accepted_renderer","text":"The renderer instance that was selected by the content negotiation stage.
"},{"location":"api-guide/requests/#accepted_media_type","title":".accepted_media_type","text":"A string representing the media type that was accepted by the content negotiation stage.
"},{"location":"api-guide/requests/#authentication","title":"Authentication","text":"REST framework provides flexible, per-request authentication, that gives you the ability to:
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.
"},{"location":"api-guide/requests/#auth","title":".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.
"},{"location":"api-guide/requests/#authenticators","title":".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.
REST framework supports a few browser enhancements such as browser-based PUT, PATCH and DELETE forms.
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.
"},{"location":"api-guide/requests/#content_type","title":".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.
"},{"location":"api-guide/requests/#stream","title":".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.
"},{"location":"api-guide/requests/#standard-httprequest-attributes","title":"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.
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 initialized 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.
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.The unrendered, serialized data of the response.
"},{"location":"api-guide/responses/#status_code","title":".status_code","text":"The numeric status code of the HTTP response.
"},{"location":"api-guide/responses/#content","title":".content","text":"The rendered content of the response. The .render() method must have been called before .content can be accessed.
The template_name, if supplied. Only required if HTMLRenderer or some other custom template renderer is the accepted renderer for the response.
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.
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.
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.
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()\nresponse['Cache-Control'] = 'no-cache'\n"},{"location":"api-guide/responses/#render","title":".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.
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:
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.
"},{"location":"api-guide/reverse/#reverse","title":"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\nfrom rest_framework.views import APIView\nfrom django.utils.timezone import now\n\nclass APIRootView(APIView):\n def get(self, request):\n year = now().year\n data = {\n ...\n 'year-summary-url': reverse('year-summary', args=[year], request=request)\n }\n return Response(data)\n"},{"location":"api-guide/reverse/#reverse_lazy","title":"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)\n"},{"location":"api-guide/routers/","title":"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.
"},{"location":"api-guide/routers/#usage","title":"Usage","text":"Here's an example of a simple URL conf, that uses SimpleRouter.
from rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\nurlpatterns = router.urls\n 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:
^users/$ Name: 'user-list'^users/{pk}/$ Name: 'user-detail'^accounts/$ Name: 'account-list'^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.\n 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.
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()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\n\nurlpatterns = [\n path('forgot-password/', ForgotPasswordFormView.as_view()),\n]\n\nurlpatterns += router.urls\n Alternatively you can use Django's include function, like so...
urlpatterns = [\n path('forgot-password', ForgotPasswordFormView.as_view()),\n path('', include(router.urls)),\n]\n You may use include with an application namespace:
urlpatterns = [\n path('forgot-password/', ForgotPasswordFormView.as_view()),\n path('api/', include((router.urls, 'app_name'))),\n]\n Or both an application and instance namespace:
urlpatterns = [\n path('forgot-password/', ForgotPasswordFormView.as_view()),\n path('api/', include((router.urls, 'app_name'), namespace='instance_name')),\n]\n 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.
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\nfrom rest_framework.decorators import action\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ...\n The following route would be generated:
^users/{pk}/set_password/$'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\nfrom rest_framework.decorators import action\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],\n url_path='change-password', url_name='change_password')\n def set_password(self, request, pk=None):\n ...\n The above example would now generate the following URL pattern:
^users/{pk}/change-password/$'user-change_password'path() with routers","text":"By default, the URLs created by routers use regular expressions. This behavior can be modified by setting the use_regex_path argument to False when instantiating the router, in this case path converters are used. For example:
router = SimpleRouter(use_regex_path=False)\n 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 or lookup_value_converter if using path converters. For example, you can limit the lookup to valid UUIDs:
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):\n lookup_field = 'my_model_id'\n lookup_value_regex = '[0-9a-f]{32}'\n\nclass MyPathModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):\n lookup_field = 'my_model_uuid'\n lookup_value_converter = 'uuid'\n Note that path converters will be used on all URLs registered in the router, including viewset actions.
"},{"location":"api-guide/routers/#api-guide","title":"API Guide","text":""},{"location":"api-guide/routers/#simplerouter","title":"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.
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)\n 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.
"},{"location":"api-guide/routers/#defaultrouter","title":"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.
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)\n"},{"location":"api-guide/routers/#custom-routers","title":"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.
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.
"},{"location":"api-guide/routers/#example","title":"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\n\nclass CustomReadOnlyRouter(SimpleRouter):\n \"\"\"\n A router for read-only APIs, which doesn't use trailing slashes.\n \"\"\"\n routes = [\n Route(\n url=r'^{prefix}$',\n mapping={'get': 'list'},\n name='{basename}-list',\n detail=False,\n initkwargs={'suffix': 'List'}\n ),\n Route(\n url=r'^{prefix}/{lookup}$',\n mapping={'get': 'retrieve'},\n name='{basename}-detail',\n detail=True,\n initkwargs={'suffix': 'Detail'}\n ),\n DynamicRoute(\n url=r'^{prefix}/{lookup}/{url_path}$',\n name='{basename}-{url_name}',\n detail=True,\n initkwargs={}\n )\n ]\n Let's take a look at the routes our CustomReadOnlyRouter would generate for a simple viewset.
views.py:
class UserViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n lookup_field = 'username'\n\n @action(detail=True)\n def group_names(self, request, pk=None):\n \"\"\"\n Returns a list of all the group names that the given\n user belongs to.\n \"\"\"\n user = self.get_object()\n groups = user.groups.all()\n return Response([group.name for group in groups])\n urls.py:
router = CustomReadOnlyRouter()\nrouter.register('users', UserViewSet)\nurlpatterns = router.urls\n The following mappings would be generated...
URLHTTP MethodActionURL Name /usersGETlistuser-list /users/{username}GETretrieveuser-detail /users/{username}/group_namesGETgroup_namesuser-group-namesFor another example of setting the .routes attribute, see the source code for the SimpleRouter class.
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.
The following third party packages are also available.
"},{"location":"api-guide/routers/#drf-nested-routers","title":"DRF Nested Routers","text":"The drf-nested-routers package provides routers and relationship fields for working with nested resources.
"},{"location":"api-guide/routers/#modelrouter-wqdbrest","title":"ModelRouter (wq.db.rest)","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\nfrom myapp.models import MyModel\n\nrest.router.register_model(MyModel)\n"},{"location":"api-guide/routers/#drf-extensions","title":"DRF-extensions","text":"The DRF-extensions package provides routers for creating nested viewsets, collection level controllers with customizable endpoint names.
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
Deprecation notice:
REST framework's built-in support for generating OpenAPI schemas is deprecated in favor of 3rd party packages that can provide this functionality instead. The built-in support will be moved into a separate package and then subsequently retired over the next releases.
As a full-fledged replacement, we recommend the drf-spectacular package. It has extensive support for generating OpenAPI 3 schemas from REST framework APIs, with both automatic and customizable options available. For further information please refer to Documenting your API.
API schemas are a useful tool that allow for a range of use cases, including generating reference documentation, or driving dynamic client libraries that can interact with your API.
Django REST Framework provides support for automatic generation of OpenAPI schemas.
"},{"location":"api-guide/schemas/#overview","title":"Overview","text":"Schema generation has several moving parts. It's worth having an overview:
SchemaGenerator is a top-level class that is responsible for walking your configured URL patterns, finding APIView subclasses, enquiring for their schema representation, and compiling the final schema object.AutoSchema encapsulates all the details necessary for per-view schema introspection. Is attached to each view via the schema attribute. You subclass AutoSchema in order to customize your schema.generateschema management command allows you to generate a static schema offline.SchemaView to dynamically generate and serve your schema.settings.DEFAULT_SCHEMA_CLASS allows you to specify an AutoSchema subclass to serve as your project's default.The following sections explain more.
"},{"location":"api-guide/schemas/#generating-an-openapi-schema","title":"Generating an OpenAPI Schema","text":""},{"location":"api-guide/schemas/#install-dependencies","title":"Install dependencies","text":"pip install pyyaml uritemplate inflection\n pyyaml is used to generate schema into YAML-based OpenAPI format.uritemplate is used internally to get parameters in path.inflection is used to pluralize operations more appropriately in the list endpoints.generateschema management command","text":"If your schema is static, you can use the generateschema management command:
./manage.py generateschema --file openapi-schema.yml\n 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.
"},{"location":"api-guide/schemas/#generating-a-dynamic-schema-with-schemaview","title":"Generating a dynamic schema withSchemaView","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\n\nurlpatterns = [\n # ...\n # Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.\n # * `title` and `description` parameters are passed to `SchemaGenerator`.\n # * Provide view name for use with `reverse()`.\n path(\n \"openapi\",\n get_schema_view(\n title=\"Your Project\", description=\"API for all things \u2026\", version=\"1.0.0\"\n ),\n name=\"openapi-schema\",\n ),\n # ...\n]\n"},{"location":"api-guide/schemas/#get_schema_view","title":"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.url: May be used to pass a canonical base URL for the schema.
schema_view = get_schema_view(\n title='Server Monitoring API',\n url='https://www.example.org/api/'\n)\n 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(\n title='Server Monitoring API',\n url='https://www.example.org/api/',\n urlconf='myproject.urls'\n)\n 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 = [\n path('api/', include('myproject.api.urls')),\n]\n\nschema_view = get_schema_view(\n title='Server Monitoring API',\n url='https://www.example.org/api/',\n patterns=schema_url_patterns,\n)\n public: May be used to specify if schema should bypass views permissions. Default to Falsegenerator_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_CLASSESpermission_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.Schema-level customization
from rest_framework.schemas.openapi import SchemaGenerator\n SchemaGenerator is a class that walks a list of routed URL patterns, requests the schema for each view and collates the resulting OpenAPI schema.
Typically you won't need to instantiate SchemaGenerator yourself, but you can do so like so:
generator = SchemaGenerator(title='Stock Prices API')\n Arguments:
title required: The name of the API.description: Longer descriptive text.version: The version of the API. Defaults to 0.1.0.url: The root URL of the API schema. This option is not required unless the schema is included under path prefix.patterns: A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.urlconf: A URL conf module name to use when generating the schema. Defaults to settings.ROOT_URLCONF.In order to customize the top-level schema, subclass rest_framework.schemas.openapi.SchemaGenerator and provide your subclass as an argument to the generateschema command or get_schema_view() helper function.
Returns a dictionary that represents the OpenAPI schema:
generator = SchemaGenerator(title='Stock Prices API')\nschema = generator.get_schema()\n The request argument is optional, and may be used if you want to apply per-user permissions to the resulting schema generation.
This is a good point to override if you want to customize the generated dictionary For example you might wish to add terms of service to the top-level info object:
class TOSSchemaGenerator(SchemaGenerator):\n def get_schema(self, *args, **kwargs):\n schema = super().get_schema(*args, **kwargs)\n schema[\"info\"][\"termsOfService\"] = \"https://example.com/tos.html\"\n return schema\n"},{"location":"api-guide/schemas/#autoschema","title":"AutoSchema","text":"Per-View Customization
from rest_framework.schemas.openapi import AutoSchema\n By default, view introspection is performed by an AutoSchema instance accessible via the schema attribute on APIView.
auto_schema = some_view.schema\n AutoSchema provides the OpenAPI elements needed for each view, request method and path:
components = auto_schema.get_components(...)\noperation = auto_schema.get_operation(...)\n In compiling the schema, SchemaGenerator calls get_components() and get_operation() for each view, allowed method, and path.
Note
The automatic introspection of components, and many operation parameters relies on the relevant attributes and methods of GenericAPIView: get_serializer(), pagination_class, filter_backends, etc. For basic APIView subclasses, default introspection is essentially limited to the URL kwarg path parameters for this reason.
AutoSchema encapsulates the view introspection needed for schema generation. Because of this all the schema generation logic is kept in a single place, rather than being spread around the already extensive view, serializer and field APIs.
Keeping with this pattern, try not to let schema logic leak into your own views, serializers, or fields when customizing the schema generation. You might be tempted to do something like this:
class CustomSchema(AutoSchema):\n \"\"\"\n AutoSchema subclass using schema_extra_info on the view.\n \"\"\"\n\n ...\n\n\nclass CustomView(APIView):\n schema = CustomSchema()\n schema_extra_info = ... # some extra info\n Here, the AutoSchema subclass goes looking for schema_extra_info on the view. This is OK (it doesn't actually hurt) but it means you'll end up with your schema logic spread out in a number of different places.
Instead try to subclass AutoSchema such that the extra_info doesn't leak out into the view:
class BaseSchema(AutoSchema):\n \"\"\"\n AutoSchema subclass that knows how to use extra_info.\n \"\"\"\n\n ...\n\n\nclass CustomSchema(BaseSchema):\n extra_info = ... # some extra info\n\n\nclass CustomView(APIView):\n schema = CustomSchema()\n This style is slightly more verbose but maintains the encapsulation of the schema related code. It's more cohesive in the parlance. It'll keep the rest of your API code more tidy.
If an option applies to many view classes, rather than creating a specific subclass per-view, you may find it more convenient to allow specifying the option as an __init__() kwarg to your base AutoSchema subclass:
class CustomSchema(BaseSchema):\n def __init__(self, **kwargs):\n # store extra_info for later\n self.extra_info = kwargs.pop(\"extra_info\")\n super().__init__(**kwargs)\n\n\nclass CustomView(APIView):\n schema = CustomSchema(extra_info=...) # some extra info\n This saves you having to create a custom subclass per-view for a commonly used option.
Not all AutoSchema methods expose related __init__() kwargs, but those for the more commonly needed options do.
AutoSchema methods","text":""},{"location":"api-guide/schemas/#get_components","title":"get_components()","text":"Generates the OpenAPI components that describe request and response bodies, deriving their properties from the serializer.
Returns a dictionary mapping the component name to the generated representation. By default this has just a single pair but you may override get_components() to return multiple pairs if your view uses multiple serializers.
get_component_name()","text":"Computes the component's name from the serializer.
You may see warnings if your API has duplicate component names. If so you can override get_component_name() or pass the component_name __init__() kwarg (see below) to provide different names.
get_reference()","text":"Returns a reference to the serializer component. This may be useful if you override get_schema().
map_serializer()","text":"Maps serializers to their OpenAPI representations.
Most serializers should conform to the standard OpenAPI object type, but you may wish to override map_serializer() in order to customize this or other serializer-level fields.
map_field()","text":"Maps individual serializer fields to their schema representation. The base implementation will handle the default fields that Django REST Framework provides.
For SerializerMethodField instances, for which the schema is unknown, or custom field subclasses you should override map_field() to generate the correct schema:
class CustomSchema(AutoSchema):\n \"\"\"Extension of ``AutoSchema`` to add support for custom field schemas.\"\"\"\n\n def map_field(self, field):\n # Handle SerializerMethodFields or custom fields here...\n # ...\n return super().map_field(field)\n Authors of third-party packages should aim to provide an AutoSchema subclass, and a mixin, overriding map_field() so that users can easily generate schemas for their custom fields.
get_tags()","text":"OpenAPI groups operations by tags. By default tags taken from the first path segment of the routed URL. For example, a URL like /users/{id}/ will generate the tag users.
You can pass an __init__() kwarg to manually specify tags (see below), or override get_tags() to provide custom logic.
get_operation()","text":"Returns the OpenAPI operation object that describes the endpoint, including path and query parameters for pagination, filtering, and so on.
Together with get_components(), this is the main entry point to the view introspection.
get_operation_id()","text":"There must be a unique operationid for each operation. By default the operationId is deduced from the model name, serializer name or view name. The operationId looks like \"listItems\", \"retrieveItem\", \"updateItem\", etc. The operationId is camelCase by convention.
get_operation_id_base()","text":"If you have several views with the same model name, you may see duplicate operationIds.
In order to work around this, you can override get_operation_id_base() to provide a different base for name part of the ID.
get_serializer()","text":"If the view has implemented get_serializer(), returns the result.
get_request_serializer()","text":"By default returns get_serializer() but can be overridden to differentiate between request and response objects.
get_response_serializer()","text":"By default returns get_serializer() but can be overridden to differentiate between request and response objects.
AutoSchema.__init__() kwargs","text":"AutoSchema provides a number of __init__() kwargs that can be used for common customizations, if the default generated values are not appropriate.
The available kwargs are:
tags: Specify a list of tags.component_name: Specify the component name.operation_id_base: Specify the resource-name part of operation IDs.You pass the kwargs when declaring the AutoSchema instance on your view:
class PetDetailView(generics.RetrieveUpdateDestroyAPIView):\n schema = AutoSchema(\n tags=['Pets'],\n component_name='Pet',\n operation_id_base='Pet',\n )\n ...\n Assuming a Pet model and PetSerializer serializer, the kwargs in this example are probably not needed. Often, though, you'll need to pass the kwargs if you have multiple view targeting the same model, or have multiple views with identically named serializers.
If your views have related customizations that are needed frequently, you can create a base AutoSchema subclass for your project that takes additional __init__() kwargs to save subclassing AutoSchema for each view.
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.
Let's start by creating a simple object we can use for example purposes:
from datetime import datetime\n\nclass Comment:\n def __init__(self, email, content, created=None):\n self.email = email\n self.content = content\n self.created = created or datetime.now()\n\ncomment = Comment(email='leila@example.com', content='foo bar')\n 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\n\nclass CommentSerializer(serializers.Serializer):\n email = serializers.EmailField()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n"},{"location":"api-guide/serializers/#serializing-objects","title":"Serializing objects","text":"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)\nserializer.data\n# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}\n At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into json.
from rest_framework.renderers import JSONRenderer\n\njson = JSONRenderer().render(serializer.data)\njson\n# b'{\"email\":\"leila@example.com\",\"content\":\"foo bar\",\"created\":\"2016-01-27T15:17:10.375877\"}'\n"},{"location":"api-guide/serializers/#deserializing-objects","title":"Deserializing objects","text":"Deserialization is similar. First we parse a stream into Python native datatypes...
import io\nfrom rest_framework.parsers import JSONParser\n\nstream = io.BytesIO(json)\ndata = JSONParser().parse(stream)\n ...then we restore those native datatypes into a dictionary of validated data.
serializer = CommentSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}\n"},{"location":"api-guide/serializers/#saving-instances","title":"Saving instances","text":"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):\n email = serializers.EmailField()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n def create(self, validated_data):\n return Comment(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n return instance\n 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):\n return Comment.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n instance.save()\n return instance\n Now when deserializing data, we can call .save() to return an object instance, based on the validated data.
comment = serializer.save()\n 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.\nserializer = CommentSerializer(data=data)\n\n# .save() will update the existing `comment` instance.\nserializer = CommentSerializer(comment, data=data)\n Both the .create() and .update() methods are optional. You can implement either none, one, or both of them, depending on the use-case for your serializer class.
.save()","text":"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)\n Any additional keyword arguments will be included in the validated_data argument when .create() or .update() are called.
.save() directly.","text":"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):\n email = serializers.EmailField()\n message = serializers.CharField()\n\n def save(self):\n email = self.validated_data['email']\n message = self.validated_data['message']\n send_email(from=email, message=message)\n Note that in the case above we're now having to access the serializer .validated_data property directly.
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'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'email': ['Enter a valid email address.'], 'created': ['This field is required.']}\n 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.
"},{"location":"api-guide/serializers/#raising-an-exception-on-invalid-data","title":"Raising an exception on invalid data","text":"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.\nserializer.is_valid(raise_exception=True)\n"},{"location":"api-guide/serializers/#field-level-validation","title":"Field-level validation","text":"You can specify custom field-level validation by adding .validate_<field_name> methods to your Serializer subclass. These are similar to the .clean_<field_name> methods on Django forms.
These methods take a single argument, which is the field value that requires validation.
Your validate_<field_name> methods should return the validated value or raise a serializers.ValidationError. For example:
from rest_framework import serializers\n\nclass BlogPostSerializer(serializers.Serializer):\n title = serializers.CharField(max_length=100)\n content = serializers.CharField()\n\n def validate_title(self, value):\n \"\"\"\n Check that the blog post is about Django.\n \"\"\"\n if 'django' not in value.lower():\n raise serializers.ValidationError(\"Blog post is not about Django\")\n return value\n Note
If your <field_name> is declared on your serializer with the parameter required=False then this validation step will not take place if the field is not included.
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\n\nclass EventSerializer(serializers.Serializer):\n description = serializers.CharField(max_length=100)\n start = serializers.DateTimeField()\n finish = serializers.DateTimeField()\n\n def validate(self, data):\n \"\"\"\n Check that start is before finish.\n \"\"\"\n if data['start'] > data['finish']:\n raise serializers.ValidationError(\"finish must occur after start\")\n return data\n"},{"location":"api-guide/serializers/#validators","title":"Validators","text":"Individual fields on a serializer can include validators, by declaring them on the field instance, for example:
def multiple_of_ten(value):\n if value % 10 != 0:\n raise serializers.ValidationError('Not a multiple of ten')\n\nclass GameRecord(serializers.Serializer):\n score = serializers.IntegerField(validators=[multiple_of_ten])\n ...\n 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):\n name = serializers.CharField()\n room_number = serializers.ChoiceField(choices=[101, 102, 103, 201])\n date = serializers.DateField()\n\n class Meta:\n # Each room only has one event per day.\n validators = [\n UniqueTogetherValidator(\n queryset=Event.objects.all(),\n fields=['room_number', 'date']\n )\n ]\n For more information see the validators documentation.
"},{"location":"api-guide/serializers/#accessing-the-initial-data-and-instance","title":"Accessing the initial data and instance","text":"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.
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\nserializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True)\n"},{"location":"api-guide/serializers/#dealing-with-nested-objects","title":"Dealing with nested objects","text":"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):\n email = serializers.EmailField()\n username = serializers.CharField(max_length=100)\n\nclass CommentSerializer(serializers.Serializer):\n user = UserSerializer()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n 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):\n user = UserSerializer(required=False) # May be an anonymous user.\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n Similarly if a nested representation should be a list of items, you should pass the many=True flag to the nested serializer.
class CommentSerializer(serializers.Serializer):\n user = UserSerializer(required=False)\n edits = EditItemSerializer(many=True) # A nested list of 'edit' items.\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n"},{"location":"api-guide/serializers/#writable-nested-representations","title":"Writable nested representations","text":"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'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'user': {'email': ['Enter a valid email address.']}, 'created': ['This field is required.']}\n Similarly, the .validated_data property will include nested data structures.
.create() methods for nested representations","text":"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):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ['username', 'email', 'profile']\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user\n"},{"location":"api-guide/serializers/#writing-update-methods-for-nested-representations","title":"Writing .update() methods for nested representations","text":"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?
NULL in the database.Here's an example for an .update() method on our previous UserSerializer class.
def update(self, instance, validated_data):\n profile_data = validated_data.pop('profile')\n # Unless the application properly enforces that this field is\n # always set, the following could raise a `DoesNotExist`, which\n # would need to be handled.\n profile = instance.profile\n\n instance.username = validated_data.get('username', instance.username)\n instance.email = validated_data.get('email', instance.email)\n instance.save()\n\n profile.is_premium_member = profile_data.get(\n 'is_premium_member',\n profile.is_premium_member\n )\n profile.has_support_contract = profile_data.get(\n 'has_support_contract',\n profile.has_support_contract\n )\n profile.save()\n\n return instance\n 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.
"},{"location":"api-guide/serializers/#handling-saving-related-instances-in-model-manager-classes","title":"Handling saving related instances in model manager classes","text":"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):\n ...\n\n def create(self, username, email, is_premium_member=False, has_support_contract=False):\n user = User(username=username, email=email)\n user.save()\n profile = Profile(\n user=user,\n is_premium_member=is_premium_member,\n has_support_contract=has_support_contract\n )\n profile.save()\n return user\n 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):\n return User.objects.create(\n username=validated_data['username'],\n email=validated_data['email'],\n is_premium_member=validated_data['profile']['is_premium_member'],\n has_support_contract=validated_data['profile']['has_support_contract']\n )\n For more details on this approach see the Django documentation on model managers, and this blogpost on using model and manager classes.
"},{"location":"api-guide/serializers/#dealing-with-multiple-objects","title":"Dealing with multiple objects","text":"The Serializer class can also handle serializing or deserializing lists of 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()\nserializer = BookSerializer(queryset, many=True)\nserializer.data\n# [\n# {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},\n# {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},\n# {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}\n# ]\n"},{"location":"api-guide/serializers/#deserializing-multiple-objects","title":"Deserializing multiple objects","text":"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.
"},{"location":"api-guide/serializers/#including-extra-context","title":"Including extra context","text":"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})\nserializer.data\n# {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}\n The context dictionary can be used within any serializer field logic, such as a custom .to_representation() method, by accessing the self.context attribute.
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:
.create() and .update().Declaring a ModelSerializer looks like this:
class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ['id', 'account_name', 'users', 'created']\n 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.
ModelSerializer","text":"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\n>>> serializer = AccountSerializer()\n>>> print(repr(serializer))\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n"},{"location":"api-guide/serializers/#specifying-which-fields-to-include","title":"Specifying which fields to include","text":"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):\n class Meta:\n model = Account\n fields = ['id', 'account_name', 'users', 'created']\n 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):\n class Meta:\n model = Account\n fields = '__all__'\n You can set the exclude attribute to a list of fields to be excluded from the serializer.
For example:
class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n exclude = ['users']\n 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.
The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option:
class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ['id', 'account_name', 'users', 'created']\n depth = 1\n 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.
"},{"location":"api-guide/serializers/#specifying-fields-explicitly","title":"Specifying fields explicitly","text":"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):\n url = serializers.CharField(source='get_absolute_url', read_only=True)\n groups = serializers.PrimaryKeyRelatedField(many=True)\n\n class Meta:\n model = Account\n fields = ['url', 'groups']\n Extra fields can correspond to any property or callable on the model.
"},{"location":"api-guide/serializers/#specifying-read-only-fields","title":"Specifying read only fields","text":"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):\n class Meta:\n model = Account\n fields = ['id', 'account_name', 'users', 'created']\n read_only_fields = ['account_name']\n 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())\n Please review the Validators Documentation for details on the UniqueTogetherValidator and CurrentUserDefault classes.
"},{"location":"api-guide/serializers/#additional-keyword-arguments","title":"Additional keyword arguments","text":"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):\n class Meta:\n model = User\n fields = ['email', 'username', 'password']\n extra_kwargs = {'password': {'write_only': True}}\n\n def create(self, validated_data):\n user = User(\n email=validated_data['email'],\n username=validated_data['username']\n )\n user.set_password(validated_data['password'])\n user.save()\n return user\n 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.
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.
"},{"location":"api-guide/serializers/#customizing-field-mappings","title":"Customizing field mappings","text":"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","text":"A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
"},{"location":"api-guide/serializers/#serializer_related_field","title":"serializer_related_field","text":"This property should be the serializer field class, that is used for relational fields by default.
For ModelSerializer this defaults to serializers.PrimaryKeyRelatedField.
For HyperlinkedModelSerializer this defaults to serializers.HyperlinkedRelatedField.
serializer_url_field","text":"The serializer field class that should be used for any url field on the serializer.
Defaults to serializers.HyperlinkedIdentityField
serializer_choice_field","text":"The serializer field class that should be used for any choice fields on the serializer.
Defaults to serializers.ChoiceField
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)","text":"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)","text":"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)","text":"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)","text":"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)","text":"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)","text":"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.
"},{"location":"api-guide/serializers/#hyperlinkedmodelserializer","title":"HyperlinkedModelSerializer","text":"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):\n class Meta:\n model = Account\n fields = ['url', 'id', 'account_name', 'users', 'created']\n"},{"location":"api-guide/serializers/#absolute-and-relative-urls","title":"Absolute and relative URLs","text":"When instantiating a HyperlinkedModelSerializer you must include the current request in the serializer context, for example:
serializer = AccountSerializer(queryset, context={'request': request})\n 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/\n Rather than relative URLs, such as:
/accounts/1/\n If you do want to use relative URLs, you should explicitly pass {'request': None} in the serializer context.
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):\n class Meta:\n model = Account\n fields = ['url', 'account_name', 'users', 'created']\n extra_kwargs = {\n 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'},\n 'users': {'lookup_field': 'username'}\n }\n Alternatively you can set the fields on the serializer explicitly. For example:
class AccountSerializer(serializers.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='accounts',\n lookup_field='slug'\n )\n users = serializers.HyperlinkedRelatedField(\n view_name='user-detail',\n lookup_field='username',\n many=True,\n read_only=True\n )\n\n class Meta:\n model = Account\n fields = ['url', 'account_name', 'users', 'created']\n 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.
The name of the URL field defaults to 'url'. You can override this globally, by using the URL_FIELD_NAME setting.
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","text":"This is True by default, but can be set to False if you want to disallow empty lists as valid input.
max_length","text":"This is None by default, but can be set to a positive integer if you want to validate that the list contains no more than this number of elements.
min_length","text":"This is None by default, but can be set to a positive integer if you want to validate that the list contains no fewer than this number of elements.
ListSerializer behavior","text":"There are a few use cases when you might want to customize the ListSerializer behavior. For example:
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):\n ...\n\nclass CustomSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = CustomListSerializer\n"},{"location":"api-guide/serializers/#customizing-multiple-create","title":"Customizing multiple create","text":"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):\n def create(self, validated_data):\n books = [Book(**item) for item in validated_data]\n return Book.objects.bulk_create(books)\n\nclass BookSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = BookListSerializer\n"},{"location":"api-guide/serializers/#customizing-multiple-update","title":"Customizing multiple update","text":"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:
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):\n def update(self, instance, validated_data):\n # Maps for id->instance and id->data item.\n book_mapping = {book.id: book for book in instance}\n data_mapping = {item['id']: item for item in validated_data}\n\n # Perform creations and updates.\n ret = []\n for book_id, data in data_mapping.items():\n book = book_mapping.get(book_id, None)\n if book is None:\n ret.append(self.child.create(data))\n else:\n ret.append(self.child.update(book, data))\n\n # Perform deletions.\n for book_id, book in book_mapping.items():\n if book_id not in data_mapping:\n book.delete()\n\n return ret\n\nclass BookSerializer(serializers.Serializer):\n # We need to identify elements in the list using their primary key,\n # so use a writable field here, rather than the default which would be read-only.\n id = serializers.IntegerField()\n ...\n\n class Meta:\n list_serializer_class = BookListSerializer\n"},{"location":"api-guide/serializers/#customizing-listserializer-initialization","title":"Customizing ListSerializer initialization","text":"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\n def many_init(cls, *args, **kwargs):\n # Instantiate the child serializer.\n kwargs['child'] = cls()\n # Instantiate the parent list serializer.\n return CustomListSerializer(*args, **kwargs)\n"},{"location":"api-guide/serializers/#baseserializer","title":"BaseSerializer","text":"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.
BaseSerializer classes","text":"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):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField()\n It's simple to create a read-only serializer for converting HighScore instances into primitive data types.
class HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, instance):\n return {\n 'score': instance.score,\n 'player_name': instance.player_name\n }\n We can now use this class to serialize single HighScore instances:
@api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data)\n Or use it to serialize multiple instances:
@api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)\n"},{"location":"api-guide/serializers/#read-write-baseserializer-classes","title":"Read-write BaseSerializer classes","text":"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):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise serializers.ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise serializers.ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) > 10:\n raise serializers.ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, instance):\n return {\n 'score': instance.score,\n 'player_name': instance.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)\n"},{"location":"api-guide/serializers/#creating-new-base-classes","title":"Creating new base classes","text":"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 complex objects into primitive representations.
class ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, instance):\n output = {}\n for attribute_name in dir(instance):\n attribute = getattr(instance, attribute_name)\n if attribute_name.startswith('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)\n return output\n"},{"location":"api-guide/serializers/#advanced-serializer-usage","title":"Advanced serializer usage","text":""},{"location":"api-guide/serializers/#overriding-serialization-and-deserialization-behavior","title":"Overriding serialization and deserialization behavior","text":"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...
The signatures for these methods are as follows:
"},{"location":"api-guide/serializers/#to_representationself-instance","title":"to_representation(self, instance)","text":"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 to modify the representation style. For example:
def to_representation(self, instance):\n \"\"\"Convert `username` to lowercase.\"\"\"\n ret = super().to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret\n"},{"location":"api-guide/serializers/#to_internal_valueself-data","title":"to_internal_value(self, data)","text":"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.
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):\n my_field = serializers.CharField()\n\n def validate_my_field(self, value):\n ...\n\nclass MySerializer(MyBaseSerializer):\n ...\n 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):\n class Meta(MyBaseSerializer.Meta):\n model = Account\n 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:
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):\n my_field = serializers.CharField()\n\nclass MySerializer(MyBaseSerializer):\n my_field = None\n 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.
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.
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):\n \"\"\"\n A ModelSerializer that takes an additional `fields` argument that\n controls which fields should be displayed.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # Don't pass the 'fields' arg up to the superclass\n fields = kwargs.pop('fields', None)\n\n # Instantiate the superclass normally\n super().__init__(*args, **kwargs)\n\n if fields is not None:\n # Drop any fields that are not specified in the `fields` argument.\n allowed = set(fields)\n existing = set(self.fields)\n for field_name in existing - allowed:\n self.fields.pop(field_name)\n This would then allow you to do the following:
>>> class UserSerializer(DynamicFieldsModelSerializer):\n>>> class Meta:\n>>> model = User\n>>> fields = ['id', 'username', 'email']\n>>>\n>>> print(UserSerializer(user))\n{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}\n>>>\n>>> print(UserSerializer(user, fields=('id', 'email')))\n{'id': 2, 'email': 'jon@example.com'}\n"},{"location":"api-guide/serializers/#customizing-the-default-fields","title":"Customizing the default fields","text":"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.
"},{"location":"api-guide/serializers/#third-party-packages","title":"Third party packages","text":"The following third party packages are also available.
"},{"location":"api-guide/serializers/#django-rest-marshmallow","title":"Django REST marshmallow","text":"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.
"},{"location":"api-guide/serializers/#serpy","title":"Serpy","text":"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.
"},{"location":"api-guide/serializers/#mongoenginemodelserializer","title":"MongoengineModelSerializer","text":"The django-rest-framework-mongoengine package provides a MongoEngineModelSerializer serializer class that supports using MongoDB as the storage layer for Django REST framework.
The django-rest-framework-gis package provides a GeoFeatureModelSerializer serializer class that supports GeoJSON both for read and write operations.
The django-rest-framework-hstore package provides an HStoreSerializer to support django-hstore DictionaryField model field and its schema-mode feature.
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.
"},{"location":"api-guide/serializers/#dynamic-fields-mixin","title":"Dynamic Fields Mixin","text":"The drf-dynamic-fields package provides a mixin to dynamically limit the fields per serializer to a subset specified by an URL parameter.
"},{"location":"api-guide/serializers/#drf-flexfields","title":"DRF FlexFields","text":"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.
"},{"location":"api-guide/serializers/#serializer-extensions","title":"Serializer Extensions","text":"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.
"},{"location":"api-guide/serializers/#html-json-forms","title":"HTML JSON Forms","text":"The html-json-forms package provides an algorithm and serializer for processing <form> submissions per the (inactive) HTML JSON Form specification. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, <input name=\"items[0][id]\" value=\"5\"> will be interpreted as {\"items\": [{\"id\": \"5\"}]}.
DRF-Base64 provides a set of field and model serializers that handles the upload of base64-encoded files.
"},{"location":"api-guide/serializers/#queryfields","title":"QueryFields","text":"djangorestframework-queryfields allows API clients to specify which fields will be sent in the response via inclusion/exclusion query parameters.
"},{"location":"api-guide/serializers/#drf-writable-nested","title":"DRF Writable Nested","text":"The drf-writable-nested package provides writable nested model serializer which allows to create/update models with nested related data.
"},{"location":"api-guide/serializers/#drf-encrypt-content","title":"DRF Encrypt Content","text":"The drf-encrypt-content package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
"},{"location":"api-guide/serializers/#shapeless-serializers","title":"Shapeless Serializers","text":"The drf-shapeless-serializers package provides dynamic serializer configuration capabilities, allowing runtime field selection, renaming, attribute modification, and nested relationship configuration without creating multiple serializer classes. It helps eliminate serializer boilerplate while providing flexible API responses.
"},{"location":"api-guide/settings/","title":"Settings","text":"Namespaces are one honking great idea - let's do more of those!
\u2014 The Zen of Python
Configuration for REST framework is all namespaced inside a single Django setting, named REST_FRAMEWORK.
For example your project's settings.py file might include something like this:
REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n ],\n 'DEFAULT_PARSER_CLASSES': [\n 'rest_framework.parsers.JSONParser',\n ]\n}\n"},{"location":"api-guide/settings/#accessing-settings","title":"Accessing settings","text":"If you need to access the values of REST framework's API settings in your project, you should use the api_settings object. For example.
from rest_framework.settings import api_settings\n\nprint(api_settings.DEFAULT_AUTHENTICATION_CLASSES)\n The api_settings object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.
The following settings control the basic API policies, and are applied to every APIView class-based view, or @api_view function based view.
A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a Response object.
Default:
[\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n]\n"},{"location":"api-guide/settings/#default_parser_classes","title":"DEFAULT_PARSER_CLASSES","text":"A list or tuple of parser classes, that determines the default set of parsers used when accessing the request.data property.
Default:
[\n 'rest_framework.parsers.JSONParser',\n 'rest_framework.parsers.FormParser',\n 'rest_framework.parsers.MultiPartParser'\n]\n"},{"location":"api-guide/settings/#default_authentication_classes","title":"DEFAULT_AUTHENTICATION_CLASSES","text":"A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the request.user or request.auth properties.
Default:
[\n 'rest_framework.authentication.SessionAuthentication',\n 'rest_framework.authentication.BasicAuthentication'\n]\n"},{"location":"api-guide/settings/#default_permission_classes","title":"DEFAULT_PERMISSION_CLASSES","text":"A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list.
Default:
[\n 'rest_framework.permissions.AllowAny',\n]\n"},{"location":"api-guide/settings/#default_throttle_classes","title":"DEFAULT_THROTTLE_CLASSES","text":"A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.
Default: []
A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.
Default: 'rest_framework.negotiation.DefaultContentNegotiation'
A view inspector class that will be used for schema generation.
Default: 'rest_framework.schemas.openapi.AutoSchema'
The following settings control the behavior of the generic class-based views.
"},{"location":"api-guide/settings/#default_filter_backends","title":"DEFAULT_FILTER_BACKENDS","text":"A list of filter backend classes that should be used for generic filtering. If set to None then generic filtering is disabled.
The default class to use for queryset pagination. If set to None, pagination is disabled by default. See the pagination documentation for further guidance on setting and modifying the pagination style.
Default: None
The default page size to use for pagination. If set to None, pagination is disabled by default.
Default: None
The name of a query parameter, which can be used to specify the search term used by SearchFilter.
Default: search
The name of a query parameter, which can be used to specify the ordering of results returned by OrderingFilter.
Default: ordering
The value that should be used for request.version when no versioning information is present.
Default: None
If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set.
Default: None
The string that should used for any versioning parameters, such as in the media type or URL query parameters.
Default: 'version'
The default versioning scheme to use.
Default: None
The following settings control the behavior of unauthenticated requests.
"},{"location":"api-guide/settings/#unauthenticated_user","title":"UNAUTHENTICATED_USER","text":"The class that should be used to initialize request.user for unauthenticated requests. (If removing authentication entirely, e.g. by removing django.contrib.auth from INSTALLED_APPS, set UNAUTHENTICATED_USER to None.)
Default: django.contrib.auth.models.AnonymousUser
The class that should be used to initialize request.auth for unauthenticated requests.
Default: None
The following settings control the behavior of APIRequestFactory and APIClient
"},{"location":"api-guide/settings/#test_request_default_format","title":"TEST_REQUEST_DEFAULT_FORMAT","text":"The default format that should be used when making test requests.
This should match up with the format of one of the renderer classes in the TEST_REQUEST_RENDERER_CLASSES setting.
Default: 'multipart'
The renderer classes that are supported when building test requests.
The format of any of these renderer classes may be used when constructing a test request, for example: client.post('/users', {'username': 'jamie'}, format='json')
Default:
[\n 'rest_framework.renderers.MultiPartRenderer',\n 'rest_framework.renderers.JSONRenderer'\n]\n"},{"location":"api-guide/settings/#schema-generation-controls","title":"Schema generation controls","text":""},{"location":"api-guide/settings/#schema_coerce_path_pk","title":"SCHEMA_COERCE_PATH_PK","text":"If set, this maps the 'pk' identifier in the URL conf onto the actual field name when generating a schema path parameter. Typically this will be 'id'. This gives a more suitable representation as \"primary key\" is an implementation detail, whereas \"identifier\" is a more general concept.
Default: True
If set, this is used to map internal viewset method names onto external action names used in the schema generation. This allows us to generate names that are more suitable for an external representation than those that are used internally in the codebase.
Default: {'retrieve': 'read', 'destroy': 'delete'}
The name of a URL parameter that may be used to override the default content negotiation Accept header behavior, by using a format=\u2026 query parameter in the request URL.
For example: http://example.com/organizations/?format=csv
If the value of this setting is None then URL format overrides will be disabled.
Default: 'format'
The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using format_suffix_patterns to include suffixed URL patterns.
For example: http://example.com/organizations.csv/
Default: 'format'
The following settings are used to control how date and time representations may be parsed and rendered.
"},{"location":"api-guide/settings/#datetime_format","title":"DATETIME_FORMAT","text":"A format string that should be used by default for rendering the output of DateTimeField serializer fields. If None, then DateTimeField serializer fields will return Python datetime objects, and the datetime encoding will be determined by the renderer.
May be any of None, 'iso-8601' or a Python strftime format string.
Default: 'iso-8601'
A list of format strings that should be used by default for parsing inputs to DateTimeField serializer fields.
May be a list including the string 'iso-8601' or Python strftime format strings.
Default: ['iso-8601']
A format string that should be used by default for rendering the output of DateField serializer fields. If None, then DateField serializer fields will return Python date objects, and the date encoding will be determined by the renderer.
May be any of None, 'iso-8601' or a Python strftime format string.
Default: 'iso-8601'
A list of format strings that should be used by default for parsing inputs to DateField serializer fields.
May be a list including the string 'iso-8601' or Python strftime format strings.
Default: ['iso-8601']
A format string that should be used by default for rendering the output of TimeField serializer fields. If None, then TimeField serializer fields will return Python time objects, and the time encoding will be determined by the renderer.
May be any of None, 'iso-8601' or a Python strftime format string.
Default: 'iso-8601'
A list of format strings that should be used by default for parsing inputs to TimeField serializer fields.
May be a list including the string 'iso-8601' or Python strftime format strings.
Default: ['iso-8601']
Indicates the default format that should be used for rendering the output of DurationField serializer fields. If None, then DurationField serializer fields will return Python timedelta objects, and the duration encoding will be determined by the renderer.
May be any of None, 'iso-8601' or 'django' (the format accepted by django.utils.dateparse.parse_duration).
Default: 'django'
When set to True, JSON responses will allow unicode characters in responses. For example:
{\"unicode black star\":\"\u2605\"}\n When set to False, JSON responses will escape non-ascii characters, like so:
{\"unicode black star\":\"\\u2605\"}\n Both styles conform to RFC 4627, and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses.
Default: True
When set to True, JSON responses will return compact representations, with no spacing after ':' and ',' characters. For example:
{\"is_admin\":false,\"email\":\"jane@example\"}\n When set to False, JSON responses will return slightly more verbose representations, like so:
{\"is_admin\": false, \"email\": \"jane@example\"}\n The default style is to return minified responses, in line with Heroku's API design guidelines.
Default: True
When set to True, JSON rendering and parsing will only observe syntactically valid JSON, raising an exception for the extended float values (nan, inf, -inf) accepted by Python's json module. This is the recommended setting, as these values are not generally supported. e.g., neither Javascript's JSON.Parse nor PostgreSQL's JSON data type accept these values.
When set to False, JSON rendering and parsing will be permissive. However, these values are still invalid and will need to be specially handled in your code.
Default: True
When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations.
When set to True, the serializer DecimalField class will return strings instead of Decimal objects. When set to False, serializers will return Decimal objects, which the default JSON encoder will return as floats.
Default: True
When returning biginteger objects in API representations that do not support numbers up to 2^64, it is best to return the value as a string. This avoids the loss of precision that occurs with biginteger implementations.
When set to True, the serializer BigIntegerField class (by default) will return strings instead of BigInteger objects. When set to False, serializers will return BigInteger objects, which the default JSON encoder will return as numbers.
Default: False
The following settings are used to generate the view names and descriptions, as used in responses to OPTIONS requests, and as used in the browsable API.
A string representing the function that should be used when generating view names.
This should be a function with the following signature:
view_name(self)\n self: The view instance. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing self.__class__.__name__.If the view instance inherits ViewSet, it may have been initialized with several optional arguments:
name: A name explicitly provided to a view in the viewset. Typically, this value should be used as-is when provided.suffix: Text used when differentiating individual views in a viewset. This argument is mutually exclusive to name.detail: Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view.Default: 'rest_framework.views.get_view_name'
A string representing the function that should be used when generating view descriptions.
This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support rst markup in your view docstrings being output in the browsable API.
This should be a function with the following signature:
view_description(self, html=False)\n self: The view instance. Typically the description function would inspect the docstring of the class when generating a description, by accessing self.__class__.__doc__html: A boolean indicating if HTML output is required. True when used in the browsable API, and False when used in generating OPTIONS responses.If the view instance inherits ViewSet, it may have been initialized with several optional arguments:
description: A description explicitly provided to the view in the viewset. Typically, this is set by extra viewset actions, and should be used as-is.Default: 'rest_framework.views.get_view_description'
Global settings for select field cutoffs for rendering relational fields in the browsable API.
"},{"location":"api-guide/settings/#html_select_cutoff","title":"HTML_SELECT_CUTOFF","text":"Global setting for the html_cutoff value. Must be an integer.
Default: 1000
"},{"location":"api-guide/settings/#html_select_cutoff_text","title":"HTML_SELECT_CUTOFF_TEXT","text":"A string representing a global setting for html_cutoff_text.
Default: \"More than {count} items...\"
A string representing the function that should be used when returning a response for any given exception. If the function returns None, a 500 error will be raised.
This setting can be changed to support error responses other than the default {\"detail\": \"Failure...\"} responses. For example, you can use it to provide API responses like {\"errors\": [{\"message\": \"Failure...\", \"code\": \"\"} ...]}.
This should be a function with the following signature:
exception_handler(exc, context)\n exc: The exception.Default: 'rest_framework.views.exception_handler'
A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors.
Default: 'non_field_errors'
A string representing the key that should be used for the URL fields generated by HyperlinkedModelSerializer.
Default: 'url'
An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to None then less strict IP matching will be used by the throttle classes.
Default: None
418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code \"418 I'm a teapot\". The resulting entity body MAY be short and stout.
\u2014 RFC 2324, Hyper Text Coffee Pot Control Protocol
Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make your code more obvious and readable.
from rest_framework import status\nfrom rest_framework.response import Response\n\ndef empty_view(self):\n content = {'please move along': 'nothing to see here'}\n return Response(content, status=status.HTTP_404_NOT_FOUND)\n The full set of HTTP status codes included in the status module is listed below.
The module also includes a set of helper functions for testing if a status code is in a given range.
from rest_framework import status\nfrom rest_framework.test import APITestCase\n\nclass ExampleTestCase(APITestCase):\n def test_url_root(self):\n url = reverse('index')\n response = self.client.get(url)\n self.assertTrue(status.is_success(response.status_code))\n For more information on proper usage of HTTP status codes see RFC 2616 and RFC 6585.
"},{"location":"api-guide/status-codes/#informational-1xx","title":"Informational - 1xx","text":"This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.
HTTP_100_CONTINUE\nHTTP_101_SWITCHING_PROTOCOLS\nHTTP_102_PROCESSING\nHTTP_103_EARLY_HINTS\n"},{"location":"api-guide/status-codes/#successful-2xx","title":"Successful - 2xx","text":"This class of status code indicates that the client's request was successfully received, understood, and accepted.
HTTP_200_OK\nHTTP_201_CREATED\nHTTP_202_ACCEPTED\nHTTP_203_NON_AUTHORITATIVE_INFORMATION\nHTTP_204_NO_CONTENT\nHTTP_205_RESET_CONTENT\nHTTP_206_PARTIAL_CONTENT\nHTTP_207_MULTI_STATUS\nHTTP_208_ALREADY_REPORTED\nHTTP_226_IM_USED\n"},{"location":"api-guide/status-codes/#redirection-3xx","title":"Redirection - 3xx","text":"This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.
HTTP_300_MULTIPLE_CHOICES\nHTTP_301_MOVED_PERMANENTLY\nHTTP_302_FOUND\nHTTP_303_SEE_OTHER\nHTTP_304_NOT_MODIFIED\nHTTP_305_USE_PROXY\nHTTP_306_RESERVED\nHTTP_307_TEMPORARY_REDIRECT\nHTTP_308_PERMANENT_REDIRECT\n"},{"location":"api-guide/status-codes/#client-error-4xx","title":"Client Error - 4xx","text":"The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
HTTP_400_BAD_REQUEST\nHTTP_401_UNAUTHORIZED\nHTTP_402_PAYMENT_REQUIRED\nHTTP_403_FORBIDDEN\nHTTP_404_NOT_FOUND\nHTTP_405_METHOD_NOT_ALLOWED\nHTTP_406_NOT_ACCEPTABLE\nHTTP_407_PROXY_AUTHENTICATION_REQUIRED\nHTTP_408_REQUEST_TIMEOUT\nHTTP_409_CONFLICT\nHTTP_410_GONE\nHTTP_411_LENGTH_REQUIRED\nHTTP_412_PRECONDITION_FAILED\nHTTP_413_REQUEST_ENTITY_TOO_LARGE\nHTTP_414_REQUEST_URI_TOO_LONG\nHTTP_415_UNSUPPORTED_MEDIA_TYPE\nHTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE\nHTTP_417_EXPECTATION_FAILED\nHTTP_421_MISDIRECTED_REQUEST\nHTTP_422_UNPROCESSABLE_ENTITY\nHTTP_423_LOCKED\nHTTP_424_FAILED_DEPENDENCY\nHTTP_425_TOO_EARLY\nHTTP_426_UPGRADE_REQUIRED\nHTTP_428_PRECONDITION_REQUIRED\nHTTP_429_TOO_MANY_REQUESTS\nHTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE\nHTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS\n"},{"location":"api-guide/status-codes/#server-error-5xx","title":"Server Error - 5xx","text":"Response status codes beginning with the digit \"5\" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
HTTP_500_INTERNAL_SERVER_ERROR\nHTTP_501_NOT_IMPLEMENTED\nHTTP_502_BAD_GATEWAY\nHTTP_503_SERVICE_UNAVAILABLE\nHTTP_504_GATEWAY_TIMEOUT\nHTTP_505_HTTP_VERSION_NOT_SUPPORTED\nHTTP_506_VARIANT_ALSO_NEGOTIATES\nHTTP_507_INSUFFICIENT_STORAGE\nHTTP_508_LOOP_DETECTED\nHTTP_509_BANDWIDTH_LIMIT_EXCEEDED\nHTTP_510_NOT_EXTENDED\nHTTP_511_NETWORK_AUTHENTICATION_REQUIRED\n"},{"location":"api-guide/status-codes/#helper-functions","title":"Helper functions","text":"The following helper functions are available for identifying the category of the response code.
is_informational() # 1xx\nis_success() #\u00a02xx\nis_redirect() # 3xx\nis_client_error() # 4xx\nis_server_error() # 5xx\n"},{"location":"api-guide/testing/","title":"Testing","text":"Code without tests is broken as designed.
\u2014 Jacob Kaplan-Moss
REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.
"},{"location":"api-guide/testing/#apirequestfactory","title":"APIRequestFactory","text":"Extends Django's existing RequestFactory class.
The APIRequestFactory class supports an almost identical API to Django's standard RequestFactory class. This means that the standard .get(), .post(), .put(), .patch(), .delete(), .head() and .options() methods are all available.
from rest_framework.test import APIRequestFactory\n\n# Using the standard RequestFactory API to create a form POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'})\n\n# Using the standard RequestFactory API to encode JSON data\nrequest = factory.post('/notes/', {'title': 'new idea'}, content_type='application/json')\n"},{"location":"api-guide/testing/#using-the-format-argument","title":"Using the format argument","text":"Methods which create a request body, such as post, put and patch, include a format argument, which make it easy to generate requests using a wide set of request formats. When using this argument, the factory will select an appropriate renderer and its configured content_type. For example:
# Create a JSON POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'}, format='json')\n By default the available formats are 'multipart' and 'json'. For compatibility with Django's existing RequestFactory the default format is 'multipart'.
To support a wider set of request formats, or change the default format, see the configuration section.
"},{"location":"api-guide/testing/#explicitly-encoding-the-request-body","title":"Explicitly encoding the request body","text":"If you need to explicitly encode the request body, you can do so by setting the content_type flag. For example:
request = factory.post('/notes/', yaml.dump({'title': 'new idea'}), content_type='application/yaml')\n"},{"location":"api-guide/testing/#put-and-patch-with-form-data","title":"PUT and PATCH with form data","text":"One difference worth noting between Django's RequestFactory and REST framework's APIRequestFactory is that multipart form data will be encoded for methods other than just .post().
For example, using APIRequestFactory, you can make a form PUT request like so:
factory = APIRequestFactory()\nrequest = factory.put('/notes/547/', {'title': 'remember to email dave'})\n Using Django's RequestFactory, you'd need to explicitly encode the data yourself:
from django.test.client import encode_multipart, RequestFactory\n\nfactory = RequestFactory()\ndata = {'title': 'remember to email dave'}\ncontent = encode_multipart('BoUnDaRyStRiNg', data)\ncontent_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'\nrequest = factory.put('/notes/547/', content, content_type=content_type)\n"},{"location":"api-guide/testing/#forcing-authentication","title":"Forcing authentication","text":"When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.
To forcibly authenticate a request, use the force_authenticate() method.
from rest_framework.test import force_authenticate\n\nfactory = APIRequestFactory()\nuser = User.objects.get(username='olivia')\nview = AccountDetail.as_view()\n\n# Make an authenticated request to the view...\nrequest = factory.get('/accounts/django-superstars/')\nforce_authenticate(request, user=user)\nresponse = view(request)\n The signature for the method is force_authenticate(request, user=None, token=None). When making the call, either or both of the user and token may be set.
For example, when forcibly authenticating using a token, you might do something like the following:
user = User.objects.get(username='olivia')\nrequest = factory.get('/accounts/django-superstars/')\nforce_authenticate(request, user=user, token=user.auth_token)\n Note
force_authenticate directly sets request.user to the in-memory user instance. If you are reusing the same user instance across multiple tests that update the saved user state, you may need to call refresh_from_db() between tests.
Note
When using APIRequestFactory, the object that is returned is Django's standard HttpRequest, and not REST framework's Request object, which is only generated once the view is called.
This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting .token directly will have no effect, and setting .user directly will only work if session authentication is being used.
# Request will only authenticate if `SessionAuthentication` is in use.\nrequest = factory.get('/accounts/django-superstars/')\nrequest.user = user\nresponse = view(request)\n If you want to test a request involving the REST framework\u2019s 'Request' object, you\u2019ll need to manually transform it first:
class DummyView(APIView):\n ...\n\nfactory = APIRequestFactory()\nrequest = factory.get('/', {'demo': 'test'})\ndrf_request = DummyView().initialize_request(request)\nassert drf_request.query_params == {'demo': ['test']}\n\nrequest = factory.post('/', {'example': 'test'})\ndrf_request = DummyView().initialize_request(request)\nassert drf_request.data.get('example') == 'test'\n"},{"location":"api-guide/testing/#forcing-csrf-validation","title":"Forcing CSRF validation","text":"By default, requests created with APIRequestFactory will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the enforce_csrf_checks flag when instantiating the factory.
factory = APIRequestFactory(enforce_csrf_checks=True)\n Note
It's worth noting that Django's standard RequestFactory doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.
Extends Django's existing Client class.
The APIClient class supports the same request interface as Django's standard Client class. This means that the standard .get(), .post(), .put(), .patch(), .delete(), .head() and .options() methods are all available. For example:
from rest_framework.test import APIClient\n\nclient = APIClient()\nclient.post('/notes/', {'title': 'new idea'}, format='json')\n To support a wider set of request formats, or change the default format, see the configuration section.
"},{"location":"api-guide/testing/#authenticating","title":"Authenticating","text":""},{"location":"api-guide/testing/#loginkwargs","title":".login(**kwargs)","text":"The login method functions exactly as it does with Django's regular Client class. This allows you to authenticate requests against any views which include SessionAuthentication.
# Make all requests in the context of a logged in session.\nclient = APIClient()\nclient.login(username='lauren', password='secret')\n To logout, call the logout method as usual.
# Log out\nclient.logout()\n The login method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.
The credentials method can be used to set headers that will then be included on all subsequent requests by the test client.
from rest_framework.authtoken.models import Token\nfrom rest_framework.test import APIClient\n\n# Include an appropriate `Authorization:` header on all requests.\ntoken = Token.objects.get(user__username='lauren')\nclient = APIClient()\nclient.credentials(HTTP_AUTHORIZATION='Token ' + token.key)\n Note that calling credentials a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments.
# Stop including any credentials\nclient.credentials()\n The credentials method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.
Sometimes you may want to bypass authentication entirely and force all requests by the test client to be automatically treated as authenticated.
This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.
user = User.objects.get(username='lauren')\nclient = APIClient()\nclient.force_authenticate(user=user)\n To unauthenticate subsequent requests, call force_authenticate setting the user and/or token to None.
client.force_authenticate(user=None)\n"},{"location":"api-guide/testing/#csrf-validation","title":"CSRF validation","text":"By default CSRF validation is not applied when using APIClient. If you need to explicitly enable CSRF validation, you can do so by setting the enforce_csrf_checks flag when instantiating the client.
client = APIClient(enforce_csrf_checks=True)\n As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling login().
REST framework also includes a client for interacting with your application using the popular Python library, requests. This may be useful if:
This exposes exactly the same interface as if you were using a requests session directly.
from rest_framework.test import RequestsClient\n\nclient = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200\n Note that the requests client requires you to pass fully qualified URLs.
"},{"location":"api-guide/testing/#requestsclient-and-working-with-the-database","title":"RequestsClient and working with the database","text":"The RequestsClient class is useful if you want to write tests that solely interact with the service interface. This is a little stricter than using the standard Django test client, as it means that all interactions should be via the API.
If you're using RequestsClient you'll want to ensure that test setup, and results assertions are performed as regular API calls, rather than interacting with the database models directly. For example, rather than checking that Customer.objects.count() == 3 you would list the customers endpoint, and ensure that it contains three records.
Custom headers and authentication credentials can be provided in the same way as when using a standard requests.Session instance.
from requests.auth import HTTPBasicAuth\n\nclient.auth = HTTPBasicAuth('user', 'pass')\nclient.headers.update({'x-test': 'true'})\n"},{"location":"api-guide/testing/#csrf","title":"CSRF","text":"If you're using SessionAuthentication then you'll need to include a CSRF token for any POST, PUT, PATCH or DELETE requests.
You can do so by following the same flow that a JavaScript based client would use. First, make a GET request in order to obtain a CSRF token, then present that token in the following request.
For example...
client = RequestsClient()\n\n# Obtain a CSRF token.\nresponse = client.get('http://testserver/homepage/')\nassert response.status_code == 200\ncsrftoken = response.cookies['csrftoken']\n\n# Interact with the API.\nresponse = client.post('http://testserver/organizations/', json={\n 'name': 'MegaCorp',\n 'status': 'active'\n}, headers={'X-CSRFToken': csrftoken})\nassert response.status_code == 200\n"},{"location":"api-guide/testing/#live-tests","title":"Live tests","text":"With careful usage both the RequestsClient and the CoreAPIClient provide the ability to write test cases that can run either in development, or be run directly against your staging server or production environment.
Using this style to create basic tests of a few core pieces of functionality is a powerful way to validate your live service. Doing so may require some careful attention to setup and teardown to ensure that the tests run in a way that they do not directly affect customer data.
"},{"location":"api-guide/testing/#coreapiclient","title":"CoreAPIClient","text":"The CoreAPIClient allows you to interact with your API using the Python coreapi client library.
# Fetch the API schema\nclient = CoreAPIClient()\nschema = client.get('http://testserver/schema/')\n\n# Create a new organization\nparams = {'name': 'MegaCorp', 'status': 'active'}\nclient.action(schema, ['organizations', 'create'], params)\n\n# Ensure that the organization exists in the listing\ndata = client.action(schema, ['organizations', 'list'])\nassert(len(data) == 1)\nassert(data == [{'name': 'MegaCorp', 'status': 'active'}])\n"},{"location":"api-guide/testing/#headers-authentication_1","title":"Headers & Authentication","text":"Custom headers and authentication may be used with CoreAPIClient in a similar way as with RequestsClient.
from requests.auth import HTTPBasicAuth\n\nclient = CoreAPIClient()\nclient.session.auth = HTTPBasicAuth('user', 'pass')\nclient.session.headers.update({'x-test': 'true'})\n"},{"location":"api-guide/testing/#api-test-cases","title":"API Test cases","text":"REST framework includes the following test case classes, that mirror the existing Django's test case classes, but use APIClient instead of Django's default Client.
APISimpleTestCaseAPITransactionTestCaseAPITestCaseAPILiveServerTestCaseYou can use any of REST framework's test case classes as you would for the regular Django test case classes. The self.client attribute will be an APIClient instance.
from django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom myproject.apps.core.models import Account\n\nclass AccountTests(APITestCase):\n def test_create_account(self):\n \"\"\"\n Ensure we can create a new account object.\n \"\"\"\n url = reverse('account-list')\n data = {'name': 'DabApps'}\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(Account.objects.count(), 1)\n self.assertEqual(Account.objects.get().name, 'DabApps')\n"},{"location":"api-guide/testing/#urlpatternstestcase","title":"URLPatternsTestCase","text":"REST framework also provides a test case class for isolating urlpatterns on a per-class basis. Note that this inherits from Django's SimpleTestCase, and will most likely need to be mixed with another test case class.
from django.urls import include, path, reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase, URLPatternsTestCase\n\n\nclass AccountTests(APITestCase, URLPatternsTestCase):\n urlpatterns = [\n path('api/', include('api.urls')),\n ]\n\n def test_create_account(self):\n \"\"\"\n Ensure we can create a new account object.\n \"\"\"\n url = reverse('account-list')\n response = self.client.get(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data), 1)\n"},{"location":"api-guide/testing/#testing-responses","title":"Testing responses","text":""},{"location":"api-guide/testing/#checking-the-response-data","title":"Checking the response data","text":"When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.
For example, it's easier to inspect response.data:
response = self.client.get('/users/4/')\nself.assertEqual(response.data, {'id': 4, 'username': 'lauren'})\n Instead of inspecting the result of parsing response.content:
response = self.client.get('/users/4/')\nself.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})\n"},{"location":"api-guide/testing/#rendering-responses","title":"Rendering responses","text":"If you're testing views directly using APIRequestFactory, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access response.content, you'll first need to render the response.
view = UserDetail.as_view()\nrequest = factory.get('/users/4')\nresponse = view(request, pk='4')\nresponse.render() # Cannot access `response.content` without this.\nself.assertEqual(response.content, '{\"username\": \"lauren\", \"id\": 4}')\n"},{"location":"api-guide/testing/#configuration","title":"Configuration","text":""},{"location":"api-guide/testing/#setting-the-default-format","title":"Setting the default format","text":"The default format used to make test requests may be set using the TEST_REQUEST_DEFAULT_FORMAT setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your settings.py file:
REST_FRAMEWORK = {\n ...\n 'TEST_REQUEST_DEFAULT_FORMAT': 'json'\n}\n"},{"location":"api-guide/testing/#setting-the-available-formats","title":"Setting the available formats","text":"If you need to test requests using something other than multipart or json requests, you can do so by setting the TEST_REQUEST_RENDERER_CLASSES setting.
For example, to add support for using format='html' in test requests, you might have something like this in your settings.py file.
REST_FRAMEWORK = {\n ...\n 'TEST_REQUEST_RENDERER_CLASSES': [\n 'rest_framework.renderers.MultiPartRenderer',\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.TemplateHTMLRenderer'\n ]\n}\n"},{"location":"api-guide/throttling/","title":"Throttling","text":"HTTP/1.1 420 Enhance Your Calm
Twitter API rate limiting response
Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.
As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.
Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.
Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.
The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.
"},{"location":"api-guide/throttling/#how-throttling-is-determined","title":"How throttling is determined","text":"As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
Before running the main body of the view each throttle in the list is checked. If any throttle check fails an exceptions.Throttled exception will be raised, and the main body of the view will not run.
The default throttling policy may be set globally, using the DEFAULT_THROTTLE_CLASSES and DEFAULT_THROTTLE_RATES settings. For example.
REST_FRAMEWORK = {\n 'DEFAULT_THROTTLE_CLASSES': [\n 'rest_framework.throttling.AnonRateThrottle',\n 'rest_framework.throttling.UserRateThrottle'\n ],\n 'DEFAULT_THROTTLE_RATES': {\n 'anon': '100/day',\n 'user': '1000/day'\n }\n}\n The rates used in DEFAULT_THROTTLE_RATES can be specified over a period of second, minute, hour or day. The period must be specified after the / separator using s, m, h or d, respectively. For increased clarity, extended units such as second, minute, hour, day or even abbreviations like sec, min, hr are allowed, as only the first character is relevant to identify the rate.
You can also set the throttling policy on a per-view or per-viewset basis, using the APIView class-based views.
from rest_framework.response import Response\nfrom rest_framework.throttling import UserRateThrottle\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n throttle_classes = [UserRateThrottle]\n\n def get(self, request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n If you're using the @api_view decorator with function based views you can use the following decorator.
@api_view(['GET'])\n@throttle_classes([UserRateThrottle])\ndef example_view(request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n It's also possible to set throttle classes for routes that are created using the @action decorator. Throttle classes set in this way will override any viewset level class settings.
@action(detail=True, methods=[\"post\"], throttle_classes=[UserRateThrottle])\ndef example_adhoc_method(request, pk=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content)\n"},{"location":"api-guide/throttling/#how-clients-are-identified","title":"How clients are identified","text":"The X-Forwarded-For HTTP header and REMOTE_ADDR WSGI variable are used to uniquely identify client IP addresses for throttling. If the X-Forwarded-For header is present then it will be used, otherwise the value of the REMOTE_ADDR variable from the WSGI environment will be used.
If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the NUM_PROXIES setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the X-Forwarded-For header, once any application proxy IP addresses have first been excluded. If set to zero, then the REMOTE_ADDR value will always be used as the identifying IP address.
It is important to understand that if you configure the NUM_PROXIES setting, then all clients behind a unique NAT'd gateway will be treated as a single client.
Further context on how the X-Forwarded-For header works, and identifying a remote client IP can be found here.
The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate cache settings. The default value of LocMemCache backend should be okay for simple setups. See Django's cache documentation for more details.
If you need to use a cache other than 'default', you can do so by creating a custom throttle class and setting the cache attribute. For example:
from django.core.cache import caches\n\nclass CustomAnonRateThrottle(AnonRateThrottle):\n cache = caches['alternate']\n You'll need to remember to also set your custom throttle class in the 'DEFAULT_THROTTLE_CLASSES' settings key, or using the throttle_classes view attribute.
The built-in throttle implementations are open to race conditions, so under high concurrency they may allow a few extra requests through.
If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class. See issue #5181 for more details.
"},{"location":"api-guide/throttling/#api-reference","title":"API Reference","text":""},{"location":"api-guide/throttling/#anonratethrottle","title":"AnonRateThrottle","text":"The AnonRateThrottle will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
The allowed request rate is determined from one of the following (in order of preference).
rate property on the class, which may be provided by overriding AnonRateThrottle and setting the property.DEFAULT_THROTTLE_RATES['anon'] setting.AnonRateThrottle is suitable if you want to restrict the rate of requests from unknown sources.
The UserRateThrottle will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.
The allowed request rate is determined from one of the following (in order of preference).
rate property on the class, which may be provided by overriding UserRateThrottle and setting the property.DEFAULT_THROTTLE_RATES['user'] setting.An API may have multiple UserRateThrottles in place at the same time. To do so, override UserRateThrottle and set a unique \"scope\" for each class.
For example, multiple user throttle rates could be implemented by using the following classes...
class BurstRateThrottle(UserRateThrottle):\n scope = 'burst'\n\nclass SustainedRateThrottle(UserRateThrottle):\n scope = 'sustained'\n ...and the following settings.
REST_FRAMEWORK = {\n 'DEFAULT_THROTTLE_CLASSES': [\n 'example.throttles.BurstRateThrottle',\n 'example.throttles.SustainedRateThrottle'\n ],\n 'DEFAULT_THROTTLE_RATES': {\n 'burst': '60/min',\n 'sustained': '1000/day'\n }\n}\n UserRateThrottle is suitable if you want simple global rate restrictions per-user.
The ScopedRateThrottle class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a .throttle_scope property. The unique throttle key will then be formed by concatenating the \"scope\" of the request with the unique user id or IP address.
The allowed request rate is determined by the DEFAULT_THROTTLE_RATES setting using a key from the request \"scope\".
For example, given the following views...
class ContactListView(APIView):\n throttle_scope = 'contacts'\n ...\n\nclass ContactDetailView(APIView):\n throttle_scope = 'contacts'\n ...\n\nclass UploadView(APIView):\n throttle_scope = 'uploads'\n ...\n ...and the following settings.
REST_FRAMEWORK = {\n 'DEFAULT_THROTTLE_CLASSES': [\n 'rest_framework.throttling.ScopedRateThrottle',\n ],\n 'DEFAULT_THROTTLE_RATES': {\n 'contacts': '1000/day',\n 'uploads': '20/day'\n }\n}\n User requests to either ContactListView or ContactDetailView would be restricted to a total of 1000 requests per-day. User requests to UploadView would be restricted to 20 requests per day.
To create a custom throttle, override BaseThrottle and implement .allow_request(self, request, view). The method should return True if the request should be allowed, and False otherwise.
Optionally you may also override the .wait() method. If implemented, .wait() should return a recommended number of seconds to wait before attempting the next request, or None. The .wait() method will only be called if .allow_request() has previously returned False.
If the .wait() method is implemented and the request is throttled, then a Retry-After header will be included in the response.
The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
import random\n\nclass RandomRateThrottle(throttling.BaseThrottle):\n def allow_request(self, request, view):\n return random.randint(1, 10) != 1\n"},{"location":"api-guide/validators/","title":"Validators","text":"Validators can be useful for reusing validation logic between different types of fields.
\u2014 Django documentation
Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.
However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
"},{"location":"api-guide/validators/#validation-in-rest-framework","title":"Validation in REST framework","text":"Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class.
With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
ModelSerializer classes and using explicit Serializer classes. Any validation behavior being used for ModelSerializer is simple to replicate.repr of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.When you're using ModelSerializer all of this is handled automatically for you. If you want to drop down to using Serializer classes instead, then you need to define the validation rules explicitly.
As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.
class CustomerReportRecord(models.Model):\n time_raised = models.DateTimeField(default=timezone.now, editable=False)\n reference = models.CharField(unique=True, max_length=20)\n description = models.TextField()\n Here's a basic ModelSerializer that we can use for creating or updating instances of CustomerReportRecord:
class CustomerReportSerializer(serializers.ModelSerializer):\n class Meta:\n model = CustomerReportRecord\n If we open up the Django shell using manage.py shell we can now
>>> from project.example.serializers import CustomerReportSerializer\n>>> serializer = CustomerReportSerializer()\n>>> print(repr(serializer))\nCustomerReportSerializer():\n id = IntegerField(label='ID', read_only=True)\n time_raised = DateTimeField(read_only=True)\n reference = CharField(max_length=20, validators=[UniqueValidator(queryset=CustomerReportRecord.objects.all())])\n description = CharField(style={'type': 'textarea'})\n The interesting bit here is the reference field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.
Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. REST framework validators, like their Django counterparts, implement the __eq__ method, allowing you to compare instances for equality.
This validator can be used to enforce the unique=True constraint on model fields. It takes a single required argument, and an optional messages argument:
queryset required - This is the queryset against which uniqueness should be enforced.message - The error message that should be used when validation fails.lookup - The lookup used to find an existing instance with the value being validated. Defaults to 'exact'.This validator should be applied to serializer fields, like so:
from rest_framework.validators import UniqueValidator\n\nslug = SlugField(\n max_length=100,\n validators=[UniqueValidator(queryset=BlogPost.objects.all())]\n)\n"},{"location":"api-guide/validators/#uniquetogethervalidator","title":"UniqueTogetherValidator","text":"This validator can be used to enforce unique_together constraints on model instances. It has two required arguments, and a single optional messages argument:
queryset required - This is the queryset against which uniqueness should be enforced.fields required - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.message - The error message that should be used when validation fails.The validator should be applied to serializer classes, like so:
from rest_framework.validators import UniqueTogetherValidator\n\nclass ExampleSerializer(serializers.Serializer):\n # ...\n class Meta:\n # ToDo items belong to a parent list, and have an ordering defined\n # by the 'position' field. No two items in a given list may share\n # the same position.\n validators = [\n UniqueTogetherValidator(\n queryset=ToDoItem.objects.all(),\n fields=['list', 'position']\n )\n ]\n Note
The UniqueTogetherValidator class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.
These validators can be used to enforce the unique_for_date, unique_for_month and unique_for_year constraints on model instances. They take the following arguments:
queryset required - This is the queryset against which uniqueness should be enforced.field required - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.date_field required - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.message - The error message that should be used when validation fails.The validator should be applied to serializer classes, like so:
from rest_framework.validators import UniqueForYearValidator\n\nclass ExampleSerializer(serializers.Serializer):\n # ...\n class Meta:\n # Blog posts should have a slug that is unique for the current year.\n validators = [\n UniqueForYearValidator(\n queryset=BlogPostItem.objects.all(),\n field='slug',\n date_field='published'\n )\n ]\n The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class default=..., because the value being used for the default wouldn't be generated until after the validation has run.
There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using ModelSerializer you'll probably simply rely on the defaults that REST framework generates for you, but if you are using Serializer or simply want more explicit control, use on of the styles demonstrated below.
If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a default argument, or by setting required=True.
published = serializers.DateTimeField(required=True)\n"},{"location":"api-guide/validators/#using-with-a-read-only-date-field","title":"Using with a read-only date field.","text":"If you want the date field to be visible, but not editable by the user, then set read_only=True and additionally set a default=... argument.
published = serializers.DateTimeField(read_only=True, default=timezone.now)\n"},{"location":"api-guide/validators/#using-with-a-hidden-date-field","title":"Using with a hidden date field.","text":"If you want the date field to be entirely hidden from the user, then use HiddenField. This field type does not accept user input, but instead always returns its default value to the validated_data in the serializer.
published = serializers.HiddenField(default=timezone.now)\n Note
The UniqueFor<Range>Validator classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.
Note
HiddenField() does not appear in partial=True serializer (when making PATCH request).
Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that is available as input to the validator. For this purposes use HiddenField. This field will be present in validated_data but will not be used in the serializer output representation.
Note
Using a read_only=True field is excluded from writable fields so it won't use a default=\u2026 argument. Look 3.8 announcement.
REST framework includes a couple of defaults that may be useful in this context.
"},{"location":"api-guide/validators/#currentuserdefault","title":"CurrentUserDefault","text":"A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.
owner = serializers.HiddenField(\n default=serializers.CurrentUserDefault()\n)\n"},{"location":"api-guide/validators/#createonlydefault","title":"CreateOnlyDefault","text":"A default class that can be used to only set a default argument during create operations. During updates the field is omitted.
It takes a single argument, which is the default value or callable that should be used during create operations.
created_at = serializers.DateTimeField(\n default=serializers.CreateOnlyDefault(timezone.now)\n)\n"},{"location":"api-guide/validators/#limitations-of-validators","title":"Limitations of validators","text":"There are some ambiguous cases where you'll need to instead handle validation explicitly, rather than relying on the default serializer classes that ModelSerializer generates.
In these cases you may want to disable the automatically generated validators, by specifying an empty list for the serializer Meta.validators attribute.
By default \"unique together\" validation enforces that all fields be required=True. In some cases, you might want to explicit apply required=False to one of the fields, in which case the desired behavior of the validation is ambiguous.
In this case you will typically need to exclude the validator from the 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):\n def validate(self, attrs):\n # Apply custom validation either here, or in the view.\n\n class Meta:\n fields = ['client', 'date', 'amount']\n extra_kwargs = {'client': {'required': False}}\n validators = [] # Remove a default \"unique together\" constraint.\n"},{"location":"api-guide/validators/#updating-nested-serializers","title":"Updating nested serializers","text":"When applying an update to an existing instance, uniqueness validators will exclude the current instance from the uniqueness check. The current instance is available in the context of the uniqueness check, because it exists as an attribute on the serializer, having initially been passed using instance=... when instantiating the serializer.
In the case of update operations on nested serializers there's no way of applying this exclusion, because the instance is not available.
Again, you'll probably want to explicitly remove the validator from the serializer class, and write the code for the validation constraint explicitly, in a .validate() method, or in the view.
If you're not sure exactly what behavior a ModelSerializer class will generate it is usually a good idea to run manage.py shell, and print an instance of the serializer, so that you can inspect the fields and validators that it automatically generates for you.
>>> serializer = MyComplexModelSerializer()\n>>> print(serializer)\nclass MyComplexModelSerializer:\n my_fields = ...\n Also keep in mind that with complex cases it can often be better to explicitly define your serializer classes, rather than relying on the default ModelSerializer behavior. This involves a little more code, but ensures that the resulting behavior is more transparent.
You can use any of Django's existing validators, or write your own custom validators.
"},{"location":"api-guide/validators/#function-based","title":"Function based","text":"A validator may be any callable that raises a serializers.ValidationError on failure.
def even_number(value):\n if value % 2 != 0:\n raise serializers.ValidationError('This field must be an even number.')\n"},{"location":"api-guide/validators/#field-level-validation","title":"Field-level validation","text":"You can specify custom field-level validation by adding .validate_<field_name> methods to your Serializer subclass. This is documented in the Serializer docs
To write a class-based validator, use the __call__ method. Class-based validators are useful as they allow you to parameterize and reuse behavior.
class MultipleOf:\n def __init__(self, base):\n self.base = base\n\n def __call__(self, value):\n if value % self.base != 0:\n message = 'This field must be a multiple of %d.' % self.base\n raise serializers.ValidationError(message)\n"},{"location":"api-guide/validators/#accessing-the-context","title":"Accessing the context","text":"In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by setting a requires_context = True attribute on the validator class. The __call__ method will then be called with the serializer_field or serializer as an additional argument.
class MultipleOf:\n requires_context = True\n\n def __call__(self, value, serializer_field):\n ...\n"},{"location":"api-guide/versioning/","title":"Versioning","text":"Versioning an interface is just a \"polite\" way to kill deployed clients.
\u2014 Roy Fielding.
API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes.
Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers.
There are a number of valid approaches to approaching versioning. Non-versioned systems can also be appropriate, particularly if you're engineering for very long-term systems with multiple clients outside of your control.
"},{"location":"api-guide/versioning/#versioning-with-rest-framework","title":"Versioning with REST framework","text":"When API versioning is enabled, the request.version attribute will contain a string that corresponds to the version requested in the incoming client request.
By default, versioning is not enabled, and request.version will always return None.
How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example:
def get_serializer_class(self):\n if self.request.version == 'v1':\n return AccountSerializerVersion1\n return AccountSerializer\n"},{"location":"api-guide/versioning/#reversing-urls-for-versioned-apis","title":"Reversing URLs for versioned APIs","text":"The reverse function included by REST framework ties in with the versioning scheme. You need to make sure to include the current request as a keyword argument, like so.
from rest_framework.reverse import reverse\n\nreverse('bookings-list', request=request)\n The above function will apply any URL transformations appropriate to the request version. For example:
NamespaceVersioning was being used, and the API version was 'v1', then the URL lookup used would be 'v1:bookings-list', which might resolve to a URL like http://example.org/v1/bookings/.QueryParameterVersioning was being used, and the API version was 1.0, then the returned URL might be something like http://example.org/bookings/?version=1.0When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer.
def get(self, request):\n queryset = Booking.objects.all()\n serializer = BookingsSerializer(queryset, many=True, context={'request': request})\n return Response({'all_bookings': serializer.data})\n Doing so will allow any returned URLs to include the appropriate versioning.
"},{"location":"api-guide/versioning/#configuring-the-versioning-scheme","title":"Configuring the versioning scheme","text":"The versioning scheme is defined by the DEFAULT_VERSIONING_CLASS settings key.
REST_FRAMEWORK = {\n 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'\n}\n Unless it is explicitly set, the value for DEFAULT_VERSIONING_CLASS will be None. In this case the request.version attribute will always return None.
You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the versioning_class attribute.
class ProfileList(APIView):\n versioning_class = versioning.QueryParameterVersioning\n"},{"location":"api-guide/versioning/#other-versioning-settings","title":"Other versioning settings","text":"The following settings keys are also used to control versioning:
DEFAULT_VERSION. The value that should be used for request.version when no versioning information is present. Defaults to None.ALLOWED_VERSIONS. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version is not in this set. Note that the value used for the DEFAULT_VERSION setting is always considered to be part of the ALLOWED_VERSIONS set (unless it is None). Defaults to None.VERSION_PARAM. The string that should be used for any versioning parameters, such as in the media type or URL query parameters. Defaults to 'version'.You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the default_version, allowed_versions and version_param class variables. For example, if you want to use URLPathVersioning:
from rest_framework.versioning import URLPathVersioning\nfrom rest_framework.views import APIView\n\nclass ExampleVersioning(URLPathVersioning):\n default_version = ...\n allowed_versions = ...\n version_param = ...\n\nclass ExampleView(APIVIew):\n versioning_class = ExampleVersioning\n"},{"location":"api-guide/versioning/#api-reference","title":"API Reference","text":""},{"location":"api-guide/versioning/#acceptheaderversioning","title":"AcceptHeaderVersioning","text":"This scheme requires the client to specify the version as part of the media type in the Accept header. The version is included as a media type parameter, that supplements the main media type.
Here's an example HTTP request using the accept header versioning style.
GET /bookings/ HTTP/1.1\nHost: example.com\nAccept: application/json; version=1.0\n In the example request above request.version attribute would return the string '1.0'.
Versioning based on accept headers is generally considered as best practice, although other styles may be suitable depending on your client requirements.
"},{"location":"api-guide/versioning/#using-accept-headers-with-vendor-media-types","title":"Using accept headers with vendor media types","text":"Strictly speaking the json media type is not specified as including additional parameters. If you are building a well-specified public API you might consider using a vendor media type. To do so, configure your renderers to use a JSON based renderer with a custom media type:
class BookingsAPIRenderer(JSONRenderer):\n media_type = 'application/vnd.megacorp.bookings+json'\n Your client requests would now look like this:
GET /bookings/ HTTP/1.1\nHost: example.com\nAccept: application/vnd.megacorp.bookings+json; version=1.0\n"},{"location":"api-guide/versioning/#urlpathversioning","title":"URLPathVersioning","text":"This scheme requires the client to specify the version as part of the URL path.
GET /v1/bookings/ HTTP/1.1\nHost: example.com\nAccept: application/json\n Your URL conf must include a pattern that matches the version with a 'version' keyword argument, so that this information is available to the versioning scheme.
urlpatterns = [\n re_path(\n r'^(?P<version>(v1|v2))/bookings/$',\n bookings_list,\n name='bookings-list'\n ),\n re_path(\n r'^(?P<version>(v1|v2))/bookings/(?P<pk>[0-9]+)/$',\n bookings_detail,\n name='bookings-detail'\n )\n]\n"},{"location":"api-guide/versioning/#namespaceversioning","title":"NamespaceVersioning","text":"To the client, this scheme is the same as URLPathVersioning. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.
GET /v1/something/ HTTP/1.1\nHost: example.com\nAccept: application/json\n With this scheme the request.version attribute is determined based on the namespace that matches the incoming request path.
In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace:
# bookings/urls.py\nurlpatterns = [\n re_path(r'^$', bookings_list, name='bookings-list'),\n re_path(r'^(?P<pk>[0-9]+)/$', bookings_detail, name='bookings-detail')\n]\n\n# urls.py\nurlpatterns = [\n re_path(r'^v1/bookings/', include('bookings.urls', namespace='v1')),\n re_path(r'^v2/bookings/', include('bookings.urls', namespace='v2'))\n]\n Both URLPathVersioning and NamespaceVersioning are reasonable if you just need a simple versioning scheme. The URLPathVersioning approach might be better suitable for small ad-hoc projects, and the NamespaceVersioning is probably easier to manage for larger projects.
The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL.
For example the following is an HTTP request to the http://v1.example.com/bookings/ URL:
GET /bookings/ HTTP/1.1\nHost: v1.example.com\nAccept: application/json\n By default this implementation expects the hostname to match this simple regular expression:
^([a-zA-Z0-9]+)\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+$\n Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.
The HostNameVersioning scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as 127.0.0.1. There are various online tutorials on how to access localhost with a custom subdomain which you may find helpful in this case.
Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions.
"},{"location":"api-guide/versioning/#queryparameterversioning","title":"QueryParameterVersioning","text":"This scheme is a simple style that includes the version as a query parameter in the URL. For example:
GET /something/?version=0.1 HTTP/1.1\nHost: example.com\nAccept: application/json\n"},{"location":"api-guide/versioning/#custom-versioning-schemes","title":"Custom versioning schemes","text":"To implement a custom versioning scheme, subclass BaseVersioning and override the .determine_version method.
The following example uses a custom X-API-Version header to determine the requested version.
class XAPIVersionScheme(versioning.BaseVersioning):\n def determine_version(self, request, *args, **kwargs):\n return request.META.get('HTTP_X_API_VERSION', None)\n If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the .reverse() method on the class. See the source code for examples.
Django's class-based views are a welcome departure from the old-style views.
\u2014 Reinout van Rees
REST framework provides an APIView class, which subclasses Django's View class.
APIView classes are different from regular View classes in the following ways:
Request instances, not Django's HttpRequest instances.Response, instead of Django's HttpResponse. The view will manage content negotiation and setting the correct renderer on the response.APIException exceptions will be caught and mediated into appropriate responses.Using the APIView class is pretty much the same as using a regular View class, as usual, the incoming request is dispatched to an appropriate handler method such as .get() or .post(). Additionally, a number of attributes may be set on the class that control various aspects of the API policy.
For example:
from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import authentication, permissions\nfrom django.contrib.auth.models import User\n\nclass ListUsers(APIView):\n \"\"\"\n View to list all users in the system.\n\n * Requires token authentication.\n * Only admin users are able to access this view.\n \"\"\"\n authentication_classes = [authentication.TokenAuthentication]\n permission_classes = [permissions.IsAdminUser]\n\n def get(self, request, format=None):\n \"\"\"\n Return a list of all users.\n \"\"\"\n usernames = [user.username for user in User.objects.all()]\n return Response(usernames)\n Note
The full methods, attributes on, and relations between Django REST Framework's APIView, GenericAPIView, various Mixins, and Viewsets can be initially complex. In addition to the documentation here, the Classy Django REST Framework resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views.
The following attributes control the pluggable aspects of API views.
"},{"location":"api-guide/views/#renderer_classes","title":".renderer_classes","text":""},{"location":"api-guide/views/#parser_classes","title":".parser_classes","text":""},{"location":"api-guide/views/#authentication_classes","title":".authentication_classes","text":""},{"location":"api-guide/views/#throttle_classes","title":".throttle_classes","text":""},{"location":"api-guide/views/#permission_classes","title":".permission_classes","text":""},{"location":"api-guide/views/#content_negotiation_class","title":".content_negotiation_class","text":""},{"location":"api-guide/views/#api-policy-instantiation-methods","title":"API policy instantiation methods","text":"The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.
"},{"location":"api-guide/views/#get_renderersself","title":".get_renderers(self)","text":""},{"location":"api-guide/views/#get_parsersself","title":".get_parsers(self)","text":""},{"location":"api-guide/views/#get_authenticatorsself","title":".get_authenticators(self)","text":""},{"location":"api-guide/views/#get_throttlesself","title":".get_throttles(self)","text":""},{"location":"api-guide/views/#get_permissionsself","title":".get_permissions(self)","text":""},{"location":"api-guide/views/#get_content_negotiatorself","title":".get_content_negotiator(self)","text":""},{"location":"api-guide/views/#get_exception_handlerself","title":".get_exception_handler(self)","text":""},{"location":"api-guide/views/#api-policy-implementation-methods","title":"API policy implementation methods","text":"The following methods are called before dispatching to the handler method.
"},{"location":"api-guide/views/#check_permissionsself-request","title":".check_permissions(self, request)","text":""},{"location":"api-guide/views/#check_throttlesself-request","title":".check_throttles(self, request)","text":""},{"location":"api-guide/views/#perform_content_negotiationself-request-forcefalse","title":".perform_content_negotiation(self, request, force=False)","text":""},{"location":"api-guide/views/#dispatch-methods","title":"Dispatch methods","text":"The following methods are called directly by the view's .dispatch() method. These perform any actions that need to occur before or after calling the handler methods such as .get(), .post(), put(), patch() and .delete().
Performs any actions that need to occur before the handler method gets called. This method is used to enforce permissions and throttling, and perform content negotiation.
You won't typically need to override this method.
"},{"location":"api-guide/views/#handle_exceptionself-exc","title":".handle_exception(self, exc)","text":"Any exception thrown by the handler method will be passed to this method, which either returns a Response instance, or re-raises the exception.
The default implementation handles any subclass of rest_framework.exceptions.APIException, as well as Django's Http404 and PermissionDenied exceptions, and returns an appropriate error response.
If you need to customize the error responses your API returns you should subclass this method.
"},{"location":"api-guide/views/#initialize_requestself-request-args-kwargs","title":".initialize_request(self, request, *args, **kwargs)","text":"Ensures that the request object that is passed to the handler method is an instance of Request, rather than the usual Django HttpRequest.
You won't typically need to override this method.
"},{"location":"api-guide/views/#finalize_responseself-request-response-args-kwargs","title":".finalize_response(self, request, response, *args, **kwargs)","text":"Ensures that any Response object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.
You won't typically need to override this method.
"},{"location":"api-guide/views/#function-based-views","title":"Function Based Views","text":"Saying [that class-based views] is always the superior solution is a mistake.
\u2014 Nick Coghlan
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of Request (rather than the usual Django HttpRequest) and allows them to return a Response (instead of a Django HttpResponse), and allow you to configure how the request is processed.
Signature: @api_view(http_method_names=['GET'])
The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\n@api_view()\ndef hello_world(request):\n return Response({\"message\": \"Hello, world!\"})\n This view will use the default renderers, parsers, authentication classes etc specified in the settings.
By default only GET methods will be accepted. Other methods will respond with \"405 Method Not Allowed\". To alter this behavior, specify which methods the view allows, like so:
@api_view(['GET', 'POST'])\ndef hello_world(request):\n if request.method == 'POST':\n return Response({\"message\": \"Got some data!\", \"data\": request.data})\n return Response({\"message\": \"Hello, world!\"})\n"},{"location":"api-guide/views/#api-policy-decorators","title":"API policy decorators","text":"To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come after (below) the @api_view decorator. For example, to create a view that uses a throttle to ensure it can only be called once per day by a particular user, use the @throttle_classes decorator, passing a list of throttle classes:
from rest_framework.decorators import api_view, throttle_classes\nfrom rest_framework.throttling import UserRateThrottle\n\nclass OncePerDayUserThrottle(UserRateThrottle):\n rate = '1/day'\n\n@api_view(['GET'])\n@throttle_classes([OncePerDayUserThrottle])\ndef view(request):\n return Response({\"message\": \"Hello for today! See you tomorrow!\"})\n These decorators correspond to the attributes set on APIView subclasses, described above.
The available decorators are:
@renderer_classes(...)@parser_classes(...)@authentication_classes(...)@throttle_classes(...)@permission_classes(...)@content_negotiation_class(...)@metadata_class(...)@versioning_class(...)Each of these decorators is equivalent to setting their respective api policy attributes.
All decorators take a single argument. The ones that end with _class expect a single class while the ones ending in _classes expect a list or tuple of classes.
To override the default schema generation for function based views you may use the @schema decorator. This must come after (below) the @api_view decorator. For example:
from rest_framework.decorators import api_view, schema\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomAutoSchema(AutoSchema):\n def get_link(self, path, method, base_url):\n # override view introspection here...\n\n@api_view(['GET'])\n@schema(CustomAutoSchema())\ndef view(request):\n return Response({\"message\": \"Hello for today! See you tomorrow!\"})\n This decorator takes a single AutoSchema instance, an AutoSchema subclass instance or ManualSchema instance as described in the Schemas documentation. You may pass None in order to exclude the view from schema generation.
@api_view(['GET'])\n@schema(None)\ndef view(request):\n return Response({\"message\": \"Will not appear in schema!\"})\n"},{"location":"api-guide/viewsets/","title":"ViewSets","text":"After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.
\u2014 Ruby on Rails Documentation
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().
The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.
Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.
"},{"location":"api-guide/viewsets/#example","title":"Example","text":"Let's define a simple viewset that can be used to list or retrieve all the users in the system.
from django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404\nfrom myapps.serializers import UserSerializer\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nclass UserViewSet(viewsets.ViewSet):\n \"\"\"\n A simple ViewSet for listing or retrieving users.\n \"\"\"\n def list(self, request):\n queryset = User.objects.all()\n serializer = UserSerializer(queryset, many=True)\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None):\n queryset = User.objects.all()\n user = get_object_or_404(queryset, pk=pk)\n serializer = UserSerializer(user)\n return Response(serializer.data)\n If we need to, we can bind this viewset into two separate views, like so:
user_list = UserViewSet.as_view({'get': 'list'})\nuser_detail = UserViewSet.as_view({'get': 'retrieve'})\n Warning
Do not use .as_view() with @action methods. It bypasses router setup and may ignore action settings like permission_classes. Use DefaultRouter for actions.
Typically, we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.
from myapp.views import UserViewSet\nfrom rest_framework.routers import DefaultRouter\n\nrouter = DefaultRouter()\nrouter.register(r'users', UserViewSet, basename='user')\nurlpatterns = router.urls\n Warning
When registering viewsets, do not include a trailing slash in the prefix (e.g., use r'users', not r'users/'). Unlike standard Django URL patterns, DRF routers append slashes automatically based on your trailing slash configuration.
Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:
class UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset for viewing and editing user instances.\n \"\"\"\n serializer_class = UserSerializer\n queryset = User.objects.all()\n There are two main advantages of using a ViewSet class over using a View class.
queryset once, and it'll be used across multiple views.Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
"},{"location":"api-guide/viewsets/#viewset-actions","title":"ViewSet actions","text":"The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
class UserViewSet(viewsets.ViewSet):\n \"\"\"\n Example empty viewset demonstrating the standard\n actions that will be handled by a router class.\n\n If you're using format suffixes, make sure to also include\n the `format=None` keyword argument for each action.\n \"\"\"\n\n def list(self, request):\n pass\n\n def create(self, request):\n pass\n\n def retrieve(self, request, pk=None):\n pass\n\n def update(self, request, pk=None):\n pass\n\n def partial_update(self, request, pk=None):\n pass\n\n def destroy(self, request, pk=None):\n pass\n"},{"location":"api-guide/viewsets/#introspecting-viewset-actions","title":"Introspecting ViewSet actions","text":"During dispatch, the following attributes are available on the ViewSet.
basename - the base to use for the URL names that are created.action - the name of the current action (e.g., list, create).detail - boolean indicating if the current action is configured for a list or detail view.suffix - the display suffix for the viewset type - mirrors the detail attribute.name - the display name for the viewset. This argument is mutually exclusive to suffix.description - the display description for the individual view of a viewset.You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the list action similar to this:
def get_permissions(self):\n \"\"\"\n Instantiates and returns the list of permissions that this view requires.\n \"\"\"\n if self.action == 'list':\n permission_classes = [IsAuthenticated]\n else:\n permission_classes = [IsAdminUser]\n return [permission() for permission in permission_classes]\n Note
The action attribute is not available in the get_parsers, get_authenticators and get_content_negotiator methods, as it is set after they are called in the framework lifecycle. If you override one of these methods and try to access the action attribute in them, you will get an AttributeError error.
If you have ad-hoc methods that should be routable, you can mark them as such with the @action decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the detail argument to True or False. The router will configure its URL patterns accordingly. e.g., the DefaultRouter will configure detail actions to contain pk in their URL patterns.
A more complete example of extra actions:
from django.contrib.auth.models import User\nfrom rest_framework import status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom myapp.serializers import UserSerializer, PasswordSerializer\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n A viewset that provides the standard actions\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n @action(detail=True, methods=['post'])\n def set_password(self, request, pk=None):\n user = self.get_object()\n serializer = PasswordSerializer(data=request.data)\n if serializer.is_valid():\n user.set_password(serializer.validated_data['password'])\n user.save()\n return Response({'status': 'password set'})\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=False)\n def recent_users(self, request):\n recent_users = User.objects.all().order_by('-last_login')\n\n page = self.paginate_queryset(recent_users)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(recent_users, many=True)\n return Response(serializer.data)\n The action decorator will route GET requests by default, but may also accept other HTTP methods by setting the methods argument. For example:
@action(detail=True, methods=['post', 'delete'])\n def unset_password(self, request, pk=None):\n ...\n Argument methods also supports HTTP methods defined as HTTPMethod. Example below is identical to the one above:
from http import HTTPMethod\n\n @action(detail=True, methods=[HTTPMethod.POST, HTTPMethod.DELETE])\n def unset_password(self, request, pk=None):\n ...\n The decorator allows you to override any viewset-level configuration such as permission_classes, serializer_class, filter_backends...:
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ...\n The two new actions will then be available at the urls ^users/{pk}/set_password/$ and ^users/{pk}/unset_password/$. Use the url_path and url_name parameters to change the URL segment and the reverse URL name of the action.
To view all extra actions, call the .get_extra_actions() method.
Extra actions can map additional HTTP methods to separate ViewSet methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.
@action(detail=True, methods=[\"put\"], name=\"Change Password\")\ndef password(self, request, pk=None):\n \"\"\"Update the user's password.\"\"\"\n ...\n\n\n@password.mapping.delete\ndef delete_password(self, request, pk=None):\n \"\"\"Delete the user's password.\"\"\"\n ...\n"},{"location":"api-guide/viewsets/#reversing-action-urls","title":"Reversing action URLs","text":"If you need to get the URL of an action, use the .reverse_action() method. This is a convenience wrapper for reverse(), automatically passing the view's request object and prepending the url_name with the .basename attribute.
Note that the basename is provided by the router during ViewSet registration. If you are not using a router, then you must provide the basename argument to the .as_view() method.
Using the example from the previous section:
>>> view.reverse_action(\"set-password\", args=[\"1\"])\n'http://localhost:8000/api/users/1/set_password'\n Alternatively, you can use the url_name attribute set by the @action decorator.
>>> view.reverse_action(view.set_password.url_name, args=[\"1\"])\n'http://localhost:8000/api/users/1/set_password'\n The url_name argument for .reverse_action() should match the same argument to the @action decorator. Additionally, this method can be used to reverse the default actions, such as list and create.
The ViewSet class inherits from APIView. You can use any of the standard attributes such as permission_classes, authentication_classes in order to control the API policy on the viewset.
The ViewSet class does not provide any implementations of actions. In order to use a ViewSet class you'll override the class and define the action implementations explicitly.
The GenericViewSet class inherits from GenericAPIView, and provides the default set of get_object, get_queryset methods and other generic view base behavior, but does not include any actions by default.
In order to use a GenericViewSet class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.
The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy().
Because ModelViewSet extends GenericAPIView, you'll normally need to provide at least the queryset and serializer_class attributes. For example:
class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n Note that you can use any of the standard attributes or method overrides provided by GenericAPIView. For example, to use a ViewSet that dynamically determines the queryset it should operate on, you might do something like this:
class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing the accounts\n associated with the user.\n \"\"\"\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n\n def get_queryset(self):\n return self.request.user.accounts.all()\n Note however that upon removal of the queryset property from your ViewSet, any associated router will be unable to derive the basename of your Model automatically, and so you will have to specify the basename kwarg as part of your router registration.
Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.
"},{"location":"api-guide/viewsets/#readonlymodelviewset","title":"ReadOnlyModelViewSet","text":"The ReadOnlyModelViewSet class also inherits from GenericAPIView. As with ModelViewSet it also includes implementations for various actions, but unlike ModelViewSet only provides the 'read-only' actions, .list() and .retrieve().
As with ModelViewSet, you'll normally need to provide at least the queryset and serializer_class attributes. For example:
class AccountViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A simple ViewSet for viewing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n Again, as with ModelViewSet, you can use any of the standard attributes and method overrides available to GenericAPIView.
You may need to provide custom ViewSet classes that do not have the full set of ModelViewSet actions, or that customize the behavior in some other way.
To create a base viewset class that provides create, list and retrieve operations, inherit from GenericViewSet, and mixin the required actions:
from rest_framework import mixins, viewsets\n\nclass CreateListRetrieveViewSet(mixins.CreateModelMixin,\n mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet):\n \"\"\"\n A viewset that provides `retrieve`, `create`, and `list` actions.\n\n To use it, override the class and set the `.queryset` and\n `.serializer_class` attributes.\n \"\"\"\n pass\n By creating your own base ViewSet classes, you can provide common behavior that can be reused in multiple viewsets across your API.
The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.
This release is incremental in nature. There are some breaking API changes, and upgrading will require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.
The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.
3.0 is the first of three releases that have been funded by our recent Kickstarter campaign.
As ever, a huge thank you to our many wonderful sponsors. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring.
"},{"location":"community/3.0-announcement/#new-features","title":"New features","text":"Notable features of this new release include:
ModelSerializer class and the explicit Serializer class.BaseSerializer class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.ListField and MultipleChoiceField.OPTIONS requests are handled by your API.Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two Kickstarter stretch goals - \"Feature improvements\" and \"Admin interface\". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
"},{"location":"community/3.0-announcement/#rest-framework-under-the-hood","title":"REST framework: Under the hood.","text":"This talk from the Django: Under the Hood event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.
Below is an in-depth guide to the API changes and migration notes for 3.0.
"},{"location":"community/3.0-announcement/#request-objects","title":"Request objects","text":""},{"location":"community/3.0-announcement/#the-data-and-query_params-properties","title":"The.data and .query_params properties.","text":"The usage of request.DATA and request.FILES is now pending deprecation in favor of a single request.data attribute that contains all the parsed data.
Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports.
You may now pass all the request data to a serializer class in a single argument:
# Do this...\nExampleSerializer(data=request.data)\n Instead of passing the files argument separately:
# Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES)\n The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params.
Previously the serializers used a two-step object creation, as follows:
serializer.object.serializer.save() would then save the object instance to the database.This style is in-line with how the ModelForm class works in Django, but is problematic for a number of reasons:
.save() is called.ExampleModel.objects.create(...). Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.We now use single-step object creation, like so:
serializer.validated_data.serializer.save() then saves and returns the new object instance.The resulting API changes are further detailed below.
"},{"location":"community/3.0-announcement/#the-create-and-update-methods","title":"The.create() and .update() methods.","text":"The .restore_object() method is now removed, and we instead have two separate methods, .create() and .update(). These methods work slightly different to the previous .restore_object().
When using the .create() and .update() methods you should both create and save the object instance. This is in contrast to the previous .restore_object() behavior that would instantiate the object but not save it.
These methods also replace the optional .save_object() method, which no longer exists.
The following example from the tutorial previously used restore_object() to handle both creating and updating object instances.
def restore_object(self, attrs, instance=None):\n if instance:\n # Update existing instance\n instance.title = attrs.get('title', instance.title)\n instance.code = attrs.get('code', instance.code)\n instance.linenos = attrs.get('linenos', instance.linenos)\n instance.language = attrs.get('language', instance.language)\n instance.style = attrs.get('style', instance.style)\n return instance\n\n # Create new instance\n return Snippet(**attrs)\n This would now be split out into two separate methods.
def update(self, instance, validated_data):\n instance.title = validated_data.get('title', instance.title)\n instance.code = validated_data.get('code', instance.code)\n instance.linenos = validated_data.get('linenos', instance.linenos)\n instance.language = validated_data.get('language', instance.language)\n instance.style = validated_data.get('style', instance.style)\n instance.save()\n return instance\n\ndef create(self, validated_data):\n return Snippet.objects.create(**validated_data)\n Note that these methods should return the newly created object instance.
"},{"location":"community/3.0-announcement/#use-validated_data-instead-of-object","title":"Use.validated_data instead of .object.","text":"You must now use the .validated_data attribute if you need to inspect the data before saving, rather than using the .object attribute, which no longer exists.
For example the following code is no longer valid:
if serializer.is_valid():\n name = serializer.object.name # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.object.user = request.user # Include the user when saving.\n serializer.save()\n Instead of using .object to inspect a partially constructed instance, you would now use .validated_data to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the .save() method as keyword arguments.
The corresponding code would now look like this:
if serializer.is_valid():\n name = serializer.validated_data['name'] # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.save(user=request.user) # Include the user when saving.\n"},{"location":"community/3.0-announcement/#using-is_validraise_exceptiontrue","title":"Using .is_valid(raise_exception=True)","text":"The .is_valid() method now takes an optional boolean flag, raise_exception.
Calling .is_valid(raise_exception=True) will cause a ValidationError to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code.
The handling and formatting of error responses may be altered globally by using the EXCEPTION_HANDLER settings key.
This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.
"},{"location":"community/3.0-announcement/#using-serializersvalidationerror","title":"Usingserializers.ValidationError.","text":"Previously serializers.ValidationError error was simply a synonym for django.core.exceptions.ValidationError. This has now been altered so that it inherits from the standard APIException base class.
The reason behind this is that Django's ValidationError class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers.
For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the serializers.ValidationError exception class, and not Django's built-in exception.
We strongly recommend that you use the namespaced import style of import serializers and not from serializers import ValidationError in order to avoid any potential confusion.
validate_<field_name>.","text":"The validate_<field_name> method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field:
def validate_score(self, attrs, source):\n if attrs['score'] % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return attrs\n This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.
def validate_score(self, value):\n if value % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return value\n Any ad-hoc validation that applies to more than one field should go in the .validate(self, attrs) method as usual.
Because .validate_<field_name> would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use .validate() instead.
You can either return non_field_errors from the validate method by raising a simple ValidationError
def validate(self, attrs):\n # serializer.errors == {'non_field_errors': ['A non field error']}\n raise serializers.ValidationError('A non field error')\n Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the ValidationError, like so:
def validate(self, attrs):\n # serializer.errors == {'my_field': ['A field error']}\n raise serializers.ValidationError({'my_field': 'A field error'})\n This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.
"},{"location":"community/3.0-announcement/#removal-of-transform_field_name","title":"Removal oftransform_<field_name>.","text":"The under-used transform_<field_name> on serializer classes is no longer provided. Instead you should just override to_representation() if you need to apply any modifications to the representation style.
For example:
def to_representation(self, instance):\n ret = super(UserSerializer, self).to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret\n Dropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches.
If you absolutely need to preserve transform_<field_name> behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example:
class BaseModelSerializer(ModelSerializer):\n \"\"\"\n A custom ModelSerializer class that preserves 2.x style `transform_<field_name>` behavior.\n \"\"\"\n def to_representation(self, instance):\n ret = super(BaseModelSerializer, self).to_representation(instance)\n for key, value in ret.items():\n method = getattr(self, 'transform_' + key, None)\n if method is not None:\n ret[key] = method(value)\n return ret\n"},{"location":"community/3.0-announcement/#differences-between-modelserializer-validation-and-modelform","title":"Differences between ModelSerializer validation and ModelForm.","text":"This change also means that we no longer use the .full_clean() method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on ModelSerializer classes that can't also be easily replicated on regular Serializer classes.
For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different.
The one difference that you do need to note is that the .clean() method will not be called as part of serializer validation, as it would be if using a ModelForm. Use the serializer .validate() method to perform a final validation step on incoming data where required.
There may be some cases where you really do need to keep validation logic in the model .clean() method, and cannot instead separate it into the serializer .validate(). You can do so by explicitly instantiating a model instance in the .validate() method.
def validate(self, attrs):\n instance = ExampleModel(**attrs)\n instance.clean()\n return attrs\n Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.
"},{"location":"community/3.0-announcement/#writable-nested-serialization","title":"Writable nested serialization.","text":"REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic:
None data.Using the depth option on ModelSerializer will now create read-only nested serializers by default.
If you try to use a writable nested serializer without writing a custom create() and/or update() method you'll see an assertion error when you attempt to save the serializer. For example:
>>> class ProfileSerializer(serializers.ModelSerializer):\n>>> class Meta:\n>>> model = Profile\n>>> fields = ['address', 'phone']\n>>>\n>>> class UserSerializer(serializers.ModelSerializer):\n>>> profile = ProfileSerializer()\n>>> class Meta:\n>>> model = User\n>>> fields = ['username', 'email', 'profile']\n>>>\n>>> data = {\n>>> 'username': 'lizzy',\n>>> 'email': 'lizzy@example.com',\n>>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n>>> }\n>>>\n>>> serializer = UserSerializer(data=data)\n>>> serializer.save()\nAssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.\n To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the create() and/or update() methods explicitly.
class UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ['username', 'email', 'profile']\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user\n The single-step object creation makes this far simpler and more obvious than the previous .restore_object() behavior.
Serializer instances now support a printable representation that allows you to inspect the fields present on the instance.
For instance, given the following example model:
class LocationRating(models.Model):\n location = models.CharField(max_length=100)\n rating = models.IntegerField()\n created_by = models.ForeignKey(User)\n Let's create a simple ModelSerializer class corresponding to the LocationRating model.
class LocationRatingSerializer(serializer.ModelSerializer):\n class Meta:\n model = LocationRating\n We can now inspect the serializer representation in the Django shell, using python manage.py shell...
>>> serializer = LocationRatingSerializer()\n>>> print(serializer) # Or use `print serializer` in Python 2.x\nLocationRatingSerializer():\n id = IntegerField(label='ID', read_only=True)\n location = CharField(max_length=100)\n rating = IntegerField()\n created_by = PrimaryKeyRelatedField(queryset=User.objects.all())\n"},{"location":"community/3.0-announcement/#the-extra_kwargs-option","title":"The extra_kwargs option.","text":"The write_only_fields option on ModelSerializer has been moved to PendingDeprecation and replaced with a more generic extra_kwargs.
class MySerializer(serializer.ModelSerializer):\n class Meta:\n model = MyModel\n fields = ['id', 'email', 'notes', 'is_admin']\n extra_kwargs = {\n 'is_admin': {'write_only': True}\n }\n Alternatively, specify the field explicitly on the serializer class:
class MySerializer(serializer.ModelSerializer):\n is_admin = serializers.BooleanField(write_only=True)\n\n class Meta:\n model = MyModel\n fields = ['id', 'email', 'notes', 'is_admin']\n The read_only_fields option remains as a convenient shortcut for the more common case.
HyperlinkedModelSerializer.","text":"The view_name and lookup_field options have been moved to PendingDeprecation. They are no longer required, as you can use the extra_kwargs argument instead:
class MySerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = MyModel\n fields = ['url', 'email', 'notes', 'is_admin']\n extra_kwargs = {\n 'url': {'lookup_field': 'uuid'}\n }\n Alternatively, specify the field explicitly on the serializer class:
class MySerializer(serializer.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='mymodel-detail',\n lookup_field='uuid'\n )\n\n class Meta:\n model = MyModel\n fields = ['url', 'email', 'notes', 'is_admin']\n"},{"location":"community/3.0-announcement/#fields-for-model-methods-and-properties","title":"Fields for model methods and properties.","text":"With ModelSerializer you can now specify field names in the fields option that refer to model methods or properties. For example, suppose you have the following model:
class Invitation(models.Model):\n created = models.DateTimeField()\n to_email = models.EmailField()\n message = models.CharField(max_length=1000)\n\n def expiry_date(self):\n return self.created + datetime.timedelta(days=30)\n You can include expiry_date as a field option on a ModelSerializer class.
class InvitationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Invitation\n fields = ['to_email', 'message', 'expiry_date']\n These fields will be mapped to serializers.ReadOnlyField() instances.
>>> serializer = InvitationSerializer()\n>>> print(repr(serializer))\nInvitationSerializer():\n to_email = EmailField(max_length=75)\n message = CharField(max_length=1000)\n expiry_date = ReadOnlyField()\n"},{"location":"community/3.0-announcement/#the-listserializer-class","title":"The ListSerializer class.","text":"The ListSerializer class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.
class MultipleUserSerializer(ListSerializer):\n child = UserSerializer()\n You can also still use the many=True argument to serializer classes. It's worth noting that many=True argument transparently creates a ListSerializer instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.
You will typically want to continue to use the existing many=True flag rather than declaring ListSerializer classes explicitly, but declaring the classes explicitly can be useful if you need to write custom create or update methods for bulk updates, or provide for other custom behavior.
See also the new ListField class, which validates input in the same way, but does not include the serializer interfaces of .is_valid(), .data, .save() and so on.
BaseSerializer class.","text":"REST framework now includes a simple 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 an 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.
BaseSerializer classes.","text":"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):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField()\n It's simple to create a read-only serializer for converting HighScore instances into primitive data types.
class HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n We can now use this class to serialize single HighScore instances:
@api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data)\n Or use it to serialize multiple instances:
@api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)\n"},{"location":"community/3.0-announcement/#read-write-baseserializer-classes","title":"Read-write BaseSerializer classes.","text":"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 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):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) > 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)\n"},{"location":"community/3.0-announcement/#creating-new-generic-serializers-with-baseserializer","title":"Creating new generic serializers with BaseSerializer.","text":"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):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name.startswith('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)\n"},{"location":"community/3.0-announcement/#serializer-fields","title":"Serializer fields","text":""},{"location":"community/3.0-announcement/#the-field-and-readonly-field-classes","title":"The Field and ReadOnly field classes.","text":"There are some minor tweaks to the field base classes.
Previously we had these two base classes:
Field as the base class for read-only fields. A default implementation was included for serializing data.WritableField as the base class for read-write fields.We now use the following:
Field is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.ReadOnlyField is a concrete implementation for read-only fields that simply returns the attribute value without modification.required, allow_null, allow_blank and default arguments.","text":"REST framework now has more explicit and clear control over validating empty values for fields.
Previously the meaning of the required=False keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be None or the empty string.
We now have a better separation, with separate required, allow_null and allow_blank arguments.
The following set of arguments are used to control validation of empty values:
required=False: The value does not need to be present in the input, and will not be passed to .create() or .update() if it is not seen.default=<value>: The value does not need to be present in the input, and a default value will be passed to .create() or .update() if it is not seen.allow_null=True: None is a valid input.allow_blank=True: '' is valid input. For CharField and subclasses only.Typically you'll want to use required=False if the corresponding model field has a default value, and additionally set either allow_null=True or allow_blank=True if required.
The default argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the required argument when a default is specified, and doing so will result in an error.
The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an IntegerField would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior.
.validate().","text":"The .validate() method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override to_internal_value().
class UppercaseCharField(serializers.CharField):\n def to_internal_value(self, data):\n value = super(UppercaseCharField, self).to_internal_value(data)\n if value != value.upper():\n raise serializers.ValidationError('The input should be uppercase only.')\n return value\n Previously validation errors could be raised in either .to_native() or .validate(), making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.
ListField class.","text":"The ListField class has now been added. This field validates list input. It takes a child keyword argument which is used to specify the field used to validate each item in the list. For example:
scores = ListField(child=IntegerField(min_value=0, max_value=100))\n You can also use a declarative style to create new subclasses of ListField, like this:
class ScoresField(ListField):\n child = IntegerField(min_value=0, max_value=100)\n We can now use the ScoresField class inside another serializer:
scores = ScoresField()\n See also the new ListSerializer class, which validates input in the same way, but also includes the serializer interfaces of .is_valid(), .data, .save() and so on.
ChoiceField class may now accept a flat list.","text":"The ChoiceField class may now accept a list of choices in addition to the existing style of using a list of pairs of (name, display_value). The following is now valid:
color = ChoiceField(choices=['red', 'green', 'blue'])\n"},{"location":"community/3.0-announcement/#the-multiplechoicefield-class","title":"The MultipleChoiceField class.","text":"The MultipleChoiceField class has been added. This field acts like ChoiceField, but returns a set, which may include none, one or many of the valid choices.
The from_native(self, value) and to_native(self, data) method names have been replaced with the more obviously named to_internal_value(self, data) and to_representation(self, value).
The field_from_native() and field_to_native() methods are removed. Previously you could use these methods if you wanted to customize the behavior in a way that did not simply lookup the field value from the object. For example...
def field_to_native(self, obj, field_name):\n \"\"\"A custom read-only field that returns the class name.\"\"\"\n return obj.__class__.__name__\n Now if you need to access the entire object you'll instead need to override one or both of the following:
get_attribute to modify the attribute value passed to to_representation().get_value to modify the data value passed to_internal_value().For example:
def get_attribute(self, obj):\n # Pass the entire object through to `to_representation()`,\n # instead of the standard attribute lookup.\n return obj\n\ndef to_representation(self, value):\n return value.__class__.__name__\n"},{"location":"community/3.0-announcement/#explicit-queryset-required-on-relational-fields","title":"Explicit queryset required on relational fields.","text":"Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a ModelSerializer.
This code would be valid in 2.4.3:
class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n class Meta:\n model = Account\n However this code would not be valid in 3.0:
# Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n def restore_object(self, attrs, instance=None):\n # ...\n The queryset argument is now always required for writable relational fields. This removes some magic and makes it easier and more obvious to move between implicit ModelSerializer classes and explicit Serializer classes.
class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(\n slug_field='name',\n queryset=Organization.objects.all()\n )\n\n class Meta:\n model = Account\n The queryset argument is only ever required for writable fields, and is not required or valid for fields with read_only=True.
SerializerMethodField.","text":"The argument to SerializerMethodField is now optional, and defaults to get_<field_name>. For example the following is valid:
class AccountSerializer(serializers.Serializer):\n # `method_name='get_billing_details'` by default.\n billing_details = serializers.SerializerMethodField()\n\n def get_billing_details(self, account):\n return calculate_billing(account)\n In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code will raise an error:
billing_details = serializers.SerializerMethodField('get_billing_details')\n"},{"location":"community/3.0-announcement/#enforcing-consistent-source-usage","title":"Enforcing consistent source usage.","text":"I've see several codebases that unnecessarily include the source argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that source is usually not required.
The following usage will now raise an error:
email = serializers.EmailField(source='email')\n"},{"location":"community/3.0-announcement/#the-uniquevalidator-and-uniquetogethervalidator-classes","title":"The UniqueValidator and UniqueTogetherValidator classes.","text":"REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit Serializer class instead of using ModelSerializer.
The UniqueValidator should be applied to a serializer field, and takes a single queryset argument.
from rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\nclass OrganizationSerializer(serializers.Serializer):\n url = serializers.HyperlinkedIdentityField(view_name='organization_detail')\n created = serializers.DateTimeField(read_only=True)\n name = serializers.CharField(\n max_length=100,\n validators=UniqueValidator(queryset=Organization.objects.all())\n )\n The UniqueTogetherValidator should be applied to a serializer, and takes a queryset argument and a fields argument which should be a list or tuple of field names.
class RaceResultSerializer(serializers.Serializer):\n category = serializers.ChoiceField(['5k', '10k'])\n position = serializers.IntegerField()\n name = serializers.CharField(max_length=100)\n\n class Meta:\n validators = [UniqueTogetherValidator(\n queryset=RaceResult.objects.all(),\n fields=['category', 'position']\n )]\n"},{"location":"community/3.0-announcement/#the-uniquefordatevalidator-classes","title":"The UniqueForDateValidator classes.","text":"REST framework also now includes explicit validator classes for validating the unique_for_date, unique_for_month, and unique_for_year model field constraints. These are used internally instead of calling into Model.full_clean().
These classes are documented in the Validators section of the documentation.
"},{"location":"community/3.0-announcement/#generic-views","title":"Generic views","text":""},{"location":"community/3.0-announcement/#simplification-of-view-logic","title":"Simplification of view logic.","text":"The view logic for the default method handlers has been significantly simplified, due to the new serializers API.
"},{"location":"community/3.0-announcement/#changes-to-prepost-save-hooks","title":"Changes to pre/post save hooks.","text":"The pre_save and post_save hooks no longer exist, but are replaced with perform_create(self, serializer) and perform_update(self, serializer).
These methods should save the object instance by calling serializer.save(), adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.
For example:
def perform_create(self, serializer):\n # Include the owner attribute directly, rather than from request data.\n instance = serializer.save(owner=self.request.user)\n # Perform a custom post-save action.\n send_email(instance.to_email, instance.message)\n The pre_delete and post_delete hooks no longer exist, and are replaced with .perform_destroy(self, instance), which should delete the instance and perform any custom actions.
def perform_destroy(self, instance):\n # Perform a custom pre-delete action.\n send_deletion_alert(user=instance.created_by, deleted=instance)\n # Delete the object instance.\n instance.delete()\n"},{"location":"community/3.0-announcement/#removal-of-view-attributes","title":"Removal of view attributes.","text":"The .object and .object_list attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic.
I would personally recommend that developers treat view instances as immutable objects in their application code.
"},{"location":"community/3.0-announcement/#put-as-create","title":"PUT as create.","text":"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 we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.
If you need to restore the previous behavior you may want to include this AllowPUTAsCreateMixin class as a mixin to your views.
The generic views now raise ValidationFailed exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a 400 Bad Request response directly.
This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.
"},{"location":"community/3.0-announcement/#the-metadata-api","title":"The metadata API","text":"Behavior for dealing with OPTIONS requests was previously built directly into the class-based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.
This makes it far easier to use a different style for OPTIONS responses throughout your API, and makes it possible to create third-party metadata policies.
REST framework 3.0 includes templated HTML form rendering for serializers.
This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.
Significant changes that you do need to be aware of include:
UserSerializer with a nested ProfileSerializer will now render a nested fieldset when used in the browsable API.widget option is no longer available for serializer fields. You can instead control the template that is used for a given field, by using the style dictionary.style keyword argument for serializer fields.","text":"The style keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the HTMLFormRenderer uses the base_template key to determine which template to render the field with.
For example, to use a textarea control instead of the default input control, you would use the following\u2026
additional_notes = serializers.CharField(\n style={'base_template': 'textarea.html'}\n)\n Similarly, to use a radio button control instead of the default select control, you would use the following\u2026
color_channel = serializers.ChoiceField(\n choices=['red', 'blue', 'green'],\n style={'base_template': 'radio.html'}\n)\n This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.
"},{"location":"community/3.0-announcement/#api-style","title":"API style","text":"There are some improvements in the default style we use in our API responses.
"},{"location":"community/3.0-announcement/#unicode-json-by-default","title":"Unicode JSON by default.","text":"Unicode JSON is now the default. The UnicodeJSONRenderer class no longer exists, and the UNICODE_JSON setting has been added. To revert this behavior use the new setting:
REST_FRAMEWORK = {\n 'UNICODE_JSON': False\n}\n"},{"location":"community/3.0-announcement/#compact-json-by-default","title":"Compact JSON by default.","text":"We now output compact JSON in responses by default. For example, we return:
{\"email\":\"amy@example.com\",\"is_admin\":true}\n Instead of the following:
{\"email\": \"amy@example.com\", \"is_admin\": true}\n The COMPACT_JSON setting has been added, and can be used to revert this behavior if needed:
REST_FRAMEWORK = {\n 'COMPACT_JSON': False\n}\n"},{"location":"community/3.0-announcement/#file-fields-as-urls","title":"File fields as URLs","text":"The FileField and ImageField classes are now represented as URLs by default. You should ensure you set Django's standard MEDIA_URL setting appropriately, and ensure your application serves the uploaded files.
You can revert this behavior, and display filenames in the representation by using the UPLOADED_FILES_USE_URL settings key:
REST_FRAMEWORK = {\n 'UPLOADED_FILES_USE_URL': False\n}\n You can also modify serializer fields individually, using the use_url argument:
uploaded_file = serializers.FileField(use_url=False)\n Also note that you should pass the request object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form https://example.com/url_path/filename.txt. For example:
context = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data)\n If the request is omitted from the context, the returned URLs will be of the form /url_path/filename.txt.
Retry-After.","text":"The custom X-Throttle-Wait-Second header has now been dropped in favor of the standard Retry-After header. You can revert this behavior if needed by writing a custom exception handler for your application.
Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as Date, Time and DateTime objects, and later coerced to strings by the renderer.
You can modify this behavior globally by settings the existing DATE_FORMAT, DATETIME_FORMAT and TIME_FORMAT settings keys. Setting these values to None instead of their default value of 'iso-8601' will result in native objects being returned in serializer data.
REST_FRAMEWORK = {\n # Return native `Date` and `Time` objects in `serializer.data`\n 'DATETIME_FORMAT': None\n 'DATE_FORMAT': None\n 'TIME_FORMAT': None\n}\n You can also modify serializer fields individually, using the date_format, time_format and datetime_format arguments:
# Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None)\n"},{"location":"community/3.0-announcement/#decimals-as-strings-in-serializer-data","title":"Decimals as strings in serializer data.","text":"Decimals are now coerced to strings by default in the serializer output. Previously they were returned as Decimal objects, and later coerced to strings by the renderer.
You can modify this behavior globally by using the COERCE_DECIMAL_TO_STRING settings key.
REST_FRAMEWORK = {\n 'COERCE_DECIMAL_TO_STRING': False\n}\n Or modify it on an individual serializer field, using the coerce_to_string keyword argument.
# Return `Decimal` instances in `serializer.data`, not strings.\namount = serializers.DecimalField(\n max_digits=10,\n decimal_places=2,\n coerce_to_string=False\n)\n The default JSON renderer will return float objects for un-coerced Decimal instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.
ChoiceField does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.APIException subclasses could previously take any arbitrary type in the detail argument. These exceptions now use translatable text strings, and as a result call force_text on the detail argument, which must be a string. If you need complex arguments to an APIException class, you should subclass it and override the __init__() method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.
The 3.1 release is planned to address improvements in the following components:
The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.
You can follow development on the GitHub site, where we use milestones to indicate planning timescales.
"},{"location":"community/3.1-announcement/","title":"Django REST framework 3.1","text":"The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality.
Some highlights include:
HStoreField and ArrayField.The pagination API has been improved, making it both easier to use, and more powerful.
A guide to the headline features follows. For full details, see the pagination documentation.
Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes.
PAGINATE_BY settings key will continue to work but is now pending deprecation. The more obviously named PAGE_SIZE settings key should now be used instead.PAGINATE_BY_PARAM, MAX_PAGINATE_BY settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.paginate_by, page_query_param, paginate_by_param and max_paginate_by generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.pagination_serializer_class view attribute and DEFAULT_PAGINATION_SERIALIZER_CLASS settings key are no longer valid. The pagination API does not use serializers to determine the output format, and you'll need to instead override the get_paginated_response method on a pagination class in order to specify how the output format is controlled.Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default.
The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for this blog post on the subject.
"},{"location":"community/3.1-announcement/#pagination-controls-in-the-browsable-api","title":"Pagination controls in the browsable API.","text":"Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API:
The cursor based pagination renders a more simple style of control:
"},{"location":"community/3.1-announcement/#support-for-header-based-pagination","title":"Support for header-based pagination.","text":"The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the Link or Content-Range headers.
For more information, see the custom pagination styles documentation.
"},{"location":"community/3.1-announcement/#versioning","title":"Versioning","text":"We've made it easier to build versioned APIs. Built-in schemes for versioning include both URL based and Accept header based variations.
When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request.
For example, when using NamespaceVersioning, and the following hyperlinked serializer:
class AccountsSerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = Accounts\n fields = ['account_name', 'users']\n The output representation would match the version used on the incoming request. Like so:
GET http://example.org/v2/accounts/10 # Version 'v2'\n\n{\n \"account_name\": \"europa\",\n \"users\": [\n \"http://example.org/v2/users/12\", # Version 'v2'\n \"http://example.org/v2/users/54\",\n \"http://example.org/v2/users/87\"\n ]\n}\n"},{"location":"community/3.1-announcement/#internationalization","title":"Internationalization","text":"REST framework now includes a built-in set of translations, and supports internationalized error responses. This allows you to either change the default language, or to allow clients to specify the language via the Accept-Language header.
You can change the default language by using the standard Django LANGUAGE_CODE setting:
LANGUAGE_CODE = \"es-es\"\n You can turn on per-request language requests by adding LocalMiddleware to your MIDDLEWARE_CLASSES setting:
MIDDLEWARE_CLASSES = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n]\n When per-request internationalization is enabled, client requests will respect the Accept-Language header where possible. For example, let's make a request for an unsupported media type:
Request
GET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org\n Response
HTTP/1.0 406 NOT ACCEPTABLE\n\n{\n \"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"\n}\n Note that the structure of the error responses is still the same. We still have a detail key in the response. If needed you can modify this behavior too, by using a custom exception handler.
We include built-in translations both for standard exception cases, and for serializer validation errors.
The full list of supported languages can be found on our Transifex project page.
If you only wish to support a subset of the supported languages, use Django's standard LANGUAGES setting:
LANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n]\n For more details, see the internationalization documentation.
Many thanks to Craig Blaszczyk for helping push this through.
"},{"location":"community/3.1-announcement/#new-field-types","title":"New field types","text":"Django 1.8's new ArrayField, HStoreField and UUIDField are now all fully supported.
This work also means that we now have both serializers.DictField(), and serializers.ListField() types, allowing you to express and validate a wider set of representations.
If you're building a new 1.8 project, then you should probably consider using UUIDField as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style:
http://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d\n"},{"location":"community/3.1-announcement/#modelserializer-api","title":"ModelSerializer API","text":"The serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships.
For more information, see the documentation on customizing field mappings for ModelSerializer classes.
"},{"location":"community/3.1-announcement/#moving-packages-out-of-core","title":"Moving packages out of core","text":"We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to pip install the new packages, and change any import paths.
We're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework.
The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained Django OAuth toolkit has now been promoted as our recommended option for integrating OAuth support.
The following packages are now moved out of core and should be separately installed:
It's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do:
pip install djangorestframework-xml\n And modify your settings, like so:
REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n 'rest_framework_xml.renderers.XMLRenderer'\n ]\n}\n Thanks go to the latest member of our maintenance team, Jos\u00e9 Padilla, for handling this work and taking on ownership of these packages.
"},{"location":"community/3.1-announcement/#deprecations","title":"Deprecations","text":"The request.DATA, request.FILES and request.QUERY_PARAMS attributes move from pending deprecation, to deprecated. Use request.data and request.query_params instead, as discussed in the 3.0 release notes.
The ModelSerializer Meta options for write_only_fields, view_name and lookup_field are also moved from pending deprecation, to deprecated. Use extra_kwargs instead, as discussed in the 3.0 release notes.
All these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2.
"},{"location":"community/3.1-announcement/#whats-next","title":"What's next?","text":"The next focus will be on HTML renderings of API output and will include:
This will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release.
"},{"location":"community/3.10-announcement/","title":"3.10 Announcement","text":""},{"location":"community/3.10-announcement/#django-rest-framework-310","title":"Django REST framework 3.10","text":"The 3.10 release drops support for Python 2.
Since we first introduced schema support in Django REST Framework 3.5, OpenAPI has emerged as the widely adopted standard for modeling Web APIs.
This release begins the deprecation process for the CoreAPI based schema generation, and introduces OpenAPI schema generation in its place.
"},{"location":"community/3.10-announcement/#continuing-to-use-coreapi","title":"Continuing to use CoreAPI","text":"If you're currently using the CoreAPI schemas, you'll need to make sure to update your REST framework settings to include DEFAULT_SCHEMA_CLASS explicitly.
settings.py:
REST_FRAMEWORK = {\n ...: ...,\n \"DEFAULT_SCHEMA_CLASS\": \"rest_framework.schemas.coreapi.AutoSchema\",\n}\n You'll still be able to keep using CoreAPI schemas, API docs, and client for the foreseeable future. We'll aim to ensure that the CoreAPI schema generator remains available as a third party package, even once it has eventually been removed from REST framework, scheduled for version 3.12.
We have removed the old documentation for the CoreAPI based schema generation. You may view the Legacy CoreAPI documentation here.
"},{"location":"community/3.10-announcement/#openapi-quickstart","title":"OpenAPI Quickstart","text":"You can generate a static OpenAPI schema, using the generateschema management command.
Alternately, to have the project serve an API schema, use the get_schema_view() shortcut.
In your urls.py:
from rest_framework.schemas import get_schema_view\n\nurlpatterns = [\n # ...\n # Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.\n # * `title` and `description` parameters are passed to `SchemaGenerator`.\n # * Provide view name for use with `reverse()`.\n path(\n \"openapi\",\n get_schema_view(title=\"Your Project\", description=\"API for all things \u2026\"),\n name=\"openapi-schema\",\n ),\n # ...\n]\n"},{"location":"community/3.10-announcement/#customization","title":"Customization","text":"For customizations that you want to apply across the entire API, you can subclass rest_framework.schemas.openapi.SchemaGenerator and provide it as an argument to the generateschema command or get_schema_view() helper function.
For specific per-view customizations, you can subclass AutoSchema, making sure to set schema = <YourCustomClass> on the view.
For more details, see the API Schema documentation.
"},{"location":"community/3.10-announcement/#api-documentation","title":"API Documentation","text":"There are some great third party options for documenting your API, based on the OpenAPI schema.
See the Documenting you API section for more details.
"},{"location":"community/3.10-announcement/#feature-roadmap","title":"Feature Roadmap","text":"Given that our OpenAPI schema generation is a new feature, it's likely that there will still be some iterative improvements for us to make. There will be two main cases here:
We'll aim to bring the first type of change quickly in point releases. For the second kind we'd like to adopt a slower approach, to make sure we keep the API simple, and as widely applicable as possible, before we bring in API changes.
It's also possible that we'll end up implementing API documentation and API client tooling that are driven by the OpenAPI schema. The apistar project has a significant amount of work towards this. However, if we do so, we'll plan on keeping any tooling outside of the core framework.
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.
Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, ESG, Rollbar, Cadre, Kloudless, and Lights On Software.
"},{"location":"community/3.11-announcement/","title":"3.11 Announcement","text":""},{"location":"community/3.11-announcement/#django-rest-framework-311","title":"Django REST framework 3.11","text":"The 3.11 release adds support for Django 3.0.
This release will be the last to support Python 3.5 or Django 1.11.
"},{"location":"community/3.11-announcement/#openapi-schema-generation-improvements","title":"OpenAPI Schema Generation Improvements","text":"The OpenAPI schema generation continues to mature. Some highlights in 3.11 include:
In this example view operation descriptions for the get and post methods will be extracted from the class docstring:
class DocStringExampleListView(APIView):\n \"\"\"\n get: A description of my GET operation.\n post: A description of my POST operation.\n \"\"\"\n\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n\n def get(self, request, *args, **kwargs): ...\n\n def post(self, request, *args, **kwargs): ...\n"},{"location":"community/3.11-announcement/#validator-default-context","title":"Validator / Default Context","text":"In some circumstances a Validator class or a Default class may need to access the serializer field with which it is called, or the .context with which the serializer was instantiated. In particular:
CurrentUserDefault needs to be able to determine the context with which the serializer was instantiated, in order to return the current user instance.Our previous approach to this was that implementations could include a set_context method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13.
Instead, validators or defaults which require the serializer context, should include a requires_context = True attribute on the class.
The __call__ method should then include an additional serializer_field argument.
Validator implementations will look like this:
class CustomValidator:\n requires_context = True\n\n def __call__(self, value, serializer_field): ...\n Default implementations will look like this:
class CustomDefault:\n requires_context = True\n\n def __call__(self, serializer_field): ...\n"},{"location":"community/3.11-announcement/#funding","title":"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.
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.
"},{"location":"community/3.12-announcement/","title":"3.12 Announcement","text":""},{"location":"community/3.12-announcement/#django-rest-framework-312","title":"Django REST framework 3.12","text":"REST framework 3.12 brings a handful of refinements to the OpenAPI schema generation, plus support for Django's new database-agnostic JSONField, and some improvements to the SearchFilter class.
Open API schemas will now automatically include tags, based on the first element in the URL path.
For example...
Method Path TagsGET, PUT, PATCH, DELETE /users/{id}/ ['users'] GET, POST /users/ ['users'] GET, PUT, PATCH, DELETE /orders/{id}/ ['orders'] GET, POST /orders/ ['orders'] The tags used for a particular view may also be overridden...
class MyOrders(APIView):\n schema = AutoSchema(tags=[\"users\", \"orders\"])\n ...\n See the schema documentation for more information.
"},{"location":"community/3.12-announcement/#customizing-the-operation-id","title":"Customizing the operation ID.","text":"REST framework automatically determines operation IDs to use in OpenAPI schemas. The latest version provides more control for overriding the behavior used to generate the operation IDs.
See the schema documentation for more information.
"},{"location":"community/3.12-announcement/#support-for-openapi-components","title":"Support for OpenAPI components.","text":"In order to output more graceful OpenAPI schemes, REST framework 3.12 now defines components in the schema, and then references them inside request and response objects. This is in contrast with the previous approach, which fully expanded the request and response bodies for each operation.
The names used for a component default to using the serializer class name, but may be overridden if needed...
class MyOrders(APIView):\n schema = AutoSchema(component_name=\"OrderDetails\")\n"},{"location":"community/3.12-announcement/#more-public-api","title":"More Public API","text":"Many methods on the AutoSchema class have now been promoted to public API, allowing you to more fully customize the schema generation. The following methods are now available for overriding...
get_path_parametersget_pagination_parametersget_filter_parametersget_request_bodyget_responsesget_serializerget_paginatormap_serializermap_fieldmap_choice_fieldmap_field_validatorsallows_filters.See the schema docs for details on using custom AutoSchema subclasses.
Django 3.1 deprecated the existing django.contrib.postgres.fields.JSONField in favor of a new database-agnositic JSONField.
REST framework 3.12 now supports this new model field, and ModelSerializer classes will correctly map the model field.
There are a couple of significant improvements to the SearchFilter class.
The class now supports nested search within JSONField and HStoreField, using the double underscore notation for traversing which element of the field the search should apply to.
class SitesSearchView(generics.ListAPIView):\n \"\"\"\n An API view to return a list of archaeological sites, optionally filtered\n by a search against the site name or location. (Location searches are\n matched against the region and country names.)\n \"\"\"\n\n queryset = Sites.objects.all()\n serializer_class = SitesSerializer\n filter_backends = [filters.SearchFilter]\n search_fields = [\"site_name\", \"location__region\", \"location__country\"]\n"},{"location":"community/3.12-announcement/#searches-against-annotate-fields","title":"Searches against annotate fields","text":"Django allows querysets to create additional virtual fields, using the .annotate method. We now support searching against annotate fields.
class PublisherSearchView(generics.ListAPIView):\n \"\"\"\n Search for publishers, optionally filtering the search against the average\n rating of all their books.\n \"\"\"\n\n queryset = Publisher.objects.annotate(avg_rating=Avg(\"book__rating\"))\n serializer_class = PublisherSerializer\n filter_backends = [filters.SearchFilter]\n search_fields = [\"avg_rating\"]\n"},{"location":"community/3.12-announcement/#deprecations","title":"Deprecations","text":""},{"location":"community/3.12-announcement/#serializersnullbooleanfield","title":"serializers.NullBooleanField","text":"serializers.NullBooleanField is now pending deprecation, and will be removed in 3.14.
Instead use serializers.BooleanField field and set allow_null=True which does the same thing.
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.
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.
"},{"location":"community/3.13-announcement/","title":"3.13 Announcement","text":""},{"location":"community/3.13-announcement/#django-rest-framework-313","title":"Django REST framework 3.13","text":""},{"location":"community/3.13-announcement/#django-40-support","title":"Django 4.0 support","text":"The latest release now fully supports Django 4.0.
Our requirements are now:
When instantiating fields on serializers, you should always use keyword arguments, such as serializers.CharField(max_length=200). This has always been the case, and all the examples that we have in the documentation use keyword arguments, rather than positional arguments.
From REST framework 3.13 onwards, this is now explicitly enforced.
The most feasible cases where users might be accidentally omitting the keyword arguments are likely in the composite fields, ListField and DictField. For instance...
aliases = serializers.ListField(serializers.CharField())\n They must now use the more explicit keyword argument style...
aliases = serializers.ListField(child=serializers.CharField())\n This change has been made because using positional arguments here does not result in the expected behavior.
See Pull Request #7632 for more details.
"},{"location":"community/3.14-announcement/","title":"3.14 Announcement","text":""},{"location":"community/3.14-announcement/#django-rest-framework-314","title":"Django REST framework 3.14","text":""},{"location":"community/3.14-announcement/#django-41-support","title":"Django 4.1 support","text":"The latest release now fully supports Django 4.1, and drops support for Django 2.2.
Our requirements are now:
raise_exception argument for is_valid is now keyword-only.","text":"Calling serializer_instance.is_valid(True) is no longer acceptable syntax. If you'd like to use the raise_exception argument, you must use it as a keyword argument.
See Pull Request #7952 for more details.
"},{"location":"community/3.14-announcement/#manyrelatedfield-supports-returning-the-default-when-the-source-attribute-doesnt-exist","title":"ManyRelatedField supports returning the default when the source attribute doesn't exist.","text":"Previously, if you used a serializer field with many=True with a dot notated source field that didn't exist, it would raise an AttributeError. Now it will return the default or be skipped depending on the other arguments.
See Pull Request #7574 for more details.
"},{"location":"community/3.14-announcement/#make-open-api-get_reference-public","title":"Make Open APIget_reference public.","text":"Returns a reference to the serializer component. This may be useful if you override get_schema().
When OR-ing two permissions, the request has to pass either class's has_permission() and has_object_permission().
Previously, both class's has_permission() was ignored when OR-ing two permissions together.
See Pull Request #7522 for more details.
"},{"location":"community/3.14-announcement/#minor-fixes-and-improvements","title":"Minor fixes and improvements","text":"There are a number of minor fixes and improvements in this release. See the release notes page for a complete listing.
"},{"location":"community/3.14-announcement/#deprecations","title":"Deprecations","text":""},{"location":"community/3.14-announcement/#serializersnullbooleanfield","title":"serializers.NullBooleanField","text":"serializers.NullBooleanField was moved to pending deprecation in 3.12, and deprecated in 3.13. It has now been removed from the core framework.
Instead use serializers.BooleanField field and set allow_null=True which does the same thing.
At the Internet, on March 15th, 2024, with 176 commits by 138 authors, we are happy to announce the release of Django REST framework 3.15.
"},{"location":"community/3.15-announcement/#django-50-and-python-312-support","title":"Django 5.0 and Python 3.12 support","text":"The latest release now fully supports Django 5.0 and Python 3.12.
The current minimum versions of Django still is 3.0 and Python 3.6.
"},{"location":"community/3.15-announcement/#primary-support-of-uniqueconstraint","title":"Primary Support of UniqueConstraint","text":"ModelSerializer generates validators for UniqueConstraint (both UniqueValidator and UniqueTogetherValidator)
By default the URLs created by SimpleRouter use regular expressions. This behavior can be modified by setting the use_regex_path argument to False when instantiating the router.
Dependency on pytz has been removed and deprecation warnings have been added, Django will provide ZoneInfo instances as long as USE_DEPRECATED_PYTZ is not enabled. More info on the migration can be found in this guide.
"},{"location":"community/3.15-announcement/#align-searchfilter-behavior-to-djangocontribadmin-search","title":"AlignSearchFilter behavior to django.contrib.admin search","text":"Searches now may contain quoted phrases with spaces, each phrase is considered as a single search term, and it will raise a validation error if any null-character is provided in search. See the Filtering API guide for more information.
"},{"location":"community/3.15-announcement/#other-fixes-and-improvements","title":"Other fixes and improvements","text":"There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behavior.
See the release notes page for a complete listing.
"},{"location":"community/3.16-announcement/","title":"3.16 Announcement","text":""},{"location":"community/3.16-announcement/#django-rest-framework-316","title":"Django REST framework 3.16","text":"At the Internet, on March 28th, 2025, we are happy to announce the release of Django REST framework 3.16.
"},{"location":"community/3.16-announcement/#updated-django-and-python-support","title":"Updated Django and Python support","text":"The latest release now fully supports Django 5.1 and the upcoming 5.2 LTS as well as Python 3.13.
The current minimum versions of Django is now 4.2 and Python 3.9.
"},{"location":"community/3.16-announcement/#django-loginrequiredmiddleware","title":"Django LoginRequiredMiddleware","text":"The new LoginRequiredMiddleware introduced by Django 5.1 can now be used alongside Django REST Framework, however it is not honored for API views as an equivalent behavior can be configured via DEFAULT_AUTHENTICATION_CLASSES. See our dedicated section in the docs for more information.
The generation of validators for UniqueConstraint has been improved to support better nullable fields and constraints with conditions.
"},{"location":"community/3.16-announcement/#other-fixes-and-improvements","title":"Other fixes and improvements","text":"There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behavior.
See the release notes page for a complete listing.
"},{"location":"community/3.2-announcement/","title":"Django REST framework 3.2","text":"The 3.2 release is the first version to include an admin interface for the browsable API.
This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing BrowsableAPIRenderer, or used together with it, allowing you to switch between the two styles as required.
We've also fixed a huge number of issues, and made numerous cleanups and improvements.
Over the course of the 3.1.x series we've resolved nearly 600 tickets on our GitHub issue tracker. This means we're currently running at a rate of closing around 100 issues or pull requests per month.
None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking a look through our sponsors and finding out who's hiring.
"},{"location":"community/3.2-announcement/#adminrenderer","title":"AdminRenderer","text":"To include AdminRenderer simply add it to your settings:
REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.AdminRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer'\n ],\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n}\n There are some limitations to the AdminRenderer, in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those.
Also note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates.
The idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.
"},{"location":"community/3.2-announcement/#supported-versions","title":"Supported versions","text":"This release drops support for Django 1.4.
Our supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.
"},{"location":"community/3.2-announcement/#deprecations","title":"Deprecations","text":"There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy.
request.DATA was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of request.data instead.request.QUERY_PARAMS was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of request.query_params instead.ModelSerializer.Meta options have now been removed: write_only_fields, view_name, lookup_field. Use the more general extra_kwargs option instead.The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors.
view.paginate_by - Use paginator.page_size instead.view.page_query_param - Use paginator.page_query_param instead.view.paginate_by_param - Use paginator.page_size_query_param instead.view.max_paginate_by - Use paginator.max_page_size instead.settings.PAGINATE_BY - Use paginator.page_size instead.settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead.settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead.There are a couple of bug fixes that are worth calling out as they introduce differing behavior.
These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.
"},{"location":"community/3.2-announcement/#manytomany-fields-and-blanktrue","title":"ManyToMany fields and blank=True","text":"We've now added an allow_empty argument, which can be used with ListSerializer, or with many=True relationships. This is True by default, but can be set to False if you want to disallow empty lists as valid input.
As a follow-up to this we are now able to properly mirror the behavior of Django's ModelForm with respect to how many-to-many fields are validated.
Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has blank=True set.
Here's what the mapping looks like in practice:
models.ManyToManyField() \u2192 serializers.PrimaryKeyRelatedField(many=True, allow_empty=False)models.ManyToManyField(blank=True) \u2192 serializers.PrimaryKeyRelatedField(many=True)The upshot is this: If you have many to many fields in your models, then make sure you've included the argument blank=True if you want to allow empty inputs in the equivalent ModelSerializer fields.
When using allow_null with ListField or a nested many=True serializer the previous behavior was to allow null values as items in the list. The behavior is now to allow null values instead of the list.
For example, take the following field:
NestedSerializer(many=True, allow_null=True)\n Previously the validation behavior would be:
[{\u2026}, null, {\u2026}] is valid.null is invalid.Our validation behavior as of 3.2.0 is now:
[{\u2026}, null, {\u2026}] is invalid.null is valid.If you want to allow null child items, you'll need to instead specify allow_null on the child class, using an explicit ListField instead of many=True. For example:
ListField(child=NestedSerializer(allow_null=True))\n"},{"location":"community/3.2-announcement/#whats-next","title":"What's next?","text":"The 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release.
This release is planned to include:
Thanks once again to all our sponsors and supporters.
"},{"location":"community/3.3-announcement/","title":"Django REST framework 3.3","text":"The 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding thank you to all our wonderful sponsors and supporters.
The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project.
In order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow @_tomchristie to keep up to date with these announcements, and be among the first set of sign ups.
We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product.
"},{"location":"community/3.3-announcement/#release-notes","title":"Release notes","text":"Significant new functionality in the 3.3 release includes:
JSONField serializer field, corresponding to Django 1.9's Postgres JSONField model field.Example of the new filter controls
"},{"location":"community/3.3-announcement/#supported-versions","title":"Supported versions","text":"This release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required.
This brings our supported versions into line with Django's currently supported versions
"},{"location":"community/3.3-announcement/#deprecations","title":"Deprecations","text":"The AJAX based support for the browsable API means that there are a number of internal cleanups in the request class. For the vast majority of developers this should largely remain transparent:
PUT and DELETE, or to support form content types such as JSON, you should now use the AJAX forms javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.accept query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to use a custom content negotiation class.HTTP_X_HTTP_METHOD_OVERRIDE header is no longer supported by default. If you require it then you'll need to use custom middleware.The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.
view.paginate_by - Use paginator.page_size instead.view.page_query_param - Use paginator.page_query_param instead.view.paginate_by_param - Use paginator.page_size_query_param instead.view.max_paginate_by - Use paginator.max_page_size instead.settings.PAGINATE_BY - Use paginator.page_size instead.settings.PAGINATE_BY_PARAM - Use paginator.page_size_query_param instead.settings.MAX_PAGINATE_BY - Use paginator.max_page_size instead.The ModelSerializer and HyperlinkedModelSerializer classes should now include either a fields or exclude option, although the fields = '__all__' shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings ModelSerializer more closely in line with Django's ModelForm behavior.
The 3.4 release is the first in a planned series that will be addressing schema generation, hypermedia support, API clients, and finally realtime support.
"},{"location":"community/3.4-announcement/#funding","title":"Funding","text":"The 3.4 release has been made possible a recent Mozilla grant, and by our collaborative funding model. If you use REST framework commercially, and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid plan.
The initial aim is to provide a single full-time position on REST framework. Right now we're over 60% of the way towards achieving that. Every single sign-up makes a significant impact.
Many thanks to all our awesome sponsors, and in particular to our premium backers, Rover, Sentry, and Stream.
"},{"location":"community/3.4-announcement/#schemas-client-libraries","title":"Schemas & client libraries","text":"REST framework 3.4 brings built-in support for generating API schemas.
We provide this support by using Core API, a Document Object Model for describing APIs.
Because Core API represents the API schema in an format-independent manner, we're able to render the Core API Document object into many different schema formats, by allowing the renderer class to determine how the internal representation maps onto the external schema format.
This approach should also open the door to a range of auto-generated API documentation options in the future, by rendering the Document object into HTML documentation pages.
Alongside the built-in schema support, we're also now providing the following:
These API clients are dynamically driven, and able to interact with any API that exposes a supported schema format.
Dynamically driven clients allow you to interact with an API at an application layer interface, rather than a network layer interface, while still providing the benefits of RESTful Web API design.
We're expecting to expand the range of languages that we provide client libraries for over the coming months.
Further work on maturing the API schema support is also planned, including documentation on supporting file upload and download, and improved support for documentation generation and parameter annotation.
Current support for schema formats is as follows:
Name Support PyPI package Core JSON Schema generation & client support. Built-in support incoreapi. Swagger / OpenAPI Schema generation & client support. The openapi-codec package. JSON Hyper-Schema Currently client support only. The hyperschema-codec package. API Blueprint Not yet available. Not yet available. You can read more about any of this new functionality in the following:
It is also worth noting that Marc Gibbons is currently working towards a 2.0 release of the popular Django REST Swagger package, which will tie in with our new built-in support.
"},{"location":"community/3.4-announcement/#supported-versions","title":"Supported versions","text":"The 3.4.0 release adds support for Django 1.10.
The following versions of Python and Django are now supported:
(*) Note that Python 3.2 and 3.3 are not supported from Django 1.9 onwards.
"},{"location":"community/3.4-announcement/#deprecations-and-changes","title":"Deprecations and changes","text":"The 3.4 release includes very limited deprecation or behavioral changes, and should present a straightforward upgrade.
"},{"location":"community/3.4-announcement/#use-fields-or-exclude-on-serializer-classes","title":"Use fields or exclude on serializer classes.","text":"The following change in 3.3.0 is now escalated from \"pending deprecation\" to \"deprecated\". Its usage will continue to function but will raise warnings:
ModelSerializer and HyperlinkedModelSerializer should include either a fields option, or an exclude option. The fields = '__all__' shortcut may be used to explicitly include all fields.
Using the default JSON renderer and directly returning a datetime or time instance will now render with microsecond precision (6 digits), rather than millisecond precision (3 digits). This makes the output format consistent with the default string output of serializers.DateTimeField and serializers.TimeField.
This change does not affect the default behavior when using serializers, which is to serialize datetime and time instances into strings with microsecond precision.
The serializer behavior can be modified if needed, using the DATETIME_FORMAT and TIME_FORMAT settings.
The renderer behavior can be modified by setting a custom encoder_class attribute on a JSONRenderer subclass.
Making an OPTIONS request to views that have a serializer choice field will result in a list of the available choices being returned in the response.
In cases where there is a relational field, the previous behavior would be to return a list of available instances to choose from for that relational field.
In order to minimize exposed information the behavior now is to not return choices information for relational fields.
If you want to override this new behavior you'll need to implement a custom metadata class.
See issue #3751 for more information on this behavioral change.
"},{"location":"community/3.4-announcement/#other-improvements","title":"Other improvements","text":"This release includes further work from a huge number of pull requests and issues.
Many thanks to all our contributors who've been involved in the release, either through raising issues, giving feedback, improving the documentation, or suggesting and implementing code changes.
The full set of itemized release notes are available here.
"},{"location":"community/3.5-announcement/","title":"3.5 Announcement","text":""},{"location":"community/3.5-announcement/#django-rest-framework-35","title":"Django REST framework 3.5","text":"The 3.5 release is the second in a planned series that is addressing schema generation, hypermedia support, API client libraries, and finally realtime support.
"},{"location":"community/3.5-announcement/#funding","title":"Funding","text":"The 3.5 release would not have been possible without our collaborative funding model. If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan.
Many thanks to all our sponsors, and in particular to our premium backers, Rover, Sentry, Stream, and Machinalis.
"},{"location":"community/3.5-announcement/#improved-schema-generation","title":"Improved schema generation","text":"Docstrings on views are now pulled through into schema definitions, allowing you to use the schema definition to document your\u00a0API.
There is now also a shortcut function, get_schema_view(), which makes it easier to adding schema views to your API.
For example, to include a swagger schema to your API, you would do the following:
Run pip install django-rest-swagger.
Add 'rest_framework_swagger' to your INSTALLED_APPS setting.
Include the schema view in your URL conf:
from rest_framework.schemas import get_schema_view\nfrom rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer\n\nschema_view = get_schema_view(\n title=\"Example API\", renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]\n)\n\nurlpatterns = [path(\"swagger/\", schema_view), ...]\n There have been a large number of fixes to the schema generation. These should resolve issues for anyone using the latest version of the django-rest-swagger package.
Some of these changes do affect the resulting schema structure, so if you're already using schema generation you should make sure to review the deprecation notes, particularly if you're currently using a dynamic client library to interact with your API.
Finally, we're also now exposing the schema generation as a publicly documented API, allowing you to more easily override the behavior.
"},{"location":"community/3.5-announcement/#requests-test-client","title":"Requests test client","text":"You can now test your project using the requests library.
This exposes exactly the same interface as if you were using a standard requests session instance.
client = RequestsClient()\nresponse = client.get('http://testserver/users/')\nassert response.status_code == 200\n Rather than sending any HTTP requests to the network, this interface will coerce all outgoing requests into WSGI, and call into your application directly.
"},{"location":"community/3.5-announcement/#core-api-client","title":"Core API client","text":"You can also now test your project by interacting with it using the coreapi client library.
# Fetch the API schema\nclient = CoreAPIClient()\nschema = client.get('http://testserver/schema/')\n\n# Create a new organization\nparams = {'name': 'MegaCorp', 'status': 'active'}\nclient.action(schema, ['organizations', 'create'], params)\n\n# Ensure that the organization exists in the listing\ndata = client.action(schema, ['organizations', 'list'])\nassert(len(data) == 1)\nassert(data == [{'name': 'MegaCorp', 'status': 'active'}])\n Again, this will call directly into the application using the WSGI interface, rather than making actual network calls.
This is a good option if you are planning for clients to mainly interact with your API using the coreapi client library, or some other auto-generated client.
One interesting aspect of both the requests client and the coreapi client is that they allow you to write tests in such a way that they can also be made to run against a live service.
By switching the WSGI based client instances to actual instances of requests.Session or coreapi.Client you can have the test cases make actual network calls.
Being able to write test cases that can exercise your staging or production environment is a powerful tool. However in order to do this, you'll need to pay close attention to how you handle setup and teardown to ensure a strict isolation of test data from other live or staging data.
"},{"location":"community/3.5-announcement/#raml-support","title":"RAML support","text":"We now have preliminary support for RAML documentation generation.
Further work on the encoding and documentation generation is planned, in order to make features such as the 'Try it now' support available at a later date.
This work also now means that you can use the Core API client libraries to interact with APIs that expose a RAML specification. The RAML codec gives some examples of interacting with the Spotify API in this way.
"},{"location":"community/3.5-announcement/#validation-codes","title":"Validation codes","text":"Exceptions raised by REST framework now include short code identifiers. When used together with our customizable error handling, this now allows you to modify the style of API error messages.
As an example, this allows for the following style of error responses:
{\n \"message\": \"You do not have permission to perform this action.\",\n \"code\": \"permission_denied\"\n}\n This is particularly useful with validation errors, which use appropriate codes to identify differing kinds of failure...
{\n \"name\": {\"message\": \"This field is required.\", \"code\": \"required\"},\n \"age\": {\"message\": \"A valid integer is required.\", \"code\": \"invalid\"}\n}\n"},{"location":"community/3.5-announcement/#client-upload-download-support","title":"Client upload & download support","text":"The Python coreapi client library and the Core API command line tool both now fully support file uploads and downloads.
The router arguments for generating a schema view, such as schema_title, are now pending deprecation.
Instead of using DefaultRouter(schema_title='Example API'), you should use the get_schema_view() function, and include the view in your URL conf.
Make sure to include the view before your router urls. For example:
from rest_framework.schemas import get_schema_view\nfrom my_project.routers import router\n\nschema_view = get_schema_view(title='Example API')\n\nurlpatterns = [\n path('', schema_view),\n path('', include(router.urls)),\n]\n"},{"location":"community/3.5-announcement/#schema-path-representations","title":"Schema path representations","text":"The 'pk' identifier in schema paths is now mapped onto the actually model field name by default. This will typically be 'id'.
This gives a better external representation for schemas, with less implementation detail being exposed. It also reflects the behavior of using a ModelSerializer class with fields = '__all__'.
You can revert to the previous behavior by setting 'SCHEMA_COERCE_PATH_PK': False in the REST framework settings.
The internal retrieve() and destroy() method names are now coerced to an external representation of read and delete.
You can revert to the previous behavior by setting 'SCHEMA_COERCE_METHOD_NAMES': {} in the REST framework settings.
The functionality of the built-in DjangoFilterBackend is now completely included by the django-filter package.
You should change your imports and REST framework filter settings as follows:
rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend.rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet.The existing imports will continue to work but are now pending deprecation.
"},{"location":"community/3.5-announcement/#corejson-media-type","title":"CoreJSON media type","text":"The media type for CoreJSON is now application/json+coreapi, rather than the previous application/vnd.json+coreapi. This brings it more into line with other custom media types, such as those used by Swagger and RAML.
The clients currently accept either media type. The old style-media type will be deprecated at a later date.
"},{"location":"community/3.5-announcement/#modelserializer-fields-and-exclude","title":"ModelSerializer 'fields' and 'exclude'","text":"ModelSerializer and HyperlinkedModelSerializer must include either a fields option, or an exclude option. The fields = '__all__' shortcut may be used to explicitly include all fields.
Failing to set either fields or exclude raised a pending deprecation warning in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.
The 3.6 release adds two major new features to REST framework.
Above: The interactive API documentation.
"},{"location":"community/3.6-announcement/#funding","title":"Funding","text":"The 3.6 release would not have been possible without our backing from Mozilla to the project, and our collaborative funding\u00a0model.
If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan.
Many thanks to all our sponsors, and in particular to our premium backers, Rover, Sentry, Stream, Machinalis, Rollbar, and MicroPyramid.
"},{"location":"community/3.6-announcement/#interactive-api-documentation","title":"Interactive API documentation","text":"REST framework's new API documentation supports a number of features:
The coreapi library is required as a dependency for the API docs. Make sure to install the latest version (2.3.0 or above). The pygments and markdown libraries are optional but recommended.
To install the API documentation, you'll need to include it in your projects URLconf:
from rest_framework.documentation import include_docs_urls\n\nAPI_TITLE = 'API title'\nAPI_DESCRIPTION = '...'\n\nurlpatterns = [\n ...\n path('docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))\n]\n Once installed you should see something a little like this:
We'll likely be making further refinements to the API documentation over the coming weeks. Keep in mind that this is a new feature, and please do give us feedback if you run into any issues or limitations.
For more information on documenting your API endpoints see the \"Documenting your API\" section.
"},{"location":"community/3.6-announcement/#javascript-client-library","title":"JavaScript client library","text":"The JavaScript client library allows you to load an API schema, and then interact with that API at an application layer interface, rather than constructing fetch requests explicitly.
Here's a brief example that demonstrates:
index.html
<html>\n <head>\n <script src=\"/static/rest_framework/js/coreapi-0.1.0.js\"></script>\n <script src=\"/docs/schema.js\"></script>\n <script>\n const coreapi = window.coreapi\n const schema = window.schema\n\n // Instantiate a client...\n let auth = coreapi.auth.TokenAuthentication({scheme: 'JWT', token: 'xxx'})\n let client = coreapi.Client({auth: auth})\n\n // Make an API request...\n client.action(schema, ['projects', 'list']).then(function(result) {\n alert(result)\n })\n </script>\n </head>\n</html>\n The JavaScript client library supports various authentication schemes, and can be used by your project itself, or as an external client interacting with your API.
The client is not limited to usage with REST framework APIs, although it does currently only support loading CoreJSON API schemas. Support for Swagger and other API schemas is planned.
For more details see the JavaScript client library documentation.
"},{"location":"community/3.6-announcement/#authentication-classes-for-the-python-client-library","title":"Authentication classes for the Python client library","text":"Previous authentication support in the Python client library was limited to allowing users to provide explicit header values.
We now have better support for handling the details of authentication, with the introduction of the BasicAuthentication, TokenAuthentication, and SessionAuthentication schemes.
You can include the authentication scheme when instantiating a new client.
auth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')\nclient = coreapi.Client(auth=auth)\n For more information see the Python client library documentation.
"},{"location":"community/3.6-announcement/#deprecations","title":"Deprecations","text":""},{"location":"community/3.6-announcement/#updating-coreapi","title":"Updating coreapi","text":"If you're using REST framework's schema generation, or want to use the API docs, then you'll need to update to the latest version of coreapi. (2.3.0)
"},{"location":"community/3.6-announcement/#generating-schemas-from-router","title":"Generating schemas from Router","text":"The 3.5 \"pending deprecation\" of router arguments for generating a schema view, such as schema_title, schema_url and schema_renderers, have now been escalated to a \"deprecated\" warning.
Instead of using DefaultRouter(schema_title='Example API'), you should use the get_schema_view() function, and include the view explicitly in your URL conf.
The 3.5 \"pending deprecation\" warning of the built-in DjangoFilterBackend has now been escalated to a \"deprecated\" warning.
You should change your imports and REST framework filter settings as follows:
rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend.rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet.There are likely to be a number of refinements to the API documentation and JavaScript client library over the coming weeks, which could include some of the following:
Once work on those refinements is complete, we'll be starting feature work on realtime support, for the 3.7 release.
"},{"location":"community/3.7-announcement/","title":"3.7 Announcement","text":""},{"location":"community/3.7-announcement/#django-rest-framework-37","title":"Django REST framework 3.7","text":"The 3.7 release focuses on improvements to schema generation and the interactive API documentation.
This release has been made possible by Bayer who have sponsored the release.
"},{"location":"community/3.7-announcement/#funding","title":"Funding","text":"If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan.
As well as our release sponsor, we'd like to say thanks in particular our premium backers, Rover, Sentry, Stream, Machinalis, and Rollbar.
"},{"location":"community/3.7-announcement/#customizing-api-docs-schema-generation","title":"Customizing API docs & schema generation.","text":"The schema generation introduced in 3.5 and the related API docs generation in 3.6 are both hugely powerful features, however they've been somewhat limited in cases where the view introspection isn't able to correctly identify the schema for a particular view.
In order to try to address this we're now adding the ability for per-view customization of the API schema. The interface that we're adding for this allows either basic manual overrides over which fields should be included on a view, or for more complex programmatic overriding of the schema generation. We believe this release comprehensively addresses some of the existing shortcomings of the schema features.
Let's take a quick look at using the new functionality...
The APIView class has a schema attribute, that is used to control how the Schema for that particular view is generated. The default behavior is to use the AutoSchema class.
from rest_framework.views import APIView\nfrom rest_framework.schemas import AutoSchema\n\nclass CustomView(APIView):\n schema = AutoSchema() # Included for demonstration only. This is the default behavior.\n We can remove a view from the API schema and docs, like so:
class CustomView(APIView):\n schema = None\n If we want to mostly use the default behavior, but additionally include some additional fields on a particular view, we can now do so easily...
class CustomView(APIView):\n schema = AutoSchema(manual_fields=[\n coreapi.Field('search', location='query')\n ])\n To ignore the automatic generation for a particular view, and instead specify the schema explicitly, we use the ManualSchema class instead...
class CustomView(APIView):\n schema = ManualSchema(fields=[...])\n For more advanced behaviors you can subclass AutoSchema to provide for customized schema generation, and apply that to particular views.
class CustomView(APIView):\n schema = CustomizedSchemaGeneration()\n For full details on the new functionality, please see the Schema Documentation.
"},{"location":"community/3.7-announcement/#django-20-support","title":"Django 2.0 support","text":"REST framework 3.7 supports Django versions 1.10, 1.11, and 2.0 alpha.
"},{"location":"community/3.7-announcement/#minor-fixes-and-improvements","title":"Minor fixes and improvements","text":"There are a large number of minor fixes and improvements in this release. See the release notes page for a complete listing.
The number of open tickets against the project currently at its lowest number in quite some time, and we're continuing to focus on reducing these to a manageable amount.
"},{"location":"community/3.7-announcement/#deprecations","title":"Deprecations","text":""},{"location":"community/3.7-announcement/#exclude_from_schema","title":"exclude_from_schema","text":"Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view decorator and now PendingDeprecation. They will be moved to deprecated in the 3.8 release, and removed entirely in 3.9.
For APIView you should instead set a schema = None attribute on the view class.
For function based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None).
DjangoFilterBackend","text":"The DjangoFilterBackend was moved to pending deprecation in 3.5, and deprecated in 3.6. It has now been removed from the core framework.
The functionality remains fully available, but is instead provided in the django-filter package.
We're still planning to work on improving real-time support for REST framework by providing documentation on integrating with Django channels, as well adding support for more easily adding WebSocket support to existing HTTP endpoints.
This will likely be timed so that any REST framework development here ties in with similar work on API Star.
"},{"location":"community/3.8-announcement/","title":"3.8 Announcement","text":""},{"location":"community/3.8-announcement/#django-rest-framework-38","title":"Django REST framework 3.8","text":"The 3.8 release is a maintenance focused release resolving a large number of previously outstanding issues and laying the foundations for future changes.
"},{"location":"community/3.8-announcement/#funding","title":"Funding","text":"If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan.
We'd like to say thanks in particular our premium backers, Rover, Sentry, Stream, Machinalis, and Rollbar.
"},{"location":"community/3.8-announcement/#breaking-changes","title":"Breaking Changes","text":""},{"location":"community/3.8-announcement/#altered-the-behavior-of-read_only-plus-default-on-field","title":"Altered the behavior ofread_only plus default on Field.","text":"#5886 read_only fields will now always be excluded from writable fields.
Previously read_only fields when combined with a default value would use the default for create and update operations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted source attributes on nullable relations.
In order to maintain the old behavior you may need to pass the value of read_only fields when calling save() in the view:
def perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n Alternatively you may override save() or create() or update() on the serializer as appropriate.
action decorator replaces list_route and detail_route","text":"#5705 list_route and detail_route have been merge into a single action decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions.
Both list_route and detail_route are now pending deprecation. They will be deprecated in 3.9 and removed entirely in 3.10.
The new action decorator takes a boolean detail argument.
detail_route uses with @action(detail=True).list_route uses with @action(detail=False).exclude_from_schema","text":"Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view decorator are now deprecated. They will be removed entirely in 3.9.
For APIView you should instead set a schema = None attribute on the view class.
For function based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None).
There are a large number of minor fixes and improvements in this release. See the release notes page for a complete listing.
"},{"location":"community/3.8-announcement/#whats-next","title":"What's next","text":"We're currently working towards moving to using OpenAPI as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the coreapi and coreschema libraries, and instead use apistar for the API documentation generation, schema generation, and API client libraries.
The 3.9 release gives access to extra actions in the Browsable API, introduces composable permissions and built-in OpenAPI schema support. (Formerly known as Swagger)
"},{"location":"community/3.9-announcement/#funding","title":"Funding","text":"If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by signing up for a paid\u00a0plan.
Many thanks to all our wonderful sponsors, and in particular to our premium backers, Rover, Sentry, Stream, Auklet, Rollbar, Cadre, Load Impact, and Kloudless.
"},{"location":"community/3.9-announcement/#built-in-openapi-schema-support","title":"Built-in OpenAPI schema support","text":"REST framework now has a first-pass at directly including OpenAPI schema support. (Formerly known as Swagger)
Specifically:
OpenAPIRenderer, and JSONOpenAPIRenderer classes that deal with encoding coreapi.Document instances into OpenAPI YAML or OpenAPI JSON.get_schema_view(...) method now defaults to OpenAPI YAML, with CoreJSON as a secondary option if it is selected via HTTP content negotiation.generateschema, which you can use to dump the schema into your repository.Here's an example of adding an OpenAPI schema to the URL conf:
from rest_framework.schemas import get_schema_view\nfrom rest_framework.renderers import JSONOpenAPIRenderer\nfrom django.urls import path\n\nschema_view = get_schema_view(\n title=\"Server Monitoring API\",\n url=\"https://www.example.org/api/\",\n renderer_classes=[JSONOpenAPIRenderer],\n)\n\nurlpatterns = [path(\"schema.json\", schema_view), ...]\n And here's how you can use the generateschema management command:
$ python manage.py generateschema --format openapi > schema.yml\n There's lots of different tooling that you can use for working with OpenAPI schemas. One option that we're working on is the API Star command line tool.
You can use apistar to validate your API schema:
$ apistar validate --path schema.json --format openapi\n\u2713 Valid OpenAPI schema.\n Or to build API documentation:
$ apistar docs --path schema.json --format openapi\n\u2713 Documentation built at \"build/index.html\".\n API Star also includes a dynamic client library that uses an API schema to automatically provide a client library interface for making requests.
"},{"location":"community/3.9-announcement/#composable-permission-classes","title":"Composable permission classes","text":"You can now compose permission classes using the and/or operators, & and |.
For example...
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]\n If you're using custom permission classes then make sure that you are subclassing from BasePermission in order to enable this support.
Following the introduction of the action decorator in v3.8, extra actions defined on a ViewSet are now available from the Browsable API.
When defined, a dropdown of \"Extra Actions\", appropriately filtered to detail/non-detail actions, is displayed.
"},{"location":"community/3.9-announcement/#supported-versions","title":"Supported Versions","text":"REST framework 3.9 supports Django versions 1.11, 2.0, and 2.1.
"},{"location":"community/3.9-announcement/#deprecations","title":"Deprecations","text":""},{"location":"community/3.9-announcement/#djangoobjectpermissionsfilter-moved-to-third-party-package","title":"DjangoObjectPermissionsFilter moved to third-party package.","text":"The DjangoObjectPermissionsFilter class is pending deprecation, will be deprecated in 3.10 and removed entirely in 3.11.
It has been moved to the third-party djangorestframework-guardian package. Please use this instead.
basename for consistency.","text":"Router.register base_name argument has been renamed in favor of basename.Router.get_default_base_name method has been renamed in favor of Router.get_default_basename. #5990See #5990.
base_name and get_default_base_name() are pending deprecation. They will be deprecated in 3.10 and removed entirely in 3.11.
action decorator replaces list_route and detail_route","text":"Both list_route and detail_route are now deprecated in favor of the single action decorator. They will be removed entirely in 3.10.
The action decorator takes a boolean detail argument.
detail_route uses with @action(detail=True).list_route uses with @action(detail=False).exclude_from_schema","text":"Both APIView.exclude_from_schema and the exclude_from_schema argument to the @api_view have now been removed.
For APIView you should instead set a schema = None attribute on the view class.
For function-based views the @schema decorator can be used to exclude the view from the schema, by using @schema(None).
There are a large number of minor fixes and improvements in this release. See the release notes page for a complete listing.
"},{"location":"community/3.9-announcement/#whats-next","title":"What's next","text":"We're planning to iteratively work towards OpenAPI becoming the standard schema representation. This will mean that the coreapi dependency will gradually become removed, and we'll instead generate the schema directly, rather than building a CoreAPI Document object.
OpenAPI has clearly become the standard for specifying Web APIs, so there's not much value any more in our schema-agnostic document model. Making this change will mean that we'll more easily be able to take advantage of the full set of OpenAPI functionality.
This will also make a wider range of tooling available.
We'll focus on continuing to develop the API Star library and client tool into a recommended option for generating API docs, validating API schemas, and providing a dynamic client library.
There's also a huge amount of ongoing work on maturing the ASGI landscape, with the possibility that some of this work will eventually feed back into Django.
There will be further work on the Uvicorn web server, as well as lots of functionality planned for the Starlette web framework, which is building a foundational set of tooling for working with ASGI.
"},{"location":"community/contributing/","title":"Contributing to REST framework","text":"The world can only really be changed one piece at a time. The art is picking that piece.
\u2014 Tim Berners-Lee
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
Note
At this point in its lifespan we consider Django REST framework to be feature-complete. We focus on pull requests that track the continued development of Django versions, and generally do not accept new features or code formatting changes.
"},{"location":"community/contributing/#community","title":"Community","text":"The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
Other really great ways you can help move the community forward include helping to answer questions on the discussion group, or setting up an email alert on StackOverflow so that you get notified of any new questions with the django-rest-framework tag.
When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
"},{"location":"community/contributing/#code-of-conduct","title":"Code of conduct","text":"Please keep the tone polite & professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.
Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations.
The Django code of conduct gives a fuller set of guidelines for participating in community forums.
"},{"location":"community/contributing/#issues","title":"Issues","text":"Our contribution process is that the GitHub discussions page should generally be your starting point. Some tips on good potential issue reporting:
Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to
To start developing on Django REST framework, first create a Fork from the Django REST Framework repo on GitHub.
Then clone your fork. The clone command will look like this, with your GitHub username instead of YOUR-USERNAME:
git clone https://github.com/YOUR-USERNAME/django-rest-framework\n See GitHub's Fork a Repo Guide for more help.
Changes should broadly follow the PEP 8 style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles. You can check your contributions against these conventions each time you commit using the pre-commit hooks, which we also run on CI. To set them up, first ensure you have the pre-commit tool installed, for example:
python -m pip install pre-commit\n Then run:
pre-commit install\n"},{"location":"community/contributing/#testing","title":"Testing","text":"To run the tests, clone the repository, and then:
# Setup the virtual environment\npython3 -m venv env\nsource env/bin/activate\npip install -e . --group dev\n\n# Run the tests\n./runtests.py\n Tip
If your tests require access to the database, do not forget to inherit from django.test.TestCase or use the @pytest.mark.django_db() decorator.
For example, with TestCase:
from django.test import TestCase\n\nclass MyDatabaseTest(TestCase):\n def test_something(self):\n # Your test code here\n pass\n Or with decorator:
import pytest\n\n@pytest.mark.django_db()\nclass MyDatabaseTest:\n def test_something(self):\n # Your test code here\n pass\n You can reuse existing models defined in tests/models.py for your tests.
Run using a more concise output style.
./runtests.py -q\n If you do not want the output to be captured (for example, to see print statements directly), you can use the -s flag.
./runtests.py -s\n Run the tests for a given test case.
./runtests.py MyTestCase\n Run the tests for a given test method.
./runtests.py MyTestCase.test_this_method\n Shorter form to run the tests for a given test method.
./runtests.py test_this_method\n Note
The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
"},{"location":"community/contributing/#running-against-multiple-environments","title":"Running against multiple environments","text":"You can also use the excellent tox testing tool to run the tests against all supported versions of Python and Django. Install tox globally, and then simply run:
tox\n"},{"location":"community/contributing/#pull-requests","title":"Pull requests","text":"It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests.
It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.
GitHub's documentation for working on pull requests is available here.
Always run the tests before submitting pull requests, and ideally run tox in order to check that your modifications are compatible on all supported versions of Python and Django.
Once you've made a pull request take a look at the build status in the GitHub interface and make sure the tests are running as you'd expect.
Above: build notifications
"},{"location":"community/contributing/#managing-compatibility-issues","title":"Managing compatibility issues","text":"Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the compat.py module, and should provide a single common interface that the rest of the codebase can use.
The documentation for REST framework is built from the Markdown source files in the docs directory.
There are many great Markdown editors that make working with the documentation really easy. The Mou editor for Mac is one such editor that comes highly recommended.
"},{"location":"community/contributing/#building-the-documentation","title":"Building the documentation","text":"To build the documentation, install MkDocs with pip install mkdocs and then run the following command.
mkdocs build\n This will build the documentation into the site directory.
You can build the documentation and open a preview in a browser window by using the serve command.
mkdocs serve\n"},{"location":"community/contributing/#language-style","title":"Language style","text":"Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.
Some other tips:
There are a couple of conventions you should follow when working on the documentation.
"},{"location":"community/contributing/#1-headers","title":"1. Headers","text":"Headers should use the hash style. For example:
### Some important topic\n The underline style should not be used. Don't do this:
Some important topic\n====================\n"},{"location":"community/contributing/#2-links","title":"2. Links","text":"Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.
Here is a link to [some other thing][other-thing].\n\nMore text...\n\n[other-thing]: http://example.com/other/thing\n This style helps keep the documentation source consistent and readable.
If you are hyperlinking to another REST framework document, you should use a relative link, and link to the .md suffix. For example:
[authentication]: ../api-guide/authentication.md\n Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
"},{"location":"community/contributing/#3-notes","title":"3. Notes","text":"If you want to draw attention to a note or warning, use an admonition, like so:
!!! note\n A useful documentation note.\n The documentation theme styles info, warning, tip and danger admonition types, but more could be added if the need arise.
Looking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of our sponsors are hiring.
"},{"location":"community/jobs/#places-to-look-for-django-rest-framework-jobs","title":"Places to look for Django REST Framework Jobs","text":"Know of any other great resources for Django REST Framework jobs that are missing in our list? Please submit a pull request or email us.
Wonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for REST Framework sponsorship yet.
"},{"location":"community/kickstarter-announcement/","title":"Kickstarting Django REST framework 3","text":"In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.
"},{"location":"community/kickstarter-announcement/#project-details","title":"Project details","text":"This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following:
Full details are available now on the project page.
If you're interested in helping make sustainable open source development a reality please visit the Kickstarter page and consider funding the project.
I can't wait to see where this takes us!
Many thanks to everyone for your support so far,
Tom Christie :)
"},{"location":"community/kickstarter-announcement/#sponsors","title":"Sponsors","text":"We've now blazed way past all our goals, with a staggering \u00a330,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.
"},{"location":"community/kickstarter-announcement/#platinum-sponsors","title":"Platinum sponsors","text":"Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.
Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.
The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank\u00a0you to individuals who have chosen to privately support the project at this level.
Individual backers: Paul Hallett, Paul Whipp, Dylan Roy, Jannis Leidel, Xavier Ordoquy, Johannes Spielmann, Rob Spectre, Chris Heisel, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.
"},{"location":"community/kickstarter-announcement/#advocates","title":"Advocates","text":"The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you!
Individual backers: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, D\u00e9c\u00e9bal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkk\u00e4, Charalampos Papaloizou, Nikolai R\u00f8ed Kristiansen, Antoni Aloy L\u00f3pez, Celia Oakley, Micha\u0142 Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel.
Corporate backers: Savannah Informatics, Prism Skylabs, Musical Operating Devices.
"},{"location":"community/kickstarter-announcement/#supporters","title":"Supporters","text":"There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!
"},{"location":"community/mozilla-grant/","title":"Mozilla Grant","text":"We have recently been awarded a Mozilla grant, in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with.
Additionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications.
The Core API project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with any API that exposes a supported schema or hypermedia format.
Specifically, the work includes:
"},{"location":"community/mozilla-grant/#client-libraries","title":"Client libraries","text":"This work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation.
The next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints.
In order to ensure that I can be fully focused on trying to secure a sustainable & well-funded open source business I will be leaving my current role at DabApps at the end of May 2016.
I have formed a UK limited company, Encode, which will act as the business entity behind REST framework. I will be issuing monthly reports from Encode on progress both towards the Mozilla grant, and for development time funded via the REST framework paid plans.
Email Address"},{"location":"community/project-management/","title":"Project management","text":"\"No one can whistle a symphony; it takes a whole orchestra to play it\"
\u2014 Halford E. Luccock
This document outlines our project management processes for REST framework.
The aim is to ensure that the project has a high \"bus factor\", and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.
"},{"location":"community/project-management/#maintenance-team","title":"Maintenance team","text":"Participating actively in the REST framework project does not require being part of the maintenance team. Almost every important part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.
"},{"location":"community/project-management/#composition","title":"Composition","text":"The composition of the maintenance team is handled by @tomchristie. Team members will be added as collaborators to the repository.
"},{"location":"community/project-management/#responsibilities","title":"Responsibilities","text":"Team members have the following responsibilities.
mkdocs gh-deploy.Further notes for maintainers:
@tomchristie.Our PyPI releases will be handled by either the current release manager, or by @tomchristie. Every release should have an open issue tagged with the Release label and marked against the appropriate milestone.
The following template should be used for the description of the issue, and serves as a release checklist.
Release manager is @***.\nPull request is #***.\n\nChecklist:\n\n- [ ] Create pull request for [release notes](https://github.com/encode/django-rest-framework/blob/mains/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/encode/django-rest-framework/milestones/***).\n- [ ] Update supported versions:\n - [ ] `pyproject.toml` `python_requires` list\n - [ ] `pyproject.toml` Python & Django version trove classifiers\n - [ ] `README` Python & Django versions\n - [ ] `docs` Python & Django versions\n- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/main/rest_framework/__init__.py).\n- [ ] Ensure documentation validates\n - Build and serve docs `mkdocs serve`\n - Validate links `pylinkvalidate.py -P http://127.0.0.1:8000`\n- [ ] Confirm with @tomchristie that release is finalized and ready to go.\n- [ ] Ensure that release date is included in pull request.\n- [ ] Merge the release pull request.\n- [ ] Install the release tools: `pip install build twine`\n- [ ] Build the package: `python -m build`\n- [ ] Push the package to PyPI with `twine upload dist/*`\n- [ ] Tag the release, with `git tag -a *.*.* -m 'version *.*.*'; git push --tags`.\n- [ ] Deploy the documentation with `mkdocs gh-deploy`.\n- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).\n- [ ] Make a release announcement on twitter.\n- [ ] Close the milestone on GitHub.\n\nTo modify this process for future releases make a pull request to the [project management](https://www.django-rest-framework.org/topics/project-management/) documentation.\n When pushing the release to PyPI ensure that your environment has been installed from our development requirement.txt, so that documentation and PyPI installs are consistently being built against a pinned set of packages.
The PyPI package is owned by @tomchristie. As a backup @j4mie also has ownership of the package.
If @tomchristie ceases to participate in the project then @j4mie has responsibility for handing over ownership duties.
The following issues still need to be addressed:
@j4mie has back-up access to the django-rest-framework.org domain setup and admin.Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.
Medium version numbers (0.x.0) may include API changes, in line with the deprecation policy. You should read the release notes carefully before upgrading between medium point releases.
Major version numbers (x.0.0) are reserved for substantial project milestones.
As REST Framework is considered feature-complete, most releases are expected to be minor releases.
"},{"location":"community/release-notes/#deprecation-policy","title":"Deprecation policy","text":"REST framework releases follow a formal deprecation policy, which is in line with Django's deprecation policy.
The timeline for deprecation of a feature present in version 1.0 would work as follows:
Version 1.1 would remain fully backwards compatible with 1.0, but would raise RemovedInDRF13Warning warnings, subclassing PendingDeprecationWarning, if you use the feature that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using python -Wd manage.py test, you'll be warned of any API changes you need to make.
Version 1.2 would escalate these warnings to subclass DeprecationWarning, which is loud by default.
Version 1.3 would remove the deprecated bits of API entirely.
Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.
"},{"location":"community/release-notes/#upgrading","title":"Upgrading","text":"To upgrade Django REST framework to the latest version, use pip:
pip install -U djangorestframework\n You can determine your currently installed version using pip show:
pip show djangorestframework\n"},{"location":"community/release-notes/#316x-series","title":"3.16.x series","text":""},{"location":"community/release-notes/#3161","title":"3.16.1","text":"Date: 6th August 2025
This release fixes a few bugs, clean-up some old code paths for unsupported Python versions and improve translations.
"},{"location":"community/release-notes/#minor-changes","title":"Minor changes","text":"backports.zoneinfo dependency and conditions on unsupported Python 3.8 and lower in #9681. Python versions prior to 3.9 were already unsupported so this shouldn't be a breaking change.unique_together validation with SerializerMethodField in #9712UniqueTogetherValidator to handle fields with source attribute in #9688drf-restwind and update outdated images in browsable-api.md in #9680djangorestframework-guardian2 to djangorestframework-guardian in #9734request in serializer context when using HyperlinkedModelSerializer in #9732pyupgrade to pre-commit hooks in #9682pytz is available in #9715@araggohnxd made their first contribution in #9673@mbeijen made their first contribution in #9660@stefan6419846 made their first contribution in #9676@ren000thomas made their first contribution in #9675@ulgens made their first contribution in #9682@bukh-sal made their first contribution in #9595@rezatn0934 made their first contribution in #9576@Rohit10jr made their first contribution in #9693@kushibayev made their first contribution in #9713@alihassancods made their first contribution in #9732@kulikjak made their first contribution in #9715@Natgho made their first contribution in #9749Full Changelog: https://github.com/encode/django-rest-framework/compare/3.16.0...3.16.1
"},{"location":"community/release-notes/#3160","title":"3.16.0","text":"Date: 28th March 2025
This release is considered a significant release to improve upstream support with Django and Python. Some of these may change the behavior of existing features and pre-existing behavior. Specifically, some fixes were added to around the support of UniqueConstraint with nullable fields which will improve built-in serializer validation.
LoginRequiredMiddleware in #9514 and #9657UniqueConstraint in #9360UniqueConstraint in #9531unique_together validation with source in #9482AttributeError raised within properties in #9455get_template_context to handle also lists in #9467DecimalField in #9515open() in setup.py in #9661AutoSchema._get_reference method in #9525OperandHolder in #9437adrf third party package in #9198queryset attribute in #9528httpie call in docs in #9543<> in validators example in #9590strftime link in the docs in #9624action attribute in 'Introspecting ViewSet actions' docs section in #9633rest-framework-gm2m-relations package to the list of 3rd party libraries in #9063django-pyoidc as a third party authentication library in #9667@maerteijn made their first contribution in #9198@FraCata00 made their first contribution in #9444@AlvaroVega made their first contribution in #9451@james-mchugh made their first contribution in #9455@ifeanyidavid made their first contribution in #9479@p-schlickmann made their first contribution in #9480@akkuman made their first contribution in #9505@rafaelgramoschi made their first contribution in #9509@Sinaatkd made their first contribution in #9521@gtkacz made their first contribution in #9535@sliverc made their first contribution in #9556@gabrielromagnoli1987 made their first contribution in #9543@cheehong1030 made their first contribution in #9563@amansharma612 made their first contribution in #9590@Gluroda made their first contribution in #9616@deepakangadi made their first contribution in #9624@EXG1O made their first contribution in #9633@decadenza made their first contribution in #9640@mojtabaakbari221b made their first contribution in #9063@mikemanger made their first contribution in #9661@gbip made their first contribution in #9667Full Changelog: https://github.com/encode/django-rest-framework/compare/3.15.2...3.16.0
"},{"location":"community/release-notes/#315x-series","title":"3.15.x series","text":""},{"location":"community/release-notes/#3152","title":"3.15.2","text":"Date: 14th June 2024
Date: 22nd March 2024
SearchFilter handling of quoted and comma separated strings, when .get_search_terms is being called into by a custom class. See [#9338]Date: 15th March 2024
SearchFilter rendering search field with invalid value [#9023]timedelta [#9007]NamespaceVersioning ignoring DEFAULT_VERSION on non-None namespaces [#7278]field.choices that triggered full table load [#8950]BooleanField validation [#8970]BrowsableAPIRenderer for usage with ListSerializer. [#7530]OR of two permission classes [#7522]pytz [#8984]Serializer [#8001]OrderedDict with dict [#8964]__eq__ for validators [#8925]can_read_model permission in DjangoModelPermissions [#8009]basename is not unique [#8438]_ignore_model_permissions = True [#8772]__eq__ method for OperandHolder class [#8710]django.test package when not testing [#8699]examples and format to OpenAPI schema of CursorPagination [#8687] [#8686]Date: 22nd September 2022
--api-version CLI option to generateschema management command. [#8663]is_valid(raise_exception=False) as a keyword-only argument. [#7952]set_context on Validators. [#8589]NotImplemented from ErrorDetails.__ne__. [#8538]DateTimeField.default_timezone when a custom timezone is set. [#8531]ManyRelatedField falling back to the default value when the attribute specified by dot notation doesn't exist. Matches ManyRelatedField.get_attribute to Field.get_attribute. [#7574]schemas.openapi.get_reference public. [#7515]ReturnDict support dict union operators on Python 3.9 and later. [#8302]request.user is set before checking if the user is authenticated. [#8370]Date: 15th December 2021
@api_view. [#8297]Date: 13th December 2021
max_length and min_length options to ListSerializer. [#8165]get_request_serializer and get_response_serializer hooks to AutoSchema. [#7424]UNICODE_JSON setting in API schema outputs. [#7991]RemoteUserAuthentication. [#7158]Date: 26th March 2021
deque instead of list for tracking throttling .history. (Due to incompatibility with DjangoRedis cache backend. See #7870) [#7872]Date: 25th March 2021
COUNT query when LimitOffsetPagination is configured but pagination params are not included on the request. [#6098]allow_null=True on DecimalField. [#7718]\"Yes\"/\"No\" values with BooleanField. [#7739]PageNumberPagination.get_page_number() method for overriding behavior. [#7652]PrimaryKeyRelatedField fields, instead of casting to ints. [#7597]OrderingFilter. [#7609]deque instead of list for tracking throttling .history. [#7849]Date: 13th October 2020
rest_framework.authtoken.models is imported, but rest_framework.authtoken is not in INSTALLED_APPS. [#7571]get_queryset() methods are not masked. [#7480]Date: 28th September 2020
TokenProxy migration. [#7557]Date: 28th September 2020
--file option to generateschema command. [#7130]tags for OpenAPI schema generation. See the schema docs. [#7184]AutoSchema become public API: get_path_parameters, get_pagination_parameters, get_filter_parameters, get_request_body, get_responses, get_serializer, get_paginator, map_serializer, map_field, map_choice_field, map_field_validators, allows_filters. See the schema docsJSONField. [#7467]SearchFilter now supports nested search on JSONField and HStoreField model fields. [#7121]SearchFilter now supports searching on annotate() fields. [#6240]pk in the admin URL. [#7341]__repr__ for Request instances. [#7239]ListField schema output to include all available child information. [#7137]default=False to be included for BooleanField schema outputs. [#7165]\"type\" information in ChoiceField schema outputs. [#7161]\"type\": \"object\" on schema objects. [#7169]DecimalField. [#7254]ObtainAuthToken view. [#7211]context=... to view .get_serializer() methods. [#7298]PermissionDenied if permission class has one set. [#7306]ChoiceField to a schema output. [#7264]UniqueTogether handling when serializer fields use source=.... [#7143]HEAD requests now set self.action correctly on a ViewSet instance. [#7223]ModelSerializer[Author]. [#7385]charset=None portion in the request Content-Type header when using APIClient. [#7400]\\Z/\\z tokens in OpenAPI regexs. [#7389]PrimaryKeyRelatedField and HyperlinkedRelatedField when source field is actually a property. [#7142]Token.generate_key is now a class method. [#7502]@action warns if method is wrapped in a decorator that does not preserve information using @functools.wraps. [#7098]serializers.NullBooleanField in favor of serializers.BooleanField with allow_null=True [#7122]Date: 30th September 2020
urlize_quoted_links template tag in favor of Django's built-in urlize. Removes a XSS vulnerability for some kinds of content in the browsable API.Date: 5th August 2020
Date: 12th December 2019
.set_context API in favor of a requires_context marker.serializers.HStoreField in OpenAPI schemas. #6914int64 representation for large integers in OpenAPI schemas. #7018.to_representation implementation is provided on a field subclass. #6996Date: 4th September 2019
lowerInitialCamelCase style in OpenAPI operation IDs.minLength/maxLength/minItems/maxItems properties in OpenAPI schemas.FileField.url once in serialization, for improved performance.Date: 29th July 2019
OpenAPI schema fixes.Date: 17th July 2019
uritemplate for OpenAPI schema generation, but not coreapi.Date: 15th July 2019
generateschema --generator_class CLI optionpyyaml>=5.1 #6680user.get_username in templates, in preference to user.username.source=\"*\"SerializerMethodField field name arguments.detail_route decorator in favor of action, which accepts a detail bool. Use @action(detail=True) instead. gh6687list_route decorator in favor of action, which accepts a detail bool. Use @action(detail=False) instead. gh6687Date: 10th May 2019
This is a maintenance release that fixes an error handling bug under Python 2.
"},{"location":"community/release-notes/#393","title":"3.9.3","text":"Date: 29th April 2019
This is the last Django REST Framework release that will support Python 2. Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
Date: 3rd March 2019
_urls cache on register() #6407validators to accept non-list iterables. #6282RemovedInDRF\u2026Warning classes to simplify deprecations. #6480Date: 16th January 2019
limit_choices_to on foreign keys. #6371Date: 18th October 2018
action support for ViewSet suffixes #6081action docs sections #6060Router.register base_name argument in favor of basename. #5990Router.get_default_base_name method in favor of Router.get_default_basename. #5990CharField to disallow null bytes. #6073 To revert to the old behavior, subclass CharField and remove ProhibitNullCharactersValidator from the validators. class NullableCharField(serializers.CharField):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.validators = [\n v\n for v in self.validators\n if not isinstance(v, ProhibitNullCharactersValidator)\n ]\nOpenAPIRenderer and generate_schema management command. #6229e.indexOf is not a function error #5982DjangoObjectPermissionsFilter class, moved to the djangorestframework-guardian package. #6075Date: 6th April 2018
read_only + default unique_together validation. #5922Date: 4th April 2018
Use old url_name behavior in route decorators #5915
For list_route and detail_route maintain the old behavior of url_name, basing it on the url_path instead of the function name.
Date: 3rd April 2018
Breaking Change: Alter read_only plus default behavior. #5886
read_only fields will now always be excluded from writable fields.
Previously read_only fields with a default value would use the default for create and update operations.
In order to maintain the old behavior you may need to pass the value of read_only fields when calling save() in the view:
def perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n Alternatively you may override save() or create() or update() on the serializer as appropriate.
Correct allow_null behavior when required=False #5888
Without an explicit default, allow_null implies a default of null for outgoing serialization. Previously such fields were being skipped when read-only or otherwise not required.
Possible backwards compatibility break if you were relying on such fields being excluded from the outgoing representation. In order to restore the old behavior you can override data to exclude the field when None.
For example:
@property\ndef data(self):\n \"\"\"\n Drop `maybe_none` field if None.\n \"\"\"\n data = super().data\n if 'maybe_none' in data and data['maybe_none'] is None:\n del data['maybe_none']\n return data\n Refactor dynamic route generation and improve viewset action introspectibility. #5705
ViewSets have been provided with new attributes and methods that allow it to introspect its set of actions and the details of the current action.
list_route and detail_route into a single action decorator.ViewSet with .get_extra_actions().url_name and url_path on the decorated method.url_name is now based on the function name, instead of the url_path, as the path is not always suitable (e.g., capturing arguments in the path)..reverse_action() method (added in 3.7.4)self.reverse_action(self.custom_action.url_name)detail initkwarg to indicate if the current action is operating on a collection or a single instance.Additional changes:
list_route & detail_route in favor of action decorator with detail boolean.DynamicRoute with detail boolean.list_route and detail_route maintain the old behavior of url_name, basing it on the url_path instead of the function name.Fix formatting of the 3.7.4 release note #5704
compat._resolve_model() #5733iter(dict) over iter(dict.keys()) #5736python_requires argument to setuptools #5739pip show #5757fields docs #5783__eq__/__ne__ and __repr__ #5787background-attachment: fixed in docs #5777exceptions.APIException output #57630. #5834LimitOffsetPagination.get_count to allow method override #5846Date: 21st December 2017
Date: 21st December 2017
Date: 21st December 2017
Date: 20th December 2017
Schema: Extract method for manual_fields processing #5633
Allows for easier customization of manual_fields processing, for example to provide per-method manual fields. AutoSchema adds get_manual_fields, as the intended override point, and a utility method update_fields, to handle by-name field replacement from a list, which, in general, you are not expected to override.
Note: AutoSchema.__init__ now ensures manual_fields is a list. Previously may have been stored internally as None.
Remove ulrparse compatibility shim; use six instead #5579
TimeDelta.total_seconds() #5577set_rollback() from compat #5591__getattr__ #5617Serializer._declared_fields enable modifying fields on a serializer #5629allow_null=True should not imply a default value #5639allow_null serialization output note #5641Serializer.data for Browsable API rendering when provided invalid data #5646.basename and .reverse_action() to ViewSet #5648override_settings compat #5668required=False #5665UNAUTHENTICATED_USER = None note #5679to_representation docs #5682source=\u2018*\u2019 to custom field docs. #5688Date: 6th November 2017
AppRegistryNotReady error from contrib.auth view imports #5567Date: 6th November 2017
allow_null=True should imply a default serialization value #5518drf_create_token command #5550wheel] section to [bdist_wheel] as the former is legacy #5557Date: 16th October 2017
source fields #5489Date: 6th October 2017
DjangoModelPermissions to ensure user authentication before calling the view's get_queryset() method. As a side effect, this changes the order of the HTTP method permissions and authentication checks, and 405 responses will only be returned when authenticated. If you want to replicate the old behavior, see the PR for details. #5376exclude_from_schema on APIView and api_view decorator. Set schema = None or @schema(None) as appropriate. #5422Timezone-aware DateTimeFields now respect active or default timezone during serialization, instead of always using UTC. #5435
Resolves inconsistency whereby instances were serialized with supplied datetime for create but UTC for retrieve. #3732
Possible backwards compatibility break if you were relying on datetime strings being UTC. Have client interpret datetimes or set default or active timezone (docs) to UTC if needed.
Removed DjangoFilterBackend inline with deprecation policy. Use django_filters.rest_framework.FilterSet and/or django_filters.rest_framework.DjangoFilterBackend instead. #5273
time when encoding. Makes consistent with datetime. BC Change: Previously only milliseconds were encoded. #5440STRICT_JSON setting (default True) to raise exception for the extended float values (nan, inf, -inf) accepted by Python's json module. BC Change: Previously these values would converted to corresponding strings. Set STRICT_JSON to False to restore the previous behavior. #5265page_size parameter in CursorPaginator class #5250DEFAULT_PAGINATION_CLASS None by default. BC Change: If your were just setting PAGE_SIZE to enable pagination you will need to add DEFAULT_PAGINATION_CLASS. The previous default was rest_framework.pagination.PageNumberPagination. There is a system check warning to catch this case. You may silence that if you are setting pagination class on a per-view basis. #5170APIException from get_serializer_fields in schema generation. #5443include_docs_urls #5448get_queryset returned None #5348data description #5361ChoiceField.choices to be set dynamically #5426drf-openapi package in docs #5470data #5472is_list_view recognize RetrieveModel\u2026 views #5480SchemaGenerator.get_serializer_fields has been refactored as AutoSchema.get_serializer_fields and drops the view argument [#5354][gh5354]Date: 21st August 2017
HTML_CUTOFF is set to None. #5174multipart/form-data correctly. #5176test_hyperlinked_related_lookup_url_encoded_exists. #5179list_route & detail_route with kwargs contains curly bracket in url_path #5187Date: 12th May 2017
get_limit in LimitOffsetPagination to return all records. (#4437)page_size attribute. (#5086, #3692).as_view() to view instance. (#5053)extra_kwargs. (#4688)Date: 10th March 2017
mark_safe in API docs template tags. (#4952, #4953)Date: 9th March 2017
markdown dependency is optional. (#4947)Date: 9th March 2017
See the release announcement.
"},{"location":"community/release-notes/#35x-series","title":"3.5.x series","text":""},{"location":"community/release-notes/#354","title":"3.5.4","text":"Date: 10th February 2017
@list_route and @detail_route endpoints. (#4821)PUT requests when prefetch_related is used. (#4661, #4668)Date: 7th November 2016
autofocus support for input controls. (#4650)Date: 1st November 2016
Date: 21st October 2016
rest_framework/compat.py imports. (#4612, #4608, #4601)raise for Python 3.5 compat. (#4600)Date: 20th October 2016
"},{"location":"community/release-notes/#34x-series","title":"3.4.x series","text":""},{"location":"community/release-notes/#347","title":"3.4.7","text":"Date: 21st September 2016
RegexField. (#4489, #4490, #2617)admin.html causing CSRF error. (#4472, #4473)ResolverMatch.func_name of api_view decorated view. (#4465, #4462)APIClient.get() when path contains unicode arguments (#4458)Date: 23rd August 2016
AdminRenderer display of PK only related fields. (#4419, #4423)Date: 19th August 2016
Date: 12th August 2016
max_digits=None on DecimalField. (#4377, #4372)Date: 5th August 2016
Date: 5th August 2016
request.user.is_authenticated as property not method, under Django 1.10+ (#4358, #4354)Date: 28th July 2016
root_renderers argument to DefaultRouter. (#4323, #4268)url and schema_url arguments. (#4321, #4308, #4305)pagination_class = None. (#4314, #4289)get_serializer_class. (#4265, #4285)Accept and Content-Type headers. (#4287, #4313, #4281)Date: 14th July 2016
DecimalField. (#4233)must_call_distinct. (#4215)limit=0 should revert to default limit. (#4194).validated_data and .errors as lists not dicts for ListSerializer. (#4180)AUTH_USER_MODEL compat property. (#4176)OrderingFilter should call get_serializer_class() to determine default fields. (#3964)initial for any serializer.Field. (#3943)field.rel. (#3906)help_text in Browsable API forms. (#3812)lookup_type is deprecated in favor of lookup_expr. (#4259)Date: 14th March 2016.
BooleanField. Thanks to Mikalai Radchuk for the fix. (#3910)Token model as abstract when the authtoken application isn't declared. Thanks to Adam Thomas for the report. (#3860, #3858)QueryParameterVersioning does not use DEFAULT_VERSION setting. Thanks to Brad Montgomery for the fix. (#3833)on_delete on the models. Thanks to Mads Jensen for the fix. (#3832)DateField.to_representation to work with Python 2 unicode. Thanks to Mikalai Radchuk for the fix. (#3819)TimeField not handling string times. Thanks to Areski Belaid for the fix. (#3809)Meta.extra_kwargs. Thanks to Kevin Massey for the report and fix. (#3805, #3804)django-crispy-forms. Thanks to Emmanuelle Delescolle, Jos\u00e9 Padilla and Luis San Pablo for the report, analysis and fix. (#3787, #3636, #3637)Min/MaxValueValidator transfer from a model's DecimalField. Thanks to Kevin Brown for the fix. (#3774)AutoFilterSet to inherit from default_filter_set. Thanks to Tom Linford for the fix. (#3753)DateTimeField does not handle empty values correctly. Thanks to Mick Parker for the report and fix. (#3731, #3726)_get_reverse_relationships() to use correct to_field. Thanks to Benjamin Phillips for the fix. (#3696)get_queryset for RelatedField. Thanks to Ryan Hiebert for the fix. (#3605)Date: 14th December 2015.
ListField enforces input is a list. (#3513)pagination.PageNumberPagination. (#3631, #3684)to_fields attribute. (#3635, #3634)template.render deprecation warnings for Django 1.9. (#3654)NestedBoundField to also handle empty string when rendering its form. (#3677)Date: 4th November 2015.
request.POST (#3592)to_field referring to primary key. (#3593)filter_class is defined. (#3560)Date: 28th October 2015.
to_field when creating ModelSerializer relational fields. (#3526)FilePathField to a serializer field. (#3536)error_messages on ModelSerializer uniqueness constraints. (#3435)max_length constraint for ModelSerializer fields mapped from TextField. (#3509)Date: 27th October 2015.
username in optional logout tag. (#3550)Date: 21th September 2015.
ViewSet.search_fields attribute. (#3324, #3323)allow_empty not working on serializers with many=True. (#3361, #3364)DurationField accepts integers. (#3359)ListField truncation on HTTP PATCH (#3415, #2761)Date: 24th August 2015.
html_cutoff and html_cutoff_text for limiting select dropdowns. (#3313)SearchFilter. (#3316)IPAddressField. ([#3249gh3249) (#3250)LimitOffsetPagination when count=0, offset=0. (#3303)Date: 13th August 2015.
display_value() method for use when displaying relational field select inputs. (#3254)BooleanField checkboxes incorrectly displaying as checked. (#3258)BooleanField to False in all cases. (#2776)WSGIRequest.FILES property without raising incorrect deprecated error. (#3261)Date: 7th August 2015.
1, 0 rendering as true, false in the admin interface. #3227)request.FILES for compat with Django's HTTPRequest class. (#3239)Date: 6th August 2015.
AdminRenderer. (#2926)FilePathField. (#1854)allow_empty to ListField. (#2250)source=<method> on hyperlinked fields. (#2690)ListField(allow_null=True) now allows null as the list value, not null items in the list. (#2766)ManyToMany() maps to allow_empty=False, ManyToMany(blank=True) maps to allow_empty=True. (#2804)OPTIONS requests support nested representations. (#2915)view.action == \"metadata\" for viewsets with OPTIONS requests. (#3115)allow_blank on UUIDField. ([#3130][gh#3130])DecimalField validation. (#3139)allow_blank=False when used with trim_whitespace=True. (#2712)allow_blank argument. (#3011)UnicodeDecodeError when invalid characters included in header with TokenAuthentication. (#2928)@non_atomic_requests decorator. (#3016)SearchFilter. (#2935)\"url\": null in the representation. (#2759)HStoreField to include allow_blank=True in DictField mapping. (#2659)Date: 4th June 2015.
DurationField. (#2481, #2989)format argument to UUIDField. (#2788, #3000)MultipleChoiceField empties incorrectly on a partial update using multipart/form-data (#2993, #2894)RelatedField. (#2981, #2811)unique_together relations. (#2975)ChoiceField/MultipleChoiceField representations. (#2839, #2940)ATOMIC_REQUESTS is set. (#2887, #2034)DecimalField accepts 2E+2 as 200 and validates decimal place correctly. (#2948, #2947)UserModel that change username. (#2952)IPAddressField improvements. (#2747, #2618, #3008)DecimalField for easier subclassing. (#2695)Date: 13rd May 2015.
DateField.to_representation can handle str and empty values. (#2656, #2687, #2869)ModelSerializer used with abstract model. (#2757, #2630)HyperLinkedRelatedField (#2724, #2711).model attribute in permissions (#2818)IntegerField to use compiled decimal regex. (#2853)queryset to raise AssertionError. (#2862)DjangoModelPermissions rely on get_queryset. (#2863)AcceptHeaderVersioning with content negotiation in place. (#2868)DjangoObjectPermissions to use views that define get_queryset. (#2905)Date: 23rd March 2015.
serializer_class is used, even when get_serializer method does not exist on the view. (#2743)lookup_url_kwarg handling in viewsets. (#2685, #2591)rest_framework.views in apps.py (#2678)TypeError if PAGE_SIZE not set (#2667, #2700)min_value field error message references max_value. (#2645)MergeDict. (#2640)Date: 5th March 2015.
For full details see the 3.1 release announcement.
"},{"location":"community/release-notes/#30x-series","title":"3.0.x series","text":""},{"location":"community/release-notes/#305","title":"3.0.5","text":"Date: 10th February 2015.
_closable_objects breaks pickling. (#1850, #2492)User models with Throttling. (#2524)User.db_table in TokenAuthentication migration. (#2479)AttributeError tracebacks on Request objects. (#2530, #2108)ManyRelatedField.get_value clearing field on partial update. (#2475)detail_route and list_route mutable argument. (#2518)TokenAuthentication. (#2519)Date: 28th January 2015.
DictField and support Django 1.8 HStoreField. (#2451, #2106)UUIDField and support Django 1.8 UUIDField. (#2448, #2433, #2432)BaseRenderer.render now raises NotImplementedError. (#2434)ResultDict and ResultList now appear as standard dict/list. (#2421)HiddenField in the HTML form of the web browsable API page. (#2410)OrderedDict for RelatedField.choices. (#2408)HTTP_X_FORWARDED_FOR. (#2401)FileUploadParser with version 3.x. (#2399)ReturnDict. (#2360)Date: 8th January 2015.
MinValueValidator on models.DateField. (#2369)DefaultRouter. (#2351)required=False allows omission of value for output. (#2342)models.TextField. (#2340)ListSerializer for pagination if required. (#2331, #2327)exclude are model fields. (#2319)IntegerField and max_length argument incompatibility. (#2317)format_suffix_patterns to work with Django's i18n_patterns. (#2278)url_path. (#2010)Date: 17th December 2014.
request.user is made available to response middleware. (#2155)Client.logout() also cancels any existing force_authenticate. (#2218, #2259)min_length message for CharField. (#2255)UnicodeDecodeError, which can occur on serializer repr. (#2270, #2279)SlugRelatedField raising UnicodeEncodeError when used as a multiple choice input. (#2290)Date: 11th December 2014.
create() fails. (#2013)FileUploadParser breaks with empty file names and multiple upload handlers. (#2109)BindingDict to support standard dict-functions. (#2135, #2163)validate() to ListSerializer. (#2168, #2225, #2232)FileField. (#2172)ViewSet.as_view(). (#2175)allow_blank to ChoiceField. (#2184, #2239)fields on serializer is not a list of strings. (#2193, #2213)validated_attrs argument renamed to validated_data in Serializer create()/update(). (#2197)fields on serializer is not a list of strings. (#2213)Date: 1st December 2014
For full details see the 3.0 release announcement.
For older release notes, please see the version 2.x documentation.
"},{"location":"community/third-party-packages/","title":"Third Party Packages","text":"Software ecosystems [\u2026] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.
\u2014 Jan Bosch.
"},{"location":"community/third-party-packages/#about-third-party-packages","title":"About Third Party Packages","text":"Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.
We support, encourage and strongly favor the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.
We aim to make creating third party packages as easy as possible, whilst keeping a simple and well maintained core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.
If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the Mailing List.
"},{"location":"community/third-party-packages/#creating-a-third-party-package","title":"Creating a Third Party Package","text":""},{"location":"community/third-party-packages/#version-compatibility","title":"Version compatibility","text":"Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a compat.py module, and should provide a single common interface that the rest of the codebase can use.
Check out Django REST framework's compat.py for an example.
"},{"location":"community/third-party-packages/#once-your-package-is-available","title":"Once your package is available","text":"Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful.
"},{"location":"community/third-party-packages/#adding-to-the-django-rest-framework-grid","title":"Adding to the Django REST framework grid","text":"We suggest adding your package to the REST Framework grid on Django Packages.
"},{"location":"community/third-party-packages/#adding-to-the-django-rest-framework-docs","title":"Adding to the Django REST framework docs","text":"Create a Pull Request on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under Third party packages of the API Guide section that best applies, like Authentication or Permissions. You can also link your package under the Third Party Packages section.
"},{"location":"community/third-party-packages/#announce-on-the-discussion-group","title":"Announce on the discussion group.","text":"You can also let others know about your package through the discussion group.
"},{"location":"community/third-party-packages/#existing-third-party-packages","title":"Existing Third Party Packages","text":"Django REST Framework has a growing community of developers, packages, and resources.
Check out a grid detailing all the packages and ecosystem around Django REST Framework at Django Packages.
To submit new content, create a pull request.
"},{"location":"community/third-party-packages/#async-support","title":"Async Support","text":"ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here.ModelViewSet's Queryset in a clean, simple and configurable way. It also supports validations on incoming query params and their values.DjangoObjectPermissionsFilter previously found in DRF.ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here.There are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.
"},{"location":"community/tutorials-and-resources/#books","title":"Books","text":""},{"location":"community/tutorials-and-resources/#courses","title":"Courses","text":"Want your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please submit a pull request or email us!
"},{"location":"theme/src/","title":"DRF logos","text":"This folder contains the source file for the DRF logos as Figma file.
"},{"location":"topics/ajax-csrf-cors/","title":"Working with AJAX, CSRF & CORS","text":"\"Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability \u2014 very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one.\"
\u2014 Jeff Atwood
"},{"location":"topics/ajax-csrf-cors/#javascript-clients","title":"Javascript clients","text":"If you\u2019re building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.
AJAX requests that are made within the same context as the API they are interacting with will typically use SessionAuthentication. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.
AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as TokenAuthentication.
Cross Site Request Forgery protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.
To guard against these type of attacks, you need to do two things:
GET, HEAD and OPTIONS cannot be used to alter any server-side state.POST, PUT, PATCH and DELETE, always require a valid CSRF token.If you're using SessionAuthentication you'll need to include valid CSRF tokens for any POST, PUT, PATCH or DELETE operations.
In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.
"},{"location":"topics/ajax-csrf-cors/#cors","title":"CORS","text":"Cross-Origin Resource Sharing is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.
The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
Adam Johnson maintains the django-cors-headers package, which is known to work correctly with REST framework APIs.
"},{"location":"topics/browsable-api/","title":"The Browsable API","text":"It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.
\u2014 Alfred North Whitehead, An Introduction to Mathematics (1911)
API may stand for Application Programming Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the HTML format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using POST, PUT, and DELETE.
If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The rest_framework package includes a reverse helper for this purpose.
By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using ?format= in the request, so you can look at the raw JSON response in a browser by adding ?format=json to the URL. There are helpful extensions for viewing JSON in Firefox and Chrome.
To quickly add authentication to the browesable api, add a routes named \"login\" and \"logout\" under the namespace \"rest_framework\". DRF provides default routes for this which you can add to your urlconf:
from django.urls import include, path\n\nurlpatterns = [\n # ...\n path(\"api-auth/\", include(\"rest_framework.urls\", namespace=\"rest_framework\"))\n]\n"},{"location":"topics/browsable-api/#customizing","title":"Customizing","text":"The browsable API is built with Twitter's Bootstrap (v 3.4.1), making it easy to customize the look-and-feel.
To customize the default style, create a template called rest_framework/api.html that extends from rest_framework/base.html. For example:
templates/rest_framework/api.html
{% extends \"rest_framework/base.html\" %}\n\n... # Override blocks with required customizations\n"},{"location":"topics/browsable-api/#overriding-the-default-theme","title":"Overriding the default theme","text":"To replace the default theme, add a bootstrap_theme block to your api.html and insert a link to the desired Bootstrap theme css file. This will completely replace the included theme.
{% block bootstrap_theme %}\n <link rel=\"stylesheet\" href=\"/path/to/my/bootstrap.css\" type=\"text/css\">\n{% endblock %}\n Suitable pre-made replacement themes are available at Bootswatch. To use any of the Bootswatch themes, simply download the theme's bootstrap.min.css file, add it to your project, and replace the default one as described above. Make sure that the Bootstrap version of the new theme matches that of the default theme.
You can also change the navbar variant, which by default is navbar-inverse, using the bootstrap_navbar_variant block. The empty {% block bootstrap_navbar_variant %}{% endblock %} will use the original Bootstrap navbar style.
Full example:
{% extends \"rest_framework/base.html\" %}\n\n{% block bootstrap_theme %}\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootswatch@3.4.1/flatly/bootstrap.min.css\" type=\"text/css\">\n{% endblock %}\n\n{% block bootstrap_navbar_variant %}{% endblock %}\n For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the style block.
Screenshot of the bootswatch 'Cerulean' theme
Screenshot of the bootswatch 'Slate' theme
"},{"location":"topics/browsable-api/#third-party-packages-for-customization","title":"Third party packages for customization","text":"You can use a third party package for customization, rather than doing it by yourself. Here is 3 packages for customizing the API:
Screenshots of the drf-restwind
Screenshot of the drf-redesign
Screenshot of the drf-material
"},{"location":"topics/browsable-api/#blocks","title":"Blocks","text":"All of the blocks available in the browsable API base template that can be used in your api.html.
body - The entire html <body>.bodyclass - Class attribute for the <body> tag, empty by default.bootstrap_theme - CSS for the Bootstrap theme.bootstrap_navbar_variant - CSS class for the navbar.branding - Branding section of the navbar, see Bootstrap components.breadcrumbs - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.script - JavaScript files for the page.style - CSS stylesheets for the page.title - Title of the page.userlinks - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links.All of the standard Bootstrap components are available.
"},{"location":"topics/browsable-api/#tooltips","title":"Tooltips","text":"The browsable API makes use of the Bootstrap tooltips component. Any element with the js-tooltip class and a title attribute has that title content will display a tooltip on hover events.
To add branding and customize the look-and-feel of the login template, create a template called login.html and add it to your project, eg: templates/rest_framework/login.html. The template should extend from rest_framework/login_base.html.
You can add your site name or branding by including the branding block:
{% extends \"rest_framework/login_base.html\" %}\n\n{% block branding %}\n <h3 style=\"margin: 0 0 20px;\">My Site Name</h3>\n{% endblock %}\n You can also customize the style by adding the bootstrap_theme or style block similar to api.html.
The context that's available to the template:
allowed_methods : A list of methods allowed by the resourceapi_settings : The API settingsavailable_formats : A list of formats allowed by the resourcebreadcrumblist : The list of links following the chain of nested resourcescontent : The content of the API responsedescription : The description of the resource, generated from its docstringname : The name of the resourcepost_form : A form instance for use by the POST form (if allowed)put_form : A form instance for use by the PUT form (if allowed)display_edit_forms : A boolean indicating whether or not POST, PUT and PATCH forms will be displayedrequest : The request objectresponse : The response objectversion : The version of Django REST Frameworkview : The view handling the requestFORMAT_PARAM : The view can accept a format overrideMETHOD_PARAM : The view can accept a method overrideYou can override the BrowsableAPIRenderer.get_context() method to customize the context that gets passed to the template.
For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have api.html extend base.html. Then the page content and capabilities are entirely up to you.
ChoiceField with large numbers of items.","text":"When a relationship or ChoiceField has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly.
The simplest option in this case is to replace the select input with a standard text input. For example:
author = serializers.HyperlinkedRelatedField(\n queryset=User.objects.all(),\n style={'base_template': 'input.html'}\n)\n"},{"location":"topics/browsable-api/#autocomplete","title":"Autocomplete","text":"An alternative, but more complex option would be to replace the input with an autocomplete widget, that only loads and renders a subset of the available options as needed. If you need to do this you'll need to do some work to build a custom autocomplete HTML template yourself.
There are a variety of packages for autocomplete widgets, such as django-autocomplete-light, that you may want to refer to. Note that you will not be able to simply include these components as standard widgets, but will need to write the HTML template explicitly. This is because REST framework 3.0 no longer supports the widget keyword argument since it now uses templated HTML generation.
\"There are two noncontroversial uses for overloaded POST. The first is to simulate HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE\"
\u2014 RESTful Web Services, Leonard Richardson & Sam Ruby.
In order to allow the browsable API to function, there are a couple of browser enhancements that REST framework needs to provide.
As of version 3.3.0 onwards these are enabled with javascript, using the ajax-form library.
"},{"location":"topics/browser-enhancements/#browser-based-put-delete-etc","title":"Browser based PUT, DELETE, etc...","text":"The AJAX form library supports browser-based PUT, DELETE and other methods on HTML forms.
After including the library, use the data-method attribute on the form, like so:
<form action=\"/\" data-method=\"PUT\">\n <input name='foo'/>\n ...\n</form>\n Note that prior to 3.3.0, this support was server-side rather than javascript based. The method overloading style (as used in Ruby on Rails) is no longer supported due to subtle issues that it introduces in request parsing.
"},{"location":"topics/browser-enhancements/#browser-based-submission-of-non-form-content","title":"Browser based submission of non-form content","text":"Browser-based submission of content types such as JSON are supported by the AJAX form library, using form fields with data-override='content-type' and data-override='content' attributes.
For example:
<form action=\"/\">\n <input data-override='content-type' value='application/json' type='hidden'/>\n <textarea data-override='content'>{}</textarea>\n <input type=\"submit\"/>\n </form>\n Note that prior to 3.3.0, this support was server-side rather than javascript based.
"},{"location":"topics/browser-enhancements/#url-based-format-suffixes","title":"URL based format suffixes","text":"REST framework can take ?format=json style URL parameters, which can be a useful shortcut for determining which content type should be returned from the view.
This behavior is controlled using the URL_FORMAT_OVERRIDE setting.
Prior to version 3.3.0 the semi extension header X-HTTP-Method-Override was supported for overriding the request method. This behavior is no longer in core, but can be adding if needed using middleware.
For example:
METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'\n\nclass MethodOverrideMiddleware:\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n if request.method == 'POST' and METHOD_OVERRIDE_HEADER in request.META:\n request.method = request.META[METHOD_OVERRIDE_HEADER]\n return self.get_response(request)\n"},{"location":"topics/browser-enhancements/#url-based-accept-headers","title":"URL based accept headers","text":"Until version 3.3.0 REST framework included built-in support for ?accept=application/json style URL parameters, which would allow the Accept header to be overridden.
Since the introduction of the content negotiation API this behavior is no longer included in core, but may be added using a custom content negotiation class, if needed.
For example:
class AcceptQueryParamOverride()\n def get_accept_list(self, request):\n header = request.META.get('HTTP_ACCEPT', '*/*')\n header = request.query_params.get('_accept', header)\n return [token.strip() for token in header.split(',')]\n"},{"location":"topics/browser-enhancements/#doesnt-html5-support-put-and-delete-forms","title":"Doesn't HTML5 support PUT and DELETE forms?","text":"Nope. It was at one point intended to support PUT and DELETE forms, but was later dropped from the spec. There remains ongoing discussion about adding support for PUT and DELETE, as well as how to support content types other than form-encoded data.
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.
\u2014 Roy Fielding, REST APIs must be hypertext driven
REST framework provides a range of different choices for documenting your API. The following is a non-exhaustive list of some of the most popular options.
"},{"location":"topics/documenting-your-api/#third-party-packages-for-openapi-support","title":"Third-party packages for OpenAPI support","text":"REST framework recommends using third-party packages for generating and presenting OpenAPI schemas, as they provide more features and flexibility than the built-in (deprecated) implementation.
"},{"location":"topics/documenting-your-api/#drf-spectacular","title":"drf-spectacular","text":"drf-spectacular is an OpenAPI 3 schema generation library with explicit focus on extensibility, customizability and client generation. It is the recommended way for generating and presenting OpenAPI schemas.
The library aims to extract as much schema information as possible, while providing decorators and extensions for easy customization. There is explicit support for swagger-codegen, SwaggerUI and Redoc, i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters, documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
"},{"location":"topics/documenting-your-api/#drf-yasg","title":"drf-yasg","text":"drf-yasg is a Swagger / OpenAPI 2 generation tool implemented without using the schema generation provided by Django Rest Framework.
It aims to implement as much of the OpenAPI 2 specification as possible - nested schemas, named models, response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code generation tools like swagger-codegen.
This also translates into a very useful interactive documentation viewer in the form of swagger-ui:
Warning
Deprecation notice: REST framework's built-in support for generating OpenAPI schemas is deprecated in favor of third-party packages that provide this functionality instead. As a replacement, we recommend using drf-spectacular.
There are a number of packages available that allow you to generate HTML documentation pages from OpenAPI schemas.
Two popular options are Swagger UI and ReDoc.
Both require little more than the location of your static schema file or dynamic SchemaView endpoint.
Assuming you've followed the example from the schemas documentation for routing a dynamic SchemaView, a minimal Django template for using Swagger UI might be this:
<!DOCTYPE html>\n<html>\n <head>\n <title>Swagger</title>\n <meta charset=\"utf-8\"/>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"//unpkg.com/swagger-ui-dist@3/swagger-ui.css\" />\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js\"></script>\n <script>\n const ui = SwaggerUIBundle({\n url: \"{% url schema_url %}\",\n dom_id: '#swagger-ui',\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n ],\n layout: \"BaseLayout\",\n requestInterceptor: (request) => {\n request.headers['X-CSRFToken'] = \"{{ csrf_token }}\"\n return request;\n }\n })\n </script>\n </body>\n</html>\n Save this in your templates folder as swagger-ui.html. Then route a TemplateView in your project's URL conf:
from django.views.generic import TemplateView\n\nurlpatterns = [\n # ...\n # Route TemplateView to serve Swagger UI template.\n # * Provide `extra_context` with view name of `SchemaView`.\n path(\n \"swagger-ui/\",\n TemplateView.as_view(\n template_name=\"swagger-ui.html\",\n extra_context={\"schema_url\": \"openapi-schema\"},\n ),\n name=\"swagger-ui\",\n ),\n]\n See the Swagger UI documentation for advanced usage.
"},{"location":"topics/documenting-your-api/#a-minimal-example-with-redoc","title":"A minimal example with ReDoc.","text":"Assuming you've followed the example from the schemas documentation for routing a dynamic SchemaView, a minimal Django template for using ReDoc might be this:
<!DOCTYPE html>\n<html>\n <head>\n <title>ReDoc</title>\n <!-- needed for adaptive design -->\n <meta charset=\"utf-8\"/>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link href=\"https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700\" rel=\"stylesheet\">\n <!-- ReDoc doesn't change outer page styles -->\n <style>\n body {\n margin: 0;\n padding: 0;\n }\n </style>\n </head>\n <body>\n <redoc spec-url='{% url schema_url %}'></redoc>\n <script src=\"https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js\"> </script>\n </body>\n</html>\n Save this in your templates folder as redoc.html. Then route a TemplateView in your project's URL conf:
from django.views.generic import TemplateView\n\nurlpatterns = [\n # ...\n # Route TemplateView to serve the ReDoc template.\n # * Provide `extra_context` with view name of `SchemaView`.\n path(\n \"redoc/\",\n TemplateView.as_view(\n template_name=\"redoc.html\", extra_context={\"schema_url\": \"openapi-schema\"}\n ),\n name=\"redoc\",\n ),\n]\n See the ReDoc documentation for advanced usage.
"},{"location":"topics/documenting-your-api/#self-describing-apis","title":"Self describing APIs","text":"The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.
"},{"location":"topics/documenting-your-api/#setting-the-title","title":"Setting the title","text":"The title that is used in the browsable API is generated from the view class name or function name. Any trailing View or ViewSet suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.
For example, the view UserListView, will be named User List when presented in the browsable API.
When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set UserViewSet will generate views named User List and User Instance.
The description in the browsable API is generated from the docstring of the view or viewset.
If the python Markdown library is installed, then markdown syntax may be used in the docstring, and will be converted to HTML in the browsable API. For example:
class AccountListView(views.APIView):\n \"\"\"\n Returns a list of all **active** accounts in the system.\n\n For more details on how accounts are activated please [see here][ref].\n\n [ref]: http://example.com/activating-accounts\n \"\"\"\n Note that when using viewsets the basic docstring is used for all generated views. To provide descriptions for each view, such as for the list and retrieve views, use docstring sections as described in Schemas as documentation: Examples.
"},{"location":"topics/documenting-your-api/#the-options-method","title":"TheOPTIONS method","text":"REST framework APIs also support programmatically accessible descriptions, using the OPTIONS HTTP method. A view will respond to an OPTIONS request with metadata including the name, description, and the various media types it accepts and responds with.
When using the generic views, any OPTIONS requests will additionally respond with metadata regarding any POST or PUT actions available, describing which fields are on the serializer.
You can modify the response behavior to OPTIONS requests by overriding the options view method and/or by providing a custom Metadata class. For example:
def options(self, request, *args, **kwargs):\n \"\"\"\n Don't include the view description in OPTIONS responses.\n \"\"\"\n meta = self.metadata_class()\n data = meta.determine_metadata(request, self)\n data.pop('description')\n return Response(data=data, status=status.HTTP_200_OK)\n See the Metadata docs for more details.
"},{"location":"topics/documenting-your-api/#the-hypermedia-approach","title":"The hypermedia approach","text":"To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.
In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the media types that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.
To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The REST, Hypermedia & HATEOAS section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.
"},{"location":"topics/html-and-forms/","title":"HTML & Forms","text":"REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates.
"},{"location":"topics/html-and-forms/#rendering-html","title":"Rendering HTML","text":"In order to return HTML responses you'll need to use either TemplateHTMLRenderer, or StaticHTMLRenderer.
The TemplateHTMLRenderer class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
The StaticHTMLRender class expects the response to contain a string of the pre-rendered HTML content.
Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.
Here's an example of a view that returns a list of \"Profile\" instances, rendered in an HTML template:
views.py:
from my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass ProfileList(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_list.html'\n\n def get(self, request):\n queryset = Profile.objects.all()\n return Response({'profiles': queryset})\n profile_list.html:
<html><body>\n<h1>Profiles</h1>\n<ul>\n {% for profile in profiles %}\n <li>{{ profile.name }}</li>\n {% endfor %}\n</ul>\n</body></html>\n"},{"location":"topics/html-and-forms/#rendering-forms","title":"Rendering Forms","text":"Serializers may be rendered as forms by using the render_form template tag, and including the serializer instance as context to the template.
The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
views.py:
from django.shortcuts import get_object_or_404\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileDetail(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_detail.html'\n\n def get(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile)\n return Response({'serializer': serializer, 'profile': profile})\n\n def post(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile, data=request.data)\n if not serializer.is_valid():\n return Response({'serializer': serializer, 'profile': profile})\n serializer.save()\n return redirect('profile-list')\n profile_detail.html:
{% load rest_framework %}\n\n<html><body>\n\n<h1>Profile - {{ profile.name }}</h1>\n\n<form action=\"{% url 'profile-detail' pk=profile.pk %}\" method=\"POST\">\n {% csrf_token %}\n {% render_form serializer %}\n <input type=\"submit\" value=\"Save\">\n</form>\n\n</body></html>\n"},{"location":"topics/html-and-forms/#using-template-packs","title":"Using template packs","text":"The render_form tag takes an optional template_pack argument, that specifies which template directory should be used for rendering the form and form fields.
REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are horizontal, vertical, and inline. The default style is horizontal. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.
The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
<head>\n \u2026\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\">\n</head>\n Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.
Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a \"Login\" form.
class LoginSerializer(serializers.Serializer):\n email = serializers.EmailField(\n max_length=100,\n style={'placeholder': 'Email', 'autofocus': True}\n )\n password = serializers.CharField(\n max_length=100,\n style={'input_type': 'password', 'placeholder': 'Password'}\n )\n remember_me = serializers.BooleanField()\n"},{"location":"topics/html-and-forms/#rest_frameworkvertical","title":"rest_framework/vertical","text":"Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.
This is the default template pack.
{% load rest_framework %}\n\n...\n\n<form action=\"{% url 'login' %}\" method=\"post\" novalidate>\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/vertical' %}\n <button type=\"submit\" class=\"btn btn-default\">Sign in</button>\n</form>\n "},{"location":"topics/html-and-forms/#rest_frameworkhorizontal","title":"rest_framework/horizontal","text":"Presents labels and controls alongside each other, using a 2/10 column split.
This is the form style used in the browsable API and admin renderers.
{% load rest_framework %}\n\n...\n\n<form class=\"form-horizontal\" action=\"{% url 'login' %}\" method=\"post\" novalidate>\n {% csrf_token %}\n {% render_form serializer %}\n <div class=\"form-group\">\n <div class=\"col-sm-offset-2 col-sm-10\">\n <button type=\"submit\" class=\"btn btn-default\">Sign in</button>\n </div>\n </div>\n</form>\n "},{"location":"topics/html-and-forms/#rest_frameworkinline","title":"rest_framework/inline","text":"A compact form style that presents all the controls inline.
{% load rest_framework %}\n\n...\n\n<form class=\"form-inline\" action=\"{% url 'login' %}\" method=\"post\" novalidate>\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/inline' %}\n <button type=\"submit\" class=\"btn btn-default\">Sign in</button>\n</form>\n "},{"location":"topics/html-and-forms/#field-styles","title":"Field styles","text":"Serializer fields can have their rendering style customized by using the style keyword argument. This argument is a dictionary of options that control the template and layout used.
The most common way to customize the field style is to use the base_template style keyword argument to select which template in the template pack should be use.
For example, to render a CharField as an HTML textarea rather than the default HTML input, you would use something like this:
details = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html'}\n)\n If you instead want a field to be rendered using a custom template that is not part of an included template pack, you can instead use the template style option, to fully specify a template name:
details = serializers.CharField(\n max_length=1000,\n style={'template': 'my-field-templates/custom-input.html'}\n)\n Field templates can also use additional style properties, depending on their type. For example, the textarea.html template also accepts a rows property that can be used to affect the sizing of the control.
details = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html', 'rows': 10}\n)\n The complete list of base_template options and their associated style options is listed below.
CharField rows, placeholder, hide_label select.html ChoiceField or relational field types hide_label radio.html ChoiceField or relational field types inline, hide_label select_multiple.html MultipleChoiceField or relational fields with many=True hide_label checkbox_multiple.html MultipleChoiceField or relational fields with many=True inline, hide_label checkbox.html BooleanField hide_label fieldset.html Nested serializer hide_label list_fieldset.html ListField or nested serializer with many=True hide_label"},{"location":"topics/internationalization/","title":"Internationalization","text":"Supporting internationalization is not optional. It must be a core feature.
\u2014 Jannis Leidel, speaking at Django Under the Hood, 2015.
REST framework ships with translatable error messages. You can make these appear in your language enabling Django's standard translation mechanisms.
Doing so will allow you to:
LANGUAGE_CODE Django setting.LocaleMiddleware included with Django. A typical usage for API clients would be to include an Accept-Language request header.You can change the default language by using the standard Django LANGUAGE_CODE setting:
LANGUAGE_CODE = \"es-es\"\n You can turn on per-request language requests by adding LocalMiddleware to your MIDDLEWARE setting:
MIDDLEWARE = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n]\n When per-request internationalization is enabled, client requests will respect the Accept-Language header where possible. For example, let's make a request for an unsupported media type:
Request
GET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org\n Response
HTTP/1.0 406 NOT ACCEPTABLE\n\n{\"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"}\n REST framework includes these built-in translations both for standard exception cases, and for serializer validation errors.
Note that the translations only apply to the error strings themselves. The format of error messages, and the keys of field names will remain the same. An example 400 Bad Request response body might look like this:
{\"detail\": {\"username\": [\"Esse campo deve ser \u00fanico.\"]}}\n If you want to use different string for parts of the response such as detail and non_field_errors then you can modify this behavior by using a custom exception handler.
By default all available languages will be supported.
If you only wish to support a subset of the available languages, use Django's standard LANGUAGES setting:
LANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n]\n"},{"location":"topics/internationalization/#adding-new-translations","title":"Adding new translations","text":"REST framework translations are managed on GitHub. You can contribute new translation languages or update existing ones by following the guidelines in the Contributing to REST Framework section and submitting a pull request.
Sometimes you may need to add translation strings to your project locally. You may need to do this if:
This guide assumes you are already familiar with how to translate a Django app. If you're not, start by reading Django's translation docs.
If you're translating a new language you'll need to translate the existing REST framework error messages:
Make a new folder where you want to store the internationalization resources. Add this path to your LOCALE_PATHS setting.
Now create a subfolder for the language you want to translate. The folder should be named using locale name notation. For example: de, pt_BR, es_AR.
Now copy the base translations file from the REST framework source code into your translations folder.
Edit the django.po file you've just copied, translating all the error messages.
Run manage.py compilemessages -l pt_BR to make the translations available for Django to use. You should see a message like processing file django.po in <...>/locale/pt_BR/LC_MESSAGES.
Restart your development server to see the changes take effect.
If you're only translating custom error messages that exist inside your project codebase you don't need to copy the REST framework source django.po file into a LOCALE_PATHS folder, and can instead simply run Django's standard makemessages process.
If you want to allow per-request language preferences you'll need to include django.middleware.locale.LocaleMiddleware in your MIDDLEWARE setting.
You can find more information on how the language preference is determined in the Django documentation. For reference, the method is:
LANGUAGE_SESSION_KEY key in the current user\u2019s session.Accept-Language HTTP header.LANGUAGE_CODE setting.For API clients the most appropriate of these will typically be to use the Accept-Language header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an Accept-Language header for API clients rather than using language URL prefixes.
You keep using that word \"REST\". I do not think it means what you think it means.
\u2014 Mike Amundsen, REST fest 2012 keynote.
First off, the disclaimer. The name \"Django REST framework\" was decided back in early 2011 and was chosen simply to ensure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of \"Web APIs\".
If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.
The following fall into the \"required reading\" category.
For a more thorough background, check out Klabnik's Hypermedia API reading list.
"},{"location":"topics/rest-hypermedia-hateoas/#building-hypermedia-apis-with-rest-framework","title":"Building Hypermedia APIs with REST framework","text":"REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.
"},{"location":"topics/rest-hypermedia-hateoas/#what-rest-framework-provides","title":"What REST framework provides.","text":"It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.
REST framework also includes serialization and parser/renderer components that make it easy to build appropriate media types, hyperlinked relations for building well-connected systems, and great support for content negotiation.
"},{"location":"topics/rest-hypermedia-hateoas/#what-rest-framework-doesnt-provide","title":"What REST framework doesn't provide.","text":"What REST framework doesn't do is give you machine readable hypermedia formats such as HAL, Collection+JSON, JSON API or HTML microformats by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labeled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
"},{"location":"topics/writable-nested-serializers/","title":"Writable nested serializers","text":"To save HTTP requests, it may be convenient to send related documents along with the request.
\u2014 JSON API specification for Ember Data.
"},{"location":"topics/writable-nested-serializers/#writable-nested-serializers","title":"Writable nested serializers","text":"Although flat data structures serve to properly delineate between the individual entities in your service, there are cases where it may be more appropriate or convenient to use nested data structures.
Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependencies between the various model instances, and the need to save or delete multiple instances in a single action.
"},{"location":"topics/writable-nested-serializers/#one-to-many-data-structures","title":"One-to-many data structures","text":"Example of a read-only nested serializer. Nothing complex to worry about here.
class ToDoItemSerializer(serializers.ModelSerializer):\n class Meta:\n model = ToDoItem\n fields = ['text', 'is_completed']\n\nclass ToDoListSerializer(serializers.ModelSerializer):\n items = ToDoItemSerializer(many=True, read_only=True)\n\n class Meta:\n model = ToDoList\n fields = ['title', 'items']\n Some example output from our serializer.
{\n 'title': 'Leaving party preparations',\n 'items': [\n {'text': 'Compile playlist', 'is_completed': True},\n {'text': 'Send invites', 'is_completed': False},\n {'text': 'Clean house', 'is_completed': False}\n ]\n}\n Let's take a look at updating our nested one-to-many data structure.
"},{"location":"topics/writable-nested-serializers/#validation-errors","title":"Validation errors","text":""},{"location":"topics/writable-nested-serializers/#adding-and-removing-items","title":"Adding and removing items","text":""},{"location":"topics/writable-nested-serializers/#making-patch-requests","title":"Making PATCH requests","text":""},{"location":"tutorial/1-serialization/","title":"Tutorial 1: Serialization","text":""},{"location":"tutorial/1-serialization/#introduction","title":"Introduction","text":"This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.
The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the quickstart documentation instead.
Note
The code for this tutorial is available in the encode/rest-framework-tutorial repository on GitHub. Feel free to clone the repository and see the code in action.
"},{"location":"tutorial/1-serialization/#setting-up-a-new-environment","title":"Setting up a new environment","text":"Before we do anything else we'll create a new virtual environment called .venv, using venv. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.
python3 -m venv .venv\nsource .venv/bin/activate\n If you use Bash for Windows
python3 -m venv .venv\nsource .venv\\Scripts\\activate\n Now that we're inside a virtual environment, we can install our package requirements.
pip install django\npip install djangorestframework\npip install pygments # We'll be using this for the code highlighting\n Tip
To exit the virtual environment at any time, just type deactivate. For more information see the venv documentation.
Okay, we're ready to get coding. To get started, let's create a new project to work with.
cd ~\ndjango-admin startproject tutorial\ncd tutorial\n Once that's done we can create an app that we'll use to create a simple Web API.
python manage.py startapp snippets\n We'll need to add our new snippets app and the rest_framework app to INSTALLED_APPS. Let's edit the tutorial/settings.py file:
INSTALLED_APPS = [\n ...\n 'rest_framework',\n 'snippets',\n]\n Okay, we're ready to roll.
"},{"location":"tutorial/1-serialization/#creating-a-model-to-work-with","title":"Creating a model to work with","text":"For the purposes of this tutorial we're going to start by creating a simple Snippet model that is used to store code snippets. Go ahead and edit the snippets/models.py file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
from django.db import models\nfrom pygments.lexers import get_all_lexers\nfrom pygments.styles import get_all_styles\n\nLEXERS = [item for item in get_all_lexers() if item[1]]\nLANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])\nSTYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])\n\n\nclass Snippet(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n title = models.CharField(max_length=100, blank=True, default=\"\")\n code = models.TextField()\n linenos = models.BooleanField(default=False)\n language = models.CharField(\n choices=LANGUAGE_CHOICES, default=\"python\", max_length=100\n )\n style = models.CharField(choices=STYLE_CHOICES, default=\"friendly\", max_length=100)\n\n class Meta:\n ordering = [\"created\"]\n We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
python manage.py makemigrations snippets\npython manage.py migrate snippets\n"},{"location":"tutorial/1-serialization/#creating-a-serializer-class","title":"Creating a Serializer class","text":"The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as json. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the snippets directory named serializers.py and add the following.
from rest_framework import serializers\nfrom snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass SnippetSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n title = serializers.CharField(required=False, allow_blank=True, max_length=100)\n code = serializers.CharField(style={\"base_template\": \"textarea.html\"})\n linenos = serializers.BooleanField(required=False)\n language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default=\"python\")\n style = serializers.ChoiceField(choices=STYLE_CHOICES, default=\"friendly\")\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Snippet` instance, given the validated data.\n \"\"\"\n return Snippet.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Snippet` instance, given the validated data.\n \"\"\"\n instance.title = validated_data.get(\"title\", instance.title)\n instance.code = validated_data.get(\"code\", instance.code)\n instance.linenos = validated_data.get(\"linenos\", instance.linenos)\n instance.language = validated_data.get(\"language\", instance.language)\n instance.style = validated_data.get(\"style\", instance.style)\n instance.save()\n return instance\n The first part of the serializer class defines the fields that get serialized/deserialized. The create() and update() methods define how fully fledged instances are created or modified when calling serializer.save()
A serializer class is very similar to a Django Form class, and includes similar validation flags on the various fields, such as required, max_length and default.
The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The {'base_template': 'textarea.html'} flag above is equivalent to using widget=widgets.Textarea on a Django Form class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.
We can actually also save ourselves some time by using the ModelSerializer class, as we'll see later, but for now we'll keep our serializer definition explicit.
Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.
python manage.py shell\n Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
>>> from snippets.models import Snippet\n>>> from snippets.serializers import SnippetSerializer\n>>> from rest_framework.renderers import JSONRenderer\n>>> from rest_framework.parsers import JSONParser\n\n>>> snippet = Snippet(code='foo = \"bar\"\\n')\n>>> snippet.save()\n\n>>> snippet = Snippet(code='print(\"hello, world\")\\n')\n>>> snippet.save()\n We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
>>> serializer = SnippetSerializer(snippet)\n>>> serializer.data\n{'id': 2, 'title': '', 'code': 'print(\"hello, world\")\\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}\n At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into json.
>>> content = JSONRenderer().render(serializer.data)\n>>> content\nb'{\"id\":2,\"title\":\"\",\"code\":\"print(\\\\\"hello, world\\\\\")\\\\n\",\"linenos\":false,\"language\":\"python\",\"style\":\"friendly\"}'\n Deserialization is similar. First we parse a stream into Python native datatypes...
>>> import io\n\n>>> stream = io.BytesIO(content)\n>>> data = JSONParser().parse(stream)\n ...then we restore those native datatypes into a fully populated object instance.
>>> serializer = SnippetSerializer(data=data)\n>>> serializer.is_valid()\nTrue\n>>> serializer.validated_data\n{'title': '', 'code': 'print(\"hello, world\")', 'linenos': False, 'language': 'python', 'style': 'friendly'}\n>>> serializer.save()\n<Snippet: Snippet object>\n Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.
We can also serialize querysets instead of model instances. To do so we simply add a many=True flag to the serializer arguments.
>>> serializer = SnippetSerializer(Snippet.objects.all(), many=True)\n>>> serializer.data\n[{'id': 1, 'title': '', 'code': 'foo = \"bar\"\\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 2, 'title': '', 'code': 'print(\"hello, world\")\\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 3, 'title': '', 'code': 'print(\"hello, world\")', 'linenos': False, 'language': 'python', 'style': 'friendly'}]\n"},{"location":"tutorial/1-serialization/#using-modelserializers","title":"Using ModelSerializers","text":"Our SnippetSerializer class is replicating a lot of information that's also contained in the Snippet model. It would be nice if we could keep our code a bit more concise.
In the same way that Django provides both Form classes and ModelForm classes, REST framework includes both Serializer classes, and ModelSerializer classes.
Let's look at refactoring our serializer using the ModelSerializer class. Open the file snippets/serializers.py again, and replace the SnippetSerializer class with the following.
from rest_framework import serializers\nfrom snippets.models import Snippet\n\n\nclass SnippetSerializer(serializers.ModelSerializer):\n class Meta:\n model = Snippet\n fields = [\"id\", \"title\", \"code\", \"linenos\", \"language\", \"style\"]\n One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with python manage.py shell, then try the following:
>>> from snippets.serializers import SnippetSerializer\n\n>>> serializer = SnippetSerializer()\n>>> print(repr(serializer))\nSnippetSerializer():\n id = IntegerField(label='ID', read_only=True)\n title = CharField(allow_blank=True, max_length=100, required=False)\n code = CharField(style={'base_template': 'textarea.html'})\n linenos = BooleanField(required=False)\n language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...\n style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...\n It's important to remember that ModelSerializer classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:
create() and update() methods.Let's see how we can write some API views using our new Serializer class. For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.
Edit the snippets/views.py file, and add the following.
from django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
@csrf_exempt\ndef snippet_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == \"GET\":\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == \"POST\":\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
@csrf_exempt\ndef snippet_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == \"GET\":\n serializer = SnippetSerializer(snippet)\n return JsonResponse(serializer.data)\n\n elif request.method == \"PUT\":\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(snippet, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == \"DELETE\":\n snippet.delete()\n return HttpResponse(status=204)\n Finally we need to wire these views up. Create the snippets/urls.py file:
from django.urls import path\nfrom snippets import views\n\nurlpatterns = [\n path(\"snippets/\", views.snippet_list),\n path(\"snippets/<int:pk>/\", views.snippet_detail),\n]\n We also need to wire up the root urlconf, in the tutorial/urls.py file, to include our snippet app's URLs.
from django.urls import path, include\n\nurlpatterns = [\n path(\"\", include(\"snippets.urls\")),\n]\n It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed json, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 \"server error\" response. Still, this'll do for now.
Now we can start up a sample server that serves our snippets.
Quit out of the shell...
>>> quit()\n ...and start up Django's development server.
python manage.py runserver\n\nValidating models...\n\n0 errors found\nDjango version 5.0, using settings 'tutorial.settings'\nStarting Development server at http://127.0.0.1:8000/\nQuit the server with CONTROL-C.\n In another terminal window, we can test the server.
We can test our API using curl or HTTPie. HTTPie is a user-friendly http client that's written in Python. Let's install that.
You can install HTTPie using pip:
pip install httpie\n Finally, we can get a list of all of the snippets:
http GET http://127.0.0.1:8000/snippets/ --unsorted\n\nHTTP/1.1 200 OK\n...\n[\n {\n \"id\": 1,\n \"title\": \"\",\n \"code\": \"foo = \\\"bar\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print(\\\"hello, world\\\")\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 3,\n \"title\": \"\",\n \"code\": \"print(\\\"hello, world\\\")\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n }\n]\n Or we can get a particular snippet by referencing its id:
http GET http://127.0.0.1:8000/snippets/2/ --unsorted\n\nHTTP/1.1 200 OK\n...\n{\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print(\\\"hello, world\\\")\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n Similarly, you can have the same json displayed by visiting these URLs in a web browser.
"},{"location":"tutorial/1-serialization/#where-are-we-now","title":"Where are we now","text":"We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.
Our API views don't do anything particularly special at the moment, beyond serving json responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.
We'll see how we can start to improve things in part 2 of the tutorial.
"},{"location":"tutorial/2-requests-and-responses/","title":"Tutorial 2: Requests and Responses","text":"From this point we're going to really start covering the core of REST framework. Let's introduce a couple of essential building blocks.
"},{"location":"tutorial/2-requests-and-responses/#request-objects","title":"Request objects","text":"REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing. The core functionality of the Request object is the request.data attribute, which is similar to request.POST, but more useful for working with Web APIs.
request.POST # Only handles form data. Only works for 'POST' method.\nrequest.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.\n"},{"location":"tutorial/2-requests-and-responses/#response-objects","title":"Response objects","text":"REST framework also introduces a Response object, which is a type of TemplateResponse that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.
return Response(data) # Renders to content type as requested by the client.\n"},{"location":"tutorial/2-requests-and-responses/#status-codes","title":"Status codes","text":"Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as HTTP_400_BAD_REQUEST in the status module. It's a good idea to use these throughout rather than using numeric identifiers.
REST framework provides two wrappers you can use to write API views.
@api_view decorator for working with function based views.APIView class for working with class-based views.These wrappers provide a few bits of functionality such as making sure you receive Request instances in your view, and adding context to Response objects so that content negotiation can be performed.
The wrappers also provide behavior such as returning 405 Method Not Allowed responses when appropriate, and handling any ParseError exceptions that occur when accessing request.data with malformed input.
Okay, let's go ahead and start using these new components to refactor our views slightly.
from rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\n@api_view([\"GET\", \"POST\"])\ndef snippet_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == \"GET\":\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return Response(serializer.data)\n\n elif request.method == \"POST\":\n serializer = SnippetSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
Here is the view for an individual snippet, in the views.py module.
@api_view([\"GET\", \"PUT\", \"DELETE\"])\ndef snippet_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == \"GET\":\n serializer = SnippetSerializer(snippet)\n return Response(serializer.data)\n\n elif request.method == \"PUT\":\n serializer = SnippetSerializer(snippet, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == \"DELETE\":\n snippet.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n This should all feel very familiar - it is not a lot different from working with regular Django views.
Notice that we're no longer explicitly tying our requests or responses to a given content type. request.data can handle incoming json requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as http://example.com/api/items/4.json.
Start by adding a format keyword argument to both of the views, like so. def snippet_list(request, format=None): and def snippet_detail(request, pk, format=None):
Now update the snippets/urls.py file slightly, to append a set of format_suffix_patterns in addition to the existing URLs.
from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n path(\"snippets/\", views.snippet_list),\n path(\"snippets/<int:pk>/\", views.snippet_detail),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.
"},{"location":"tutorial/2-requests-and-responses/#hows-it-looking","title":"How's it looking?","text":"Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
We can get a list of all of the snippets, as before.
http http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n {\n \"id\": 1,\n \"title\": \"\",\n \"code\": \"foo = \\\"bar\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print(\\\"hello, world\\\")\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n }\n]\n We can control the format of the response that we get back, either by using the Accept header:
http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON\nhttp http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML\n Or by appending a format suffix:
http http://127.0.0.1:8000/snippets.json # JSON suffix\nhttp http://127.0.0.1:8000/snippets.api # Browsable API suffix\n Similarly, we can control the format of the request that we send, using the Content-Type header.
# POST using form data\nhttp --form POST http://127.0.0.1:8000/snippets/ code=\"print(123)\"\n\n{\n \"id\": 3,\n \"title\": \"\",\n \"code\": \"print(123)\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n\n# POST using JSON\nhttp --json POST http://127.0.0.1:8000/snippets/ code=\"print(456)\"\n\n{\n \"id\": 4,\n \"title\": \"\",\n \"code\": \"print(456)\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n If you add a --debug switch to the http requests above, you will be able to see the request type in request headers.
Now go and open the API in a web browser, by visiting http://127.0.0.1:8000/snippets/.
"},{"location":"tutorial/2-requests-and-responses/#browsability","title":"Browsability","text":"Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.
See the browsable api topic for more information about the browsable API feature and how to customize it.
"},{"location":"tutorial/2-requests-and-responses/#whats-next","title":"What's next?","text":"In tutorial part 3, we'll start using class-based views, and see how generic views reduce the amount of code we need to write.
"},{"location":"tutorial/3-class-based-views/","title":"Tutorial 3: Class-based Views","text":"We can also write our API views using class-based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code DRY.
"},{"location":"tutorial/3-class-based-views/#rewriting-our-api-using-class-based-views","title":"Rewriting our API using class-based views","text":"We'll start by rewriting the root view as a class-based view. All this involves is a little bit of refactoring of views.py.
from snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom django.http import Http404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n\nclass SnippetList(APIView):\n \"\"\"\n List all snippets, or create a new snippet.\n \"\"\"\n\n def get(self, request, format=None):\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return Response(serializer.data)\n\n def post(self, request, format=None):\n serializer = SnippetSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in views.py.
class SnippetDetail(APIView):\n \"\"\"\n Retrieve, update or delete a snippet instance.\n \"\"\"\n\n def get_object(self, pk):\n try:\n return Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n raise Http404\n\n def get(self, request, pk, format=None):\n snippet = self.get_object(pk)\n serializer = SnippetSerializer(snippet)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n snippet = self.get_object(pk)\n serializer = SnippetSerializer(snippet, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n snippet = self.get_object(pk)\n snippet.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n That's looking good. Again, it's still pretty similar to the function based view right now.
We'll also need to refactor our snippets/urls.py slightly now that we're using class-based views.
from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n path(\"snippets/\", views.SnippetList.as_view()),\n path(\"snippets/<int:pk>/\", views.SnippetDetail.as_view()),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n Okay, we're done. If you run the development server everything should be working just as before.
"},{"location":"tutorial/3-class-based-views/#using-mixins","title":"Using mixins","text":"One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior.
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behavior are implemented in REST framework's mixin classes.
Let's take a look at how we can compose the views by using the mixin classes. Here's our views.py module again.
from snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework import mixins\nfrom rest_framework import generics\n\n\nclass SnippetList(\n mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView\n):\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n\n def get(self, request, *args, **kwargs):\n return self.list(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n return self.create(request, *args, **kwargs)\n We'll take a moment to examine exactly what's happening here. We're building our view using GenericAPIView, and adding in ListModelMixin and CreateModelMixin.
The base class provides the core functionality, and the mixin classes provide the .list() and .create() actions. We're then explicitly binding the get and post methods to the appropriate actions. Simple enough stuff so far.
class SnippetDetail(\n mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n mixins.DestroyModelMixin,\n generics.GenericAPIView,\n):\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n\n def get(self, request, *args, **kwargs):\n return self.retrieve(request, *args, **kwargs)\n\n def put(self, request, *args, **kwargs):\n return self.update(request, *args, **kwargs)\n\n def delete(self, request, *args, **kwargs):\n return self.destroy(request, *args, **kwargs)\n Pretty similar. Again we're using the GenericAPIView class to provide the core functionality, and adding in mixins to provide the .retrieve(), .update() and .destroy() actions.
Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our views.py module even more.
from snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework import generics\n\n\nclass SnippetList(generics.ListCreateAPIView):\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n\n\nclass SnippetDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.
Next we'll move onto part 4 of the tutorial, where we'll take a look at how we can deal with authentication and permissions for our API.
"},{"location":"tutorial/4-authentication-and-permissions/","title":"Tutorial 4: Authentication & Permissions","text":"Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:
We're going to make a couple of changes to our Snippet model class. First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.
Add the following two fields to the Snippet model in models.py.
owner = models.ForeignKey(\n \"auth.User\", related_name=\"snippets\", on_delete=models.CASCADE\n)\nhighlighted = models.TextField()\n We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the pygments code highlighting library.
We'll need some extra imports:
from pygments.lexers import get_lexer_by_name\nfrom pygments.formatters.html import HtmlFormatter\nfrom pygments import highlight\n And now we can add a .save() method to our model class:
def save(self, *args, **kwargs):\n \"\"\"\n Use the `pygments` library to create a highlighted HTML\n representation of the code snippet.\n \"\"\"\n lexer = get_lexer_by_name(self.language)\n linenos = \"table\" if self.linenos else False\n options = {\"title\": self.title} if self.title else {}\n formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)\n self.highlighted = highlight(self.code, lexer, formatter)\n super().save(*args, **kwargs)\n When that's all done we'll need to update our database tables. Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
rm -f db.sqlite3\nrm -r snippets/migrations\npython manage.py makemigrations snippets\npython manage.py migrate\n You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the createsuperuser command.
python manage.py createsuperuser\n"},{"location":"tutorial/4-authentication-and-permissions/#adding-endpoints-for-our-user-models","title":"Adding endpoints for our User models","text":"Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In serializers.py add:
from django.contrib.auth.models import User\n\n\nclass UserSerializer(serializers.ModelSerializer):\n snippets = serializers.PrimaryKeyRelatedField(\n many=True, queryset=Snippet.objects.all()\n )\n\n class Meta:\n model = User\n fields = [\"id\", \"username\", \"snippets\"]\n Because 'snippets' is a reverse relationship on the User model, it will not be included by default when using the ModelSerializer class, so we needed to add an explicit field for it.
We'll also add a couple of views to views.py. We'd like to just use read-only views for the user representations, so we'll use the ListAPIView and RetrieveAPIView generic class-based views.
from django.contrib.auth.models import User\n\n\nclass UserList(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass UserDetail(generics.RetrieveAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n Make sure to also import the UserSerializer class
from snippets.serializers import UserSerializer\n Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in snippets/urls.py.
path(\"users/\", views.UserList.as_view()),\npath(\"users/<int:pk>/\", views.UserDetail.as_view()),\n"},{"location":"tutorial/4-authentication-and-permissions/#associating-snippets-with-users","title":"Associating Snippets with Users","text":"Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.
The way we deal with that is by overriding a .perform_create() method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.
On the SnippetList view class, add the following method:
def perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n The create() method of our serializer will now be passed an additional 'owner' field, along with the validated data from the request.
Now that snippets are associated with the user that created them, let's update our SnippetSerializer to reflect that. Add the following field to the serializer definition in serializers.py:
owner = serializers.ReadOnlyField(source=\"owner.username\")\n Note
Make sure you also add 'owner', to the list of fields in the inner Meta class.
This field is doing something quite interesting. The source argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.
The field we've added is the untyped ReadOnlyField class, in contrast to the other typed fields, such as CharField, BooleanField etc... The untyped ReadOnlyField is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used CharField(read_only=True) here.
Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.
REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is IsAuthenticatedOrReadOnly, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.
First add the following import in the views module
from rest_framework import permissions\n Then, add the following property to both the SnippetList and SnippetDetail view classes.
permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n"},{"location":"tutorial/4-authentication-and-permissions/#adding-login-to-the-browsable-api","title":"Adding login to the Browsable API","text":"If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
We can add a login view for use with the browsable API, by editing the URLconf in our project-level urls.py file.
Add the following import at the top of the file:
from django.urls import path, include\n And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
urlpatterns += [\n path(\"api-auth/\", include(\"rest_framework.urls\")),\n]\n The 'api-auth/' part of pattern can actually be whatever URL you want to use.
Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.
Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet ids that are associated with each user, in each user's 'snippets' field.
"},{"location":"tutorial/4-authentication-and-permissions/#object-level-permissions","title":"Object level permissions","text":"Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.
To do that we're going to need to create a custom permission.
In the snippets app, create a new file, permissions.py
from rest_framework import permissions\n\n\nclass IsOwnerOrReadOnly(permissions.BasePermission):\n \"\"\"\n Custom permission to only allow owners of an object to edit it.\n \"\"\"\n\n def has_object_permission(self, request, view, obj):\n # Read permissions are allowed to any request,\n # so we'll always allow GET, HEAD or OPTIONS requests.\n if request.method in permissions.SAFE_METHODS:\n return True\n\n # Write permissions are only allowed to the owner of the snippet.\n return obj.owner == request.user\n Now we can add that custom permission to our snippet instance endpoint, by editing the permission_classes property on the SnippetDetail view class:
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]\n Make sure to also import the IsOwnerOrReadOnly class.
from snippets.permissions import IsOwnerOrReadOnly\n Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
"},{"location":"tutorial/4-authentication-and-permissions/#authenticating-with-the-api","title":"Authenticating with the API","text":"Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are SessionAuthentication and BasicAuthentication.
When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.
If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.
If we try to create a snippet without authenticating, we'll get an error:
http POST http://127.0.0.1:8000/snippets/ code=\"print(123)\"\n\n{\n \"detail\": \"Authentication credentials were not provided.\"\n}\n We can make a successful request by including the username and password of one of the users we created earlier.
http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code=\"print(789)\"\n\n{\n \"id\": 1,\n \"owner\": \"admin\",\n \"title\": \"foo\",\n \"code\": \"print(789)\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n"},{"location":"tutorial/4-authentication-and-permissions/#summary","title":"Summary","text":"We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.
In part 5 of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
"},{"location":"tutorial/5-relationships-and-hyperlinked-apis/","title":"Tutorial 5: Relationships & Hyperlinked APIs","text":"At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.
"},{"location":"tutorial/5-relationships-and-hyperlinked-apis/#creating-an-endpoint-for-the-root-of-our-api","title":"Creating an endpoint for the root of our API","text":"Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the @api_view decorator we introduced earlier. In your snippets/views.py add:
from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\n\n\n@api_view([\"GET\"])\ndef api_root(request, format=None):\n return Response(\n {\n \"users\": reverse(\"user-list\", request=request, format=format),\n \"snippets\": reverse(\"snippet-list\", request=request, format=format),\n }\n )\n Two things should be noticed here. First, we're using REST framework's reverse function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our snippets/urls.py.
The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.
Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.
The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own .get() method. In your snippets/views.py add:
from rest_framework import renderers\n\n\nclass SnippetHighlight(generics.GenericAPIView):\n queryset = Snippet.objects.all()\n renderer_classes = [renderers.StaticHTMLRenderer]\n\n def get(self, request, *args, **kwargs):\n snippet = self.get_object()\n return Response(snippet.highlighted)\n As usual we need to add the new views that we've created in to our URLconf. We'll add a url pattern for our new API root in snippets/urls.py:
path(\"\", views.api_root),\n And then add a url pattern for the snippet highlights:
path(\"snippets/<int:pk>/highlight/\", views.SnippetHighlight.as_view()),\n"},{"location":"tutorial/5-relationships-and-hyperlinked-apis/#hyperlinking-our-api","title":"Hyperlinking our API","text":"Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:
REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.
In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend HyperlinkedModelSerializer instead of the existing ModelSerializer.
The HyperlinkedModelSerializer has the following differences from ModelSerializer:
id field by default.url field, using HyperlinkedIdentityField.HyperlinkedRelatedField, instead of PrimaryKeyRelatedField.We can easily re-write our existing serializers to use hyperlinking. In your snippets/serializers.py add:
class SnippetSerializer(serializers.HyperlinkedModelSerializer):\n owner = serializers.ReadOnlyField(source=\"owner.username\")\n highlight = serializers.HyperlinkedIdentityField(\n view_name=\"snippet-highlight\", format=\"html\"\n )\n\n class Meta:\n model = Snippet\n fields = [\n \"url\",\n \"id\",\n \"highlight\",\n \"owner\",\n \"title\",\n \"code\",\n \"linenos\",\n \"language\",\n \"style\",\n ]\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n snippets = serializers.HyperlinkedRelatedField(\n many=True, view_name=\"snippet-detail\", read_only=True\n )\n\n class Meta:\n model = User\n fields = [\"url\", \"id\", \"username\", \"snippets\"]\n Notice that we've also added a new 'highlight' field. This field is of the same type as the url field, except that it points to the 'snippet-highlight' url pattern, instead of the 'snippet-detail' url pattern.
Because we've included format suffixed URLs such as '.json', we also need to indicate on the highlight field that any format suffixed hyperlinks it returns should use the '.html' suffix.
Note
When you are manually instantiating these serializers inside your views (e.g., in SnippetDetail or SnippetList), you must pass context={'request': request} so the serializer knows how to build absolute URLs. For example, instead of:
serializer = SnippetSerializer(snippet)\n You must write:
serializer = SnippetSerializer(snippet, context={\"request\": request})\n If your view is a subclass of GenericAPIView, you may use the get_serializer_context() as a convenience method.
If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.
'user-list' and 'snippet-list'.'snippet-highlight'.'snippet-detail'.'url' fields that by default will refer to '{model_name}-detail', which in this case will be 'snippet-detail' and 'user-detail'.After adding all those names into our URLconf, our final snippets/urls.py file should look like this:
from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\n# API endpoints\nurlpatterns = format_suffix_patterns(\n [\n path(\"\", views.api_root),\n path(\"snippets/\", views.SnippetList.as_view(), name=\"snippet-list\"),\n path(\n \"snippets/<int:pk>/\", views.SnippetDetail.as_view(), name=\"snippet-detail\"\n ),\n path(\n \"snippets/<int:pk>/highlight/\",\n views.SnippetHighlight.as_view(),\n name=\"snippet-highlight\",\n ),\n path(\"users/\", views.UserList.as_view(), name=\"user-list\"),\n path(\"users/<int:pk>/\", views.UserDetail.as_view(), name=\"user-detail\"),\n ]\n)\n"},{"location":"tutorial/5-relationships-and-hyperlinked-apis/#adding-pagination","title":"Adding pagination","text":"The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.
We can change the default list style to use pagination, by modifying our tutorial/settings.py file slightly. Add the following setting:
REST_FRAMEWORK = {\n \"DEFAULT_PAGINATION_CLASS\": \"rest_framework.pagination.PageNumberPagination\",\n \"PAGE_SIZE\": 10,\n}\n Note that settings in REST framework are all namespaced into a single dictionary setting, named REST_FRAMEWORK, which helps keep them well separated from your other project settings.
We could also customize the pagination style if we needed to, but in this case we'll just stick with the default.
"},{"location":"tutorial/5-relationships-and-hyperlinked-apis/#browsing-the-api","title":"Browsing the API","text":"If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.
You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.
In part 6 of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.
"},{"location":"tutorial/6-viewsets-and-routers/","title":"Tutorial 6: ViewSets & Routers","text":"REST framework includes an abstraction for dealing with ViewSets, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.
ViewSet classes are almost the same thing as View classes, except that they provide operations such as retrieve, or update, and not method handlers such as get or put.
A ViewSet class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a Router class which handles the complexities of defining the URL conf for you.
Let's take our current set of views, and refactor them into view sets.
First of all let's refactor our UserList and UserDetail classes into a single UserViewSet class. In the snippets/views.py file, we can remove the two view classes and replace them with a single ViewSet class:
from rest_framework import viewsets\n\n\nclass UserViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n This viewset automatically provides `list` and `retrieve` actions.\n \"\"\"\n\n queryset = User.objects.all()\n serializer_class = UserSerializer\n Here we've used the ReadOnlyModelViewSet class to automatically provide the default 'read-only' operations. We're still setting the queryset and serializer_class attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.
Next we're going to replace the SnippetList, SnippetDetail and SnippetHighlight view classes. We can remove the three views, and again replace them with a single class.
from rest_framework import permissions\nfrom rest_framework import renderers\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\n\n\nclass SnippetViewSet(viewsets.ModelViewSet):\n \"\"\"\n This ViewSet automatically provides `list`, `create`, `retrieve`,\n `update` and `destroy` actions.\n\n Additionally we also provide an extra `highlight` action.\n \"\"\"\n\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]\n\n @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])\n def highlight(self, request, *args, **kwargs):\n snippet = self.get_object()\n return Response(snippet.highlighted)\n\n def perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n This time we've used the ModelViewSet class in order to get the complete set of default read and write operations.
Notice that we've also used the @action decorator to create a custom action, named highlight. This decorator can be used to add any custom endpoints that don't fit into the standard create/update/delete style.
Custom actions which use the @action decorator will respond to GET requests by default. We can use the methods argument if we wanted an action that responded to POST requests.
The URLs for custom actions by default depend on the method name itself. If you want to change the way url should be constructed, you can include url_path as a decorator keyword argument.
The handler methods only get bound to the actions when we define the URLConf. To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.
In the snippets/urls.py file we bind our ViewSet classes into a set of concrete views.
from rest_framework import renderers\n\nfrom snippets.views import api_root, SnippetViewSet, UserViewSet\n\nsnippet_list = SnippetViewSet.as_view({\"get\": \"list\", \"post\": \"create\"})\nsnippet_detail = SnippetViewSet.as_view(\n {\"get\": \"retrieve\", \"put\": \"update\", \"patch\": \"partial_update\", \"delete\": \"destroy\"}\n)\nsnippet_highlight = SnippetViewSet.as_view(\n {\"get\": \"highlight\"}, renderer_classes=[renderers.StaticHTMLRenderer]\n)\nuser_list = UserViewSet.as_view({\"get\": \"list\"})\nuser_detail = UserViewSet.as_view({\"get\": \"retrieve\"})\n Notice how we're creating multiple views from each ViewSet class, by binding the HTTP methods to the required action for each view.
Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.
urlpatterns = format_suffix_patterns(\n [\n path(\"\", api_root),\n path(\"snippets/\", snippet_list, name=\"snippet-list\"),\n path(\"snippets/<int:pk>/\", snippet_detail, name=\"snippet-detail\"),\n path(\n \"snippets/<int:pk>/highlight/\", snippet_highlight, name=\"snippet-highlight\"\n ),\n path(\"users/\", user_list, name=\"user-list\"),\n path(\"users/<int:pk>/\", user_detail, name=\"user-detail\"),\n ]\n)\n"},{"location":"tutorial/6-viewsets-and-routers/#using-routers","title":"Using Routers","text":"Because we're using ViewSet classes rather than View classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a Router class. All we need to do is register the appropriate view sets with a router, and let it do the rest.
Here's our re-wired snippets/urls.py file.
from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n\nfrom snippets import views\n\n# Create a router and register our ViewSets with it.\nrouter = DefaultRouter()\nrouter.register(r\"snippets\", views.SnippetViewSet, basename=\"snippet\")\nrouter.register(r\"users\", views.UserViewSet, basename=\"user\")\n\n# The API URLs are now determined automatically by the router.\nurlpatterns = [\n path(\"\", include(router.urls)),\n]\n Registering the ViewSets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the view set itself.
The DefaultRouter class we're using also automatically creates the API root view for us, so we can now delete the api_root function from our views module.
Using ViewSets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function-based views. Using ViewSets is less explicit than building your API views individually.
"},{"location":"tutorial/quickstart/","title":"Quickstart","text":"We're going to create a simple API to allow admin users to view and edit the users and groups in the system.
"},{"location":"tutorial/quickstart/#project-setup","title":"Project setup","text":"Create a new Django project named tutorial, then start a new app called quickstart.
# Create the project directory\nmkdir tutorial\ncd tutorial\n\n# Create a virtual environment to isolate our package dependencies locally\npython3 -m venv .venv\nsource .venv/bin/activate\n\n# Install Django and Django REST framework into the virtual environment\npip install djangorestframework\n\n# Set up a new project with a single application\ndjango-admin startproject tutorial . # Note the trailing '.' character\ncd tutorial\ndjango-admin startapp quickstart\ncd ..\n If you use Bash for Windows
# Create the project directory\nmkdir tutorial\ncd tutorial\n\n# Create a virtual environment to isolate our package dependencies locally\npython3 -m venv .venv\nsource .venv\\Scripts\\activate\n\n# Install Django and Django REST framework into the virtual environment\npip install djangorestframework\n\n# Set up a new project with a single application\ndjango-admin startproject tutorial . # Note the trailing '.' character\ncd tutorial\ndjango-admin startapp quickstart\ncd ..\n The project layout should look like:
$ pwd\n<some path>/tutorial\n$ find .\n.\n./tutorial\n./tutorial/asgi.py\n./tutorial/__init__.py\n./tutorial/quickstart\n./tutorial/quickstart/migrations\n./tutorial/quickstart/migrations/__init__.py\n./tutorial/quickstart/models.py\n./tutorial/quickstart/__init__.py\n./tutorial/quickstart/apps.py\n./tutorial/quickstart/admin.py\n./tutorial/quickstart/tests.py\n./tutorial/quickstart/views.py\n./tutorial/settings.py\n./tutorial/urls.py\n./tutorial/wsgi.py\n./env\n./env/...\n./manage.py\n It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).
Now sync your database for the first time:
python manage.py migrate\n We'll also create an initial user named admin with a password. We'll authenticate as that user later in our example.
python manage.py createsuperuser --username admin --email admin@example.com\n Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...
"},{"location":"tutorial/quickstart/#serializers","title":"Serializers","text":"First up we're going to define some serializers. Let's create a new module named tutorial/quickstart/serializers.py that we'll use for our data representations.
from django.contrib.auth.models import Group, User\nfrom rest_framework import serializers\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = [\"url\", \"username\", \"email\", \"groups\"]\n\n\nclass GroupSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Group\n fields = [\"url\", \"name\"]\n Notice that we're using hyperlinked relations in this case with HyperlinkedModelSerializer. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
Right, we'd better write some views then. Open tutorial/quickstart/views.py and get typing.
from django.contrib.auth.models import Group, User\nfrom rest_framework import permissions, viewsets\n\nfrom tutorial.quickstart.serializers import GroupSerializer, UserSerializer\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n\n queryset = User.objects.all().order_by(\"-date_joined\")\n serializer_class = UserSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n\nclass GroupViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows groups to be viewed or edited.\n \"\"\"\n\n queryset = Group.objects.all().order_by(\"name\")\n serializer_class = GroupSerializer\n permission_classes = [permissions.IsAuthenticated]\n Rather than write multiple views we're grouping together all the common behavior into classes called ViewSets.
We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.
"},{"location":"tutorial/quickstart/#urls","title":"URLs","text":"Okay, now let's wire up the API URLs. On to tutorial/urls.py...
from django.urls import include, path\nfrom rest_framework import routers\n\nfrom tutorial.quickstart import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r\"users\", views.UserViewSet)\nrouter.register(r\"groups\", views.GroupViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n path(\"\", include(router.urls)),\n path(\"api-auth/\", include(\"rest_framework.urls\", namespace=\"rest_framework\")),\n]\n Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.
Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
"},{"location":"tutorial/quickstart/#pagination","title":"Pagination","text":"Pagination allows you to control how many objects per page are returned. To enable it add the following lines to tutorial/settings.py
REST_FRAMEWORK = {\n \"DEFAULT_PAGINATION_CLASS\": \"rest_framework.pagination.PageNumberPagination\",\n \"PAGE_SIZE\": 10,\n}\n"},{"location":"tutorial/quickstart/#settings","title":"Settings","text":"Add 'rest_framework' to INSTALLED_APPS. The settings module will be in tutorial/settings.py
INSTALLED_APPS = [\n ...\n 'rest_framework',\n]\n Okay, we're done.
"},{"location":"tutorial/quickstart/#testing-our-api","title":"Testing our API","text":"We're now ready to test the API we've built. Let's fire up the server from the command line.
python manage.py runserver\n We can now access our API, both from the command-line, using tools like curl...
bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/\nEnter host password for user 'admin':\n{\n \"count\": 1,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"url\": \"http://127.0.0.1:8000/users/1/\",\n \"username\": \"admin\",\n \"email\": \"admin@example.com\",\n \"groups\": []\n }\n ]\n}\n Or using the httpie, command line tool...
bash: http -a admin http://127.0.0.1:8000/users/\nhttp: password for admin@127.0.0.1:8000:: \n$HTTP/1.1 200 OK\n...\n{\n \"count\": 1,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://127.0.0.1:8000/users/1/\",\n \"username\": \"admin\"\n }\n ]\n}\n Or directly through the browser, by going to the URL http://127.0.0.1:8000/users/...
If you're working through the browser, make sure to login using the control in the top right corner.
Great, that was easy!
If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial, or start browsing the API guide.
"}]} \ No newline at end of file