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.
— 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.
Let's define a simple viewset that can be used to list or retrieve all the users in the system.
If we need to, we can bind this viewset into two separate views, like so:
Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.
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:
There are two main advantages of using a ViewSet class over using a View class.
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.
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
During dispatch, the following attributes are available on the ViewSet.
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the list action similar to this:
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:
The action decorator will route GET requests by default, but may also accept other HTTP methods by setting the methods argument. For example:
The decorator allows you to override any viewset-level configuration such as permission_classes, serializer_class, filter_backends...:
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.
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:
Alternatively, you can use the url_name attribute set by the @action decorator.
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:
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:
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.
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:
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:
By creating your own base ViewSet classes, you can provide common behavior that can be reused in multiple viewsets across your API.
viewsets.py


Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format.
— 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:
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
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
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 set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a requires_context = True attribute, then the serializer field will be passed as an argument.
For example:
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.
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
The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email'). When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal.
The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
Defaults to the name of the field.
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.
A dictionary of error codes to error messages.
A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
A text string that may be used as a description of the field in HTML form fields or other descriptive elements.
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:
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':
For more details see the HTML & Forms documentation.
A boolean representation.
When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to False, even if it has a default=True option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.
Note that Django 2.1 removed the blank kwarg from models.BooleanField. Prior to Django 2.1 models.BooleanField fields were always blank=True. Thus since Django 2.1 default serializers.BooleanField instances will be generated without the required kwarg (i.e. equivalent to required=True) whereas with previous versions of Django, default BooleanField instances will be generated with a required=False option. If you want to control this behaviour manually, explicitly declare the BooleanField on the serializer class, or use the extra_kwargs option to set the required flag.
Corresponds to django.db.models.fields.BooleanField.
Signature: BooleanField()
A boolean representation that also accepts None as a valid value.
Corresponds to django.db.models.fields.NullBooleanField.
Signature: NullBooleanField()
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)
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 e-mail 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:
Signature: UUIDField(format='hex_verbose')
A field whose choices are limited to the filenames in a certain directory on the filesystem
Corresponds to django.forms.fields.FilePathField.
Signature: FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)
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)
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)
A floating point representation.
Corresponds to django.db.models.fields.FloatField.
Signature: FloatField(max_value=None, min_value=None)
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)
To validate numbers up to 999 with a resolution of 2 decimal places, you would use:
And to validate numbers up to anything less than one billion with a resolution of 10 decimal places:
This field also takes an optional argument, coerce_to_string. If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer.
If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise.
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 strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z')
When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class.
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:
A date representation.
Corresponds to django.db.models.fields.DateField
Signature: DateField(format=api_settings.DATE_FORMAT, input_formats=None)
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 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. The representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]'.
Signature: DurationField(max_value=None, min_value=None)
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=… argument.
Signature: ChoiceField(choices)
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 set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. to_internal_value returns a set containing the selected values.
Signature: MultipleChoiceField(choices)
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)
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)
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)
For example, to validate a list of integers you might use something like the following:
The ListField class also supports a declarative style that allows you to write reusable list field classes.
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)
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
You can also use the declarative style, as with ListField. For example:
A preconfigured DictField that is compatible with Django's postgres HStoreField.
Signature: HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)
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)
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:
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:
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.
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)
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:
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:
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:
Our ColorField class above currently does not perform any data validation. To indicate invalid data, we should raise a serializers.ValidationError, like so:
The .fail() method is a shortcut for raising ValidationError that takes a message string from the error_messages dictionary. For example:
This style keeps your error messages cleaner and more separated from your code, and should be preferred.
Here we'll take an example of a flat DataPoint model with x_coordinate and y_coordinate attributes.
Using a custom field and source='*' we can provide a nested representation of the coordinate pair:
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.
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.
For completeness lets do the same thing again but with the nested serializer approach suggested above:
Here the mapping between the target and source attribute pairs (x and x_coordinate, y and y_coordinate) is handled in the IntegerField declarations. It's our NestedCoordinateSerializer that takes source='*'.
Our new DataPointSerializer exhibits the same behaviour as the custom field approach.
Serializing:
Deserializing:
But we also get the built-in validation for free:
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.
The following third party packages are also available.
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 django-rest-framework-hstore package provides an HStoreField to support django-hstore DictionaryField model field.
fields.py


Auth needs to be pluggable.
— 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.
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.
You can also set the authentication scheme on a per-view or per-viewset basis, using the APIView class-based views.
Or, if you're using the @api_view decorator with function based views.
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.
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 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.
Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example:
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.
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:
Note: Make sure to run manage.py migrate after changing your settings. The rest_framework.authtoken app provides Django database migrations.
You'll also need to create tokens for your users.
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:
Note: If you want to use a different keyword in the header, such as Bearer, simply subclass TokenAuthentication and set the keyword class variable.
If successfully authenticated, TokenAuthentication provides the following credentials.
Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example:
The curl command line tool may be useful for testing token authenticated APIs. For example:
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.
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:
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 behaviour. To use it, add the obtain_auth_token view to your URLconf:
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:
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 to throttle 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:
And in your urls.py:
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 customize it to your needs, more specifically by declaring the user field as raw_field.
your_app/admin.py:
Since version 3.6.4 it's possible to generate a user token using the following command:
this command will return the API token for the given user, creating it if it doesn't exist:
In case you want to regenerate the token (for example if it has been compromised or leaked) you can pass an additional parameter:
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.
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 behaviour is not suitable for login views, which should always have CSRF validation applied.
This authentication scheme allows you to delegate authentication to your web server, which sets the REMOTE_USER environment variable.
To use it, you must have django.contrib.auth.backends.RemoteUserBackend (or a subclass) in your AUTHENTICATION_BACKENDS setting. By default, RemoteUserBackend creates User objects for usernames that don't already exist. To change this and other behaviour, consult the Django documentation.
If successfully authenticated, RemoteUserAuthentication provides the following credentials:
Consult your web server's documentation for information about configuring an authentication method, e.g.:
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:
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'.
The following third-party packages are also available.
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.
Install using pip.
Add the package to your INSTALLED_APPS and modify your REST framework settings.
For more details see the Django REST framework - Getting started documentation.
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.
Install the package using pip.
For details on configuration and usage see the Django REST framework OAuth documentation for authentication and permissions.
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.
The HawkREST library builds on the Mohawk library to let you work with Hawk signed requests and responses in your API. Hawk lets two parties securely communicate with each other using messages signed by a shared key. It is based on HTTP MAC access authentication (which was based on parts of OAuth 1.0).
HTTP Signature (currently a IETF draft) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to Amazon's HTTP Signature scheme, used by many of its services, it permits stateless, per-request authentication. Elvio Toccalino maintains the djangorestframework-httpsignature (outdated) package which provides an easy to use HTTP Signature Authentication mechanism. You can use the updated fork version of djangorestframework-httpsignature, which is drf-httpsig.
Djoser 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 ready to use REST implementation of the Django authentication system.
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.
Django-rest-framework-social-oauth2 library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.
Django-rest-knox library provides models and views to handle token-based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
drfpasswordless 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.
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.
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.
authentication.py


Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.
— Django documentation
REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types.
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.
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.
You can also set the renderers used for an individual view, or viewset, using the APIView class-based views.
Or, if you're using the @api_view decorator with function based views.
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:
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.
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:
The template name is determined by (in order of preference):
An example of a view that uses TemplateHTMLRenderer:
You can use TemplateHTMLRenderer either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
If you're building websites that use TemplateHTMLRenderer along with other renderer classes, you should consider listing TemplateHTMLRenderer as the first class in the renderer_classes list, so that it will be prioritised first even for browsers that send poorly formed ACCEPT: headers.
See the HTML & Forms Topic Page for further examples of TemplateHTMLRenderer usage.
.media_type: text/html
.format: 'html'
.charset: utf-8
See also: StaticHTMLRenderer
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:
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:
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:
.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.
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, 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:
The request data, as set by the Response() instantiation.
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".
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.
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.
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.
You can do some pretty flexible things using REST framework's renderers. Some examples...
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:
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:
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.
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.
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.
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.
Install using pip.
Modify your REST framework settings.
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.
Install using pip.
Modify your REST framework settings.
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.
Modify your REST framework settings.
MessagePack is a fast, efficient binary serialization format. Juan Riaza maintains the djangorestframework-msgpack package which provides MessagePack renderer and parser support for REST framework.
XLSX is the world's most popular binary spreadsheet format. Tim Allen of The Wharton School maintains drf-renderer-xlsx, which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
Install using pip.
Modify your REST framework settings.
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:
Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. Mjumbe Poe maintains the djangorestframework-csv package which provides CSV renderer support for REST framework.
UltraJSON 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.
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.
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 Laulatex. It is maintained by Pebble (S/F Software).
renderers.py


If you're doing REST-based web service stuff ... you should ignore request.POST.
— Malcom Tredinnick, Django developers group
REST framework's Request class extends the standard HttpRequest, adding support for REST framework's flexible request parsing and request authentication.
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.
request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES attributes except that:
For more details see the parsers documentation.
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 behaviour such as selecting a different serialization schemes for different media types.
The renderer instance that was selected by the content negotiation stage.
A string representing the media type that was accepted by the content negotiation stage.
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.
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.
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.
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.
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.
As REST framework's Request extends Django's HttpRequest, all the other standard attributes and methods are also available. For example the request.META and request.session dictionaries are available as normal.
Note that due to implementation reasons the Request class does not inherit from HttpRequest class, but instead extends the class using composition.
request.py


Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.
— Django documentation
REST framework supports HTTP content negotiation by providing a Response class which allows you to return content that can be rendered into multiple content types, depending on the client request.
The Response class subclasses Django's SimpleTemplateResponse. Response objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.
There's no requirement for you to use the Response class, you can also return regular HttpResponse or StreamingHttpResponse objects from your views if required. Using the Response class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats.
Unless you want to heavily customize REST framework for some reason, you should always use an APIView class or @api_view function for views that return Response objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view.
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:
The unrendered, serialized data of the response.
The numeric status code of the HTTP response.
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:
Signature: .render()
As with any other TemplateResponse, this method is called to render the serialized data of the response into the final response content. When .render() is called, the response content will be set to the result of calling the .render(data, accepted_media_type, renderer_context) method on the accepted_renderer instance.
You won't typically need to call .render() yourself, as it's handled by Django's standard response cycle.
response.py


Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.
— Django Documentation
One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
If the generic views don't suit the needs of your API, you can drop down to using the regular APIView class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
Typically when using the generic views, you'll override the view, and set several class attributes.
For more complex cases you might also want to override various methods on the view class. For example.
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:
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.
Pagination:
The following attributes are used to control pagination when used with list views.
Filtering:
Base methods:
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:
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:
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.
Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
For example:
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:
Save and deletion hooks:
The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
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.
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.
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:
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.
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
Used for read-only endpoints to represent a collection of model instances.
Provides a get method handler.
Extends: GenericAPIView, ListModelMixin
Used for read-only endpoints to represent a single model instance.
Provides a get method handler.
Extends: GenericAPIView, RetrieveModelMixin
Used for delete-only endpoints for a single model instance.
Provides a delete method handler.
Extends: GenericAPIView, DestroyModelMixin
Used for update-only endpoints for a single model instance.
Provides put and patch method handlers.
Extends: GenericAPIView, UpdateModelMixin
Used for read-write endpoints to represent a collection of model instances.
Provides get and post method handlers.
Extends: GenericAPIView, ListModelMixin, CreateModelMixin
Used for read or update endpoints to represent a single model instance.
Provides get, put and patch method handlers.
Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin
Used for read or delete endpoints to represent a single model instance.
Provides get and delete method handlers.
Extends: GenericAPIView, RetrieveModelMixin, DestroyModelMixin
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
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.
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:
You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.
Using custom mixins is a good option if you have custom behavior that needs to be used.
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:
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.
Prior to version 3.0 the REST framework mixins treated PUT as either an update or a create operation, depending on if the object already existed or not.
Allowing PUT as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning 404 responses.
Both styles "PUT as 404" and "PUT as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.
If you need to generic PUT-as-create behavior you may want to include something like this AllowPUTAsCreateMixin class as a mixin to your views.
The following third party packages provide additional generic view implementations.
Django Rest Multiple Models provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
mixins.pygenerics.py


Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.
— Ruby on Rails Documentation
Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.
REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.
Here's an example of a simple URL conf, that uses SimpleRouter.
There are two mandatory arguments to the register() method:
Optionally, you may also specify an additional argument:
The example above would generate the following URL patterns:
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:
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.
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...
Alternatively you can use Django's include function, like so...
You may use include with an application namespace:
Or both an application and instance namespace:
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:
The following route would be generated:
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:
The above example would now generate the following URL pattern:
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:
Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.
The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the lookup_value_regex attribute on the viewset. For example, you can limit the lookup to valid UUIDs:
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.
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:
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:
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:
initkwargs: A dictionary of any additional arguments that should be passed when instantiating the view.
The following example will only route to the list and retrieve actions, and does not use the trailing slash convention.
Let's take a look at the routes our CustomReadOnlyRouter would generate for a simple viewset.
views.py:
urls.py:
The following mappings would be generated...
For 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.
The drf-nested-routers package provides routers and relationship fields for working with nested resources.
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.
The DRF-extensions package provides routers for creating nested viewsets, collection level controllers with customizable endpoint names.
routers.py


A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
— Heroku, JSON Schema for the Heroku Platform API
API schemas are a useful tool that allow for a range of use cases, including generating reference documentation, or driving dynamic client libraries that can interact with your API.
Django REST Framework provides support for automatic generation of OpenAPI schemas.
Schema generation has several moving parts. It's worth having an overview:
The following sections explain more.
If your schema is static, you can use the generateschema management command:
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.
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:
The get_schema_view() helper takes the following keyword arguments:
url: May be used to pass a canonical base URL for the schema.
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.
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:
generator_class: May be used to specify a SchemaGenerator subclass to be passed to the SchemaView.
Schema-level customization
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:
Arguments:
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:
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:
Per-View Customization
By default, view introspection is performed by an AutoSchema instance accessible via the schema attribute on APIView.
AutoSchema provides the OpenAPI elements needed for each view, request method and path:
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:
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:
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:
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
If the view has implemented get_serializer(), returns the result.
By default returns get_serializer() but can be overridden to differentiate between request and response objects.
By default returns get_serializer() but can be overridden to differentiate between request and response objects.
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:
You pass the kwargs when declaring the AutoSchema instance on your view:
Assuming a Pet model and PetSerializer serializer, the kwargs in this example are probably not needed. Often, though, you'll need to pass the kwargs if you have multiple view targeting the same model, or have multiple views with identically named serializers.
If your views have related customizations that are needed frequently, you can create a base AutoSchema subclass for your project that takes additional __init__() kwargs to save subclassing AutoSchema for each view.
schemas


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.
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.
The rate descriptions used in DEFAULT_THROTTLE_RATES may include second, minute, hour or day as the throttle period.
You can also set the throttling policy on a per-view or per-viewset basis, using the APIView class-based views.
If you're using the @api_view decorator with function based views you can use the following decorator.
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.
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:
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 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).
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).
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...
...and the following settings.
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...
...and the following settings.
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.
throttling.py