The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.
— Django documentation
The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.
The simplest way to filter the queryset of any view that subclasses GenericAPIView is to override the .get_queryset() method.
Overriding this method allows you to customize the queryset returned by the view in a number of different ways.
You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.
You can do so by filtering based on the value of request.user.
For example:
Another style of filtering might involve restricting the queryset based on some part of the URL.
For example if your URL config contained an entry like this:
You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.
We can override .get_queryset() to deal with URLs such as http://example.com/api/purchases?username=denvercoder9, and filter the queryset only if the username parameter is included in the URL:
As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.
Generic filters can also present themselves as HTML controls in the browsable API and admin API.
The default filter backends may be set globally, using the DEFAULT_FILTER_BACKENDS setting. For example.
You can also set the filter backends on a per-view, or per-viewset basis, using the GenericAPIView class-based views.
Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.
For instance, given the previous example, and a product with an id of 4675, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:
Note that you can use both an overridden .get_queryset() and generic filtering together, and everything will work as expected. For example, if Product had a many-to-many relationship with User, named purchase, you might want to write a view like this:
The django-filter library includes a DjangoFilterBackend class which supports highly customizable field filtering for REST framework.
To use DjangoFilterBackend, first install django-filter.
Then add 'django_filters' to Django's INSTALLED_APPS:
You should now either add the filter backend to your settings:
Or add the filter backend to an individual View or ViewSet.
If all you need is simple equality-based filtering, you can set a filterset_fields attribute on the view, or viewset, listing the set of fields you wish to filter against.
This will automatically create a FilterSet class for the given fields, and will allow you to make requests such as:
For more advanced filtering requirements you can specify a FilterSet class that should be used by the view. You can read more about FilterSets in the django-filter documentation. It's also recommended that you read the section on DRF integration.
The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin's search functionality.
When in use, the browsable API will include a SearchFilter control:
The SearchFilter class will only be applied if the view has a search_fields attribute set. The search_fields attribute should be a list of names of text type fields on the model, such as CharField or TextField.
This will allow the client to filter the items in the list by making queries such as:
You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:
For JSONField and HStoreField fields you can filter based on nested values within the data structure using the same double-underscore notation:
By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.
The search behavior may be restricted by prepending various characters to the search_fields.
For example:
By default, the search parameter is named 'search', but this may be overridden with the SEARCH_PARAM setting.
To dynamically change search fields based on request content, it's possible to subclass the SearchFilter and override the get_search_fields() function. For example, the following subclass will only search on title if the query parameter title_only is in the request:
For more details, see the Django documentation.
The OrderingFilter class supports simple query parameter controlled ordering of results.
By default, the query parameter is named 'ordering', but this may by overridden with the ORDERING_PARAM setting.
For example, to order users by username:
The client may also specify reverse orderings by prefixing the field name with '-', like so:
Multiple orderings may also be specified:
It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an ordering_fields attribute on the view, like so:
This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.
If you don't specify an ordering_fields attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the serializer_class attribute.
If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on any model field or queryset aggregate, by using the special value '__all__'.
If an ordering attribute is set on the view, this will be used as the default ordering.
Typically you'd instead control this by setting order_by on the initial queryset, but using the ordering parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results.
The ordering attribute may be either a string or a list/tuple of strings.
You can also provide your own generic filtering backend, or write an installable app for other developers to use.
To do so override BaseFilterBackend, and override the .filter_queryset(self, request, queryset, view) method. The method should return a new, filtered queryset.
As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.
For example, you might need to restrict users to only being able to see objects they created.
We could achieve the same behavior by overriding get_queryset() on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.
Generic filters may also present an interface in the browsable API. To do so you should implement a to_html() method which returns a rendered HTML representation of the filter. This method should have the following signature:
to_html(self, request, queryset, view)
The method should return a rendered HTML string.
You can also make the filter controls available to the schema autogeneration that REST framework provides, by implementing a get_schema_fields() method. This method should have the following signature:
get_schema_fields(self, view)
The method should return a list of coreapi.Field instances.
The following third party packages provide additional filter implementations.
The django-rest-framework-filters package works together with the DjangoFilterBackend class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.
The djangorestframework-word-filter developed as alternative to filters.SearchFilter which will search full word in text, or exact match.
django-url-filter provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django QuerySets.
drf-url-filter is a simple Django app to apply filters on drf ModelViewSet's Queryset in a clean, simple and configurable way. It also supports validations on incoming query params and their values. A beautiful python package Voluptuous is being used for validations on the incoming query parameters. The best part about voluptuous is you can define your own validations as per your query params requirements.
filters.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


Expanding the usefulness of the serializers is something that we would like to address. However, it's not a trivial problem, and it will take some serious design work.
— Russell Keith-Magee, Django users group
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
The serializers in REST framework work very similarly to Django's Form and ModelForm classes. We provide a Serializer class which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.
Let's start by creating a simple object we can use for example purposes:
We'll declare a serializer that we can use to serialize and deserialize data that corresponds to Comment objects.
Declaring a serializer looks very similar to declaring a form:
We can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class.
At this point we've translated the model instance into Python native datatypes. To finalise the serialization process we render the data into json.
Deserialization is similar. First we parse a stream into Python native datatypes...
...then we restore those native datatypes into a dictionary of validated data.
If we want to be able to return complete object instances based on the validated data we need to implement one or both of the .create() and .update() methods. For example:
If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if Comment was a Django model, the methods might look like this:
Now when deserializing data, we can call .save() to return an object instance, based on the validated data.
Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:
Both the .create() and .update() methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.
Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data.
You can do so by including additional keyword arguments when calling .save(). For example:
Any additional keyword arguments will be included in the validated_data argument when .create() or .update() are called.
In some cases the .create() and .update() method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message.
In these cases you might instead choose to override .save() directly, as being more readable and meaningful.
For example:
Note that in the case above we're now having to access the serializer .validated_data property directly.
When deserializing data, you always need to call is_valid() before attempting to access the validated data, or save an object instance. If any validation errors occur, the .errors property will contain a dictionary representing the resulting error messages. For example:
Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The non_field_errors key may also be present, and will list any general validation errors. The name of the non_field_errors key may be customized using the NON_FIELD_ERRORS_KEY REST framework setting.
When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.
The .is_valid() method takes an optional raise_exception flag that will cause it to raise a serializers.ValidationError exception if there are validation errors.
These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return HTTP 400 Bad Request responses by default.
You can specify custom field-level validation by adding .validate_<field_name> methods to your Serializer subclass. These are similar to the .clean_<field_name> methods on Django forms.
These methods take a single argument, which is the field value that requires validation.
Your validate_<field_name> methods should return the validated value or raise a serializers.ValidationError. For example:
Note: If your <field_name> is declared on your serializer with the parameter required=False then this validation step will not take place if the field is not included.
To do any other validation that requires access to multiple fields, add a method called .validate() to your Serializer subclass. This method takes a single argument, which is a dictionary of field values. It should raise a serializers.ValidationError if necessary, or just return the validated values. For example:
Individual fields on a serializer can include validators, by declaring them on the field instance, for example:
Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner Meta class, like so:
For more information see the validators documentation.
When passing an initial object or queryset to a serializer instance, the object will be made available as .instance. If no initial object is passed then the .instance attribute will be None.
When passing data to a serializer instance, the unmodified data will be made available as .initial_data. If the data keyword argument is not passed then the .initial_data attribute will not exist.
By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the partial argument in order to allow partial updates.
The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.
The Serializer class is itself a type of Field, and can be used to represent relationships where one object type is nested inside another.
If a nested representation may optionally accept the None value you should pass the required=False flag to the nested serializer.
Similarly if a nested representation should be a list of items, you should pass the many=True flag to the nested serializer.
When dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object.
Similarly, the .validated_data property will include nested data structures.
If you're supporting writable nested representations you'll need to write .create() or .update() methods that handle saving multiple objects.
The following example demonstrates how you might handle creating a user with a nested profile object.
For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is None, or not provided, which of the following should occur?
Here's an example for an .update() method on our previous UserSerializer class.
Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default ModelSerializer .create() and .update() methods do not include support for writable nested representations.
There are however, third-party packages available such as DRF Writable Nested that support automatic writable nested representations.
An alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances.
For example, suppose we wanted to ensure that User instances and Profile instances are always created together as a pair. We might write a custom manager class that looks something like this:
This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our .create() method on the serializer class can now be re-written to use the new manager method.
For more details on this approach see the Django documentation on model managers, and this blogpost on using model and manager classes.
The Serializer class can also handle serializing or deserializing lists of objects.
To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.
The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the ListSerializer documentation below.
There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs.
You can provide arbitrary additional context by passing a context argument when instantiating the serializer. For example:
The context dictionary can be used within any serializer field logic, such as a custom .to_representation() method, by accessing the self.context attribute.
Often you'll want serializer classes that map closely to Django model definitions.
The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.
The ModelSerializer class is the same as a regular Serializer class, except that:
Declaring a ModelSerializer looks like this:
By default, all the model fields on the class will be mapped to a corresponding serializer fields.
Any relationships such as foreign keys on the model will be mapped to PrimaryKeyRelatedField. Reverse relationships are not included by default unless explicitly included as specified in the serializer relations documentation.
Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with ModelSerializers where you want to determine what set of fields and validators are being automatically created for you.
To do so, open the Django shell, using python manage.py shell, then import the serializer class, instantiate it, and print the object representation…
If you only want a subset of the default fields to be used in a model serializer, you can do so using fields or exclude options, just as you would with a ModelForm. It is strongly recommended that you explicitly set all fields that should be serialized using the fields attribute. This will make it less likely to result in unintentionally exposing data when your models change.
For example:
You can also set the fields attribute to the special value '__all__' to indicate that all fields in the model should be used.
For example:
You can set the exclude attribute to a list of fields to be excluded from the serializer.
For example:
In the example above, if the Account model had 3 fields account_name, users, and created, this will result in the fields account_name and created to be serialized.
The names in the fields and exclude attributes will normally map to model fields on the model class.
Alternatively names in the fields options can map to properties or methods which take no arguments that exist on the model class.
Since version 3.3.0, it is mandatory to provide one of the attributes fields or exclude.
The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option:
The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
If you want to customize the way the serialization is done you'll need to define the field yourself.
You can add extra fields to a ModelSerializer or override the default fields by declaring fields on the class, just as you would for a Serializer class.
Extra fields can correspond to any property or callable on the model.
You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the read_only=True attribute, you may use the shortcut Meta option, read_only_fields.
This option should be a list or tuple of field names, and is declared as follows:
Model fields which have editable=False set, and AutoField fields will be set to read-only by default, and do not need to be added to the read_only_fields option.
Note: There is a special-case where a read-only field is part of a unique_together constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.
The right way to deal with this is to specify the field explicitly on the serializer, providing both the read_only=True and default=… keyword arguments.
One example of this is a read-only relation to the currently authenticated User which is unique_together with another identifier. In this case you would declare the user field like so:
Please review the Validators Documentation for details on the UniqueTogetherValidator and CurrentUserDefault classes.
There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the extra_kwargs option. As in the case of read_only_fields, this means you do not need to explicitly declare the field on the serializer.
This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:
Please keep in mind that, if the field has already been explicitly declared on the serializer class, then the extra_kwargs option will be ignored.
When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for ModelSerializer is to use the primary keys of the related instances.
Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.
For full details see the serializer relations documentation.
The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer.
Normally if a ModelSerializer does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular Serializer class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
This property should be the serializer field class, that is used for relational fields by default.
For ModelSerializer this defaults to PrimaryKeyRelatedField.
For HyperlinkedModelSerializer this defaults to serializers.HyperlinkedRelatedField.
The serializer field class that should be used for any url field on the serializer.
Defaults to serializers.HyperlinkedIdentityField
The serializer field class that should be used for any choice fields on the serializer.
Defaults to serializers.ChoiceField
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of (field_class, field_kwargs).
Called to generate a serializer field that maps to a standard model field.
The default implementation returns a serializer class based on the serializer_field_mapping attribute.
Called to generate a serializer field that maps to a relational model field.
The default implementation returns a serializer class based on the serializer_related_field attribute.
The relation_info argument is a named tuple, that contains model_field, related_model, to_many and has_through_model properties.
Called to generate a serializer field that maps to a relational model field, when the depth option has been set.
The default implementation dynamically creates a nested serializer class based on either ModelSerializer or HyperlinkedModelSerializer.
The nested_depth will be the value of the depth option, minus one.
The relation_info argument is a named tuple, that contains model_field, related_model, to_many and has_through_model properties.
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
The default implementation returns a ReadOnlyField class.
Called to generate a serializer field for the serializer's own url field. The default implementation returns a HyperlinkedIdentityField class.
Called when the field name did not map to any model field or model property. The default implementation raises an error, although subclasses may customize this behavior.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys.
By default the serializer will include a url field instead of a primary key field.
The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field.
You can explicitly include the primary key by adding it to the fields option, for example:
When instantiating a HyperlinkedModelSerializer you must include the current request in the serializer context, for example:
Doing so will ensure that the hyperlinks can include an appropriate hostname, so that the resulting representation uses fully qualified URLs, such as:
Rather than relative URLs, such as:
If you do want to use relative URLs, you should explicitly pass {'request': None} in the serializer context.
There needs to be a way of determining which views should be used for hyperlinking to model instances.
By default hyperlinks are expected to correspond to a view name that matches the style '{model_name}-detail', and looks up the instance by a pk keyword argument.
You can override a URL field view name and lookup field by using either, or both of, the view_name and lookup_field options in the extra_kwargs setting, like so:
Alternatively you can set the fields on the serializer explicitly. For example:
Tip: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the repr of a HyperlinkedModelSerializer instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.
The name of the URL field defaults to 'url'. You can override this globally, by using the URL_FIELD_NAME setting.
The ListSerializer class provides the behavior for serializing and validating multiple objects at once. You won't typically need to use ListSerializer directly, but should instead simply pass many=True when instantiating a serializer.
When a serializer is instantiated and many=True is passed, a ListSerializer instance will be created. The serializer class then becomes a child of the parent ListSerializer
The following argument can also be passed to a ListSerializer field or a serializer that is passed many=True:
This is True by default, but can be set to False if you want to disallow empty lists as valid input.
There are a few use cases when you might want to customize the ListSerializer behavior. For example:
For these cases you can modify the class that is used when many=True is passed, by using the list_serializer_class option on the serializer Meta class.
For example:
The default implementation for multiple object creation is to simply call .create() for each item in the list. If you want to customize this behavior, you'll need to customize the .create() method on ListSerializer class that is used when many=True is passed.
For example:
By default the ListSerializer class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous.
To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind:
You will need to add an explicit id field to the instance serializer. The default implicitly-generated id field is marked as read_only. This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's update method.
Here's an example of how you might choose to implement multiple updates:
It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the allow_add_remove behavior that was present in REST framework 2.
When a serializer with many=True is instantiated, we need to determine which arguments and keyword arguments should be passed to the .__init__() method for both the child Serializer class, and for the parent ListSerializer class.
The default implementation is to pass all arguments to both classes, except for validators, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class.
Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when many=True is passed. You can do so by using the many_init class method.
BaseSerializer class that can be used to easily support alternative serialization and deserialization styles.
This class implements the same basic API as the Serializer class:
There are four methods that can be overridden, depending on what functionality you want the serializer class to support:
Because this class provides the same interface as the Serializer class, you can use it with the existing generic class-based views exactly as you would for a regular Serializer or ModelSerializer.
The only difference you'll notice when doing so is the BaseSerializer classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.
To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation() method. Let's take a look at an example using a simple Django model:
It's simple to create a read-only serializer for converting HighScore instances into primitive data types.
We can now use this class to serialize single HighScore instances:
Or use it to serialize multiple instances:
To create a read-write serializer we first need to implement a .to_internal_value() method. This method returns the validated values that will be used to construct the object instance, and may raise a serializers.ValidationError if the supplied data is in an incorrect format.
Once you've implemented .to_internal_value(), the basic validation API will be available on the serializer, and you will be able to use .is_valid(), .validated_data and .errors.
If you want to also support .save() you'll need to also implement either or both of the .create() and .update() methods.
Here's a complete example of our previous HighScoreSerializer, that's been updated to support both read and write operations.
The BaseSerializer class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.
The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
If you need to alter the serialization or deserialization behavior of a serializer class, you can do so by overriding the .to_representation() or .to_internal_value() methods.
Some reasons this might be useful include...
The signatures for these methods are as follows:
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
May be overridden in order to modify the representation style. For example:
Takes the unvalidated incoming data as input and should return the validated data that will be made available as serializer.validated_data. The return value will also be passed to the .create() or .update() methods if .save() is called on the serializer class.
If any of the validation fails, then the method should raise a serializers.ValidationError(errors). The errors argument should be a dictionary mapping field names (or settings.NON_FIELD_ERRORS_KEY) to a list of error messages. If you don't need to alter deserialization behavior and instead want to provide object-level validation, it's recommended that you instead override the .validate() method.
The data argument passed to this method will normally be the value of request.data, so the datatype it provides will depend on the parser classes you have configured for your API.
Similar to Django forms, you can extend and reuse serializers through inheritance. This allows you to declare a common set of fields or methods on a parent class that can then be used in a number of serializers. For example,
Like Django's Model and ModelForm classes, the inner Meta class on serializers does not implicitly inherit from it's parents' inner Meta classes. If you want the Meta class to inherit from a parent class you must do so explicitly. For example:
Typically we would recommend not using inheritance on inner Meta classes, but instead declaring all options explicitly.
Additionally, the following caveats apply to serializer inheritance:
It’s possible to declaratively remove a Field inherited from a parent class by setting the name to be None on the subclass.
However, you can only use this technique to opt out from a field defined declaratively by a parent class; it won’t prevent the ModelSerializer from generating a default field. To opt-out from default fields, see Specifying which fields to include.
Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the .fields attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.
Modifying the fields argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer.
For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so:
This would then allow you to do the following:
REST framework 2 provided an API to allow developers to override how a ModelSerializer class would automatically generate the default set of fields.
This API included the .get_field(), .get_pk_field() and other methods.
Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change.
The following third party packages are also available.
The django-rest-marshmallow package provides an alternative implementation for serializers, using the python marshmallow library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases.
The serpy package is an alternative implementation for serializers that is built for speed. Serpy serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed.
The django-rest-framework-mongoengine package provides a MongoEngineModelSerializer serializer class that supports using MongoDB as the storage layer for Django REST framework.
The django-rest-framework-gis package provides a GeoFeatureModelSerializer serializer class that supports GeoJSON both for read and write operations.
The django-rest-framework-hstore package provides an HStoreSerializer to support django-hstore DictionaryField model field and its schema-mode feature.
The dynamic-rest package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers.
The drf-dynamic-fields package provides a mixin to dynamically limit the fields per serializer to a subset specified by an URL parameter.
The drf-flex-fields package extends the ModelSerializer and ModelViewSet to provide commonly used functionality for dynamically setting fields and expanding primitive fields to nested models, both from URL parameters and your serializer class definitions.
The django-rest-framework-serializer-extensions package provides a collection of tools to DRY up your serializers, by allowing fields to be defined on a per-view/request basis. Fields can be whitelisted, blacklisted and child serializers can be optionally expanded.
The html-json-forms package provides an algorithm and serializer for processing <form> submissions per the (inactive) HTML JSON Form specification. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, <input name="items[0][id]" value="5"> will be interpreted as {"items": [{"id": "5"}]}.
DRF-Base64 provides a set of field and model serializers that handles the upload of base64-encoded files.
djangorestframework-queryfields allows API clients to specify which fields will be sent in the response via inclusion/exclusion query parameters.
The drf-writable-nested package provides writable nested model serializer which allows to create/update models with nested related data.
The drf-encrypt-content package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
serializers.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


Namespaces are one honking great idea - let's do more of those!
— The Zen of Python
Configuration for REST framework is all namespaced inside a single Django setting, named REST_FRAMEWORK.
For example your project's settings.py file might include something like this:
If you need to access the values of REST framework's API settings in your project, you should use the api_settings object. For example.
The api_settings object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.
The following settings control the basic API policies, and are applied to every APIView class-based view, or @api_view function based view.
A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a Response object.
Default:
A list or tuple of parser classes, that determines the default set of parsers used when accessing the request.data property.
Default:
A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the request.user or request.auth properties.
Default:
A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list.
Default:
A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.
Default: []
A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.
Default: 'rest_framework.negotiation.DefaultContentNegotiation'
A view inspector class that will be used for schema generation.
Default: 'rest_framework.schemas.openapi.AutoSchema'
The following settings control the behavior of the generic class-based views.
A list of filter backend classes that should be used for generic filtering. If set to None then generic filtering is disabled.
The default class to use for queryset pagination. If set to None, pagination is disabled by default. See the pagination documentation for further guidance on setting and modifying the pagination style.
Default: None
The default page size to use for pagination. If set to None, pagination is disabled by default.
Default: None
The name of a query parameter, which can be used to specify the search term used by SearchFilter.
Default: search
The name of a query parameter, which can be used to specify the ordering of results returned by OrderingFilter.
Default: ordering
The value that should be used for request.version when no versioning information is present.
Default: None
If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set.
Default: None
The string that should used for any versioning parameters, such as in the media type or URL query parameters.
Default: 'version'
The following settings control the behavior of unauthenticated requests.
The class that should be used to initialize request.user for unauthenticated requests. (If removing authentication entirely, e.g. by removing django.contrib.auth from INSTALLED_APPS, set UNAUTHENTICATED_USER to None.)
Default: django.contrib.auth.models.AnonymousUser
The class that should be used to initialize request.auth for unauthenticated requests.
Default: None
The following settings control the behavior of APIRequestFactory and APIClient
The default format that should be used when making test requests.
This should match up with the format of one of the renderer classes in the TEST_REQUEST_RENDERER_CLASSES setting.
Default: 'multipart'
The renderer classes that are supported when building test requests.
The format of any of these renderer classes may be used when constructing a test request, for example: client.post('/users', {'username': 'jamie'}, format='json')
Default:
If set, this maps the 'pk' identifier in the URL conf onto the actual field name when generating a schema path parameter. Typically this will be 'id'. This gives a more suitable representation as "primary key" is an implementation detail, whereas "identifier" is a more general concept.
Default: True
If set, this is used to map internal viewset method names onto external action names used in the schema generation. This allows us to generate names that are more suitable for an external representation than those that are used internally in the codebase.
Default: {'retrieve': 'read', 'destroy': 'delete'}
The name of a URL parameter that may be used to override the default content negotiation Accept header behavior, by using a format=… query parameter in the request URL.
For example: http://example.com/organizations/?format=csv
If the value of this setting is None then URL format overrides will be disabled.
Default: 'format'
The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using format_suffix_patterns to include suffixed URL patterns.
For example: http://example.com/organizations.csv/
Default: 'format'
The following settings are used to control how date and time representations may be parsed and rendered.
A format string that should be used by default for rendering the output of DateTimeField serializer fields. If None, then DateTimeField serializer fields will return Python datetime objects, and the datetime encoding will be determined by the renderer.
May be any of None, 'iso-8601' or a Python strftime format string.
Default: 'iso-8601'
A list of format strings that should be used by default for parsing inputs to DateTimeField serializer fields.
May be a list including the string 'iso-8601' or Python strftime format strings.
Default: ['iso-8601']
A format string that should be used by default for rendering the output of DateField serializer fields. If None, then DateField serializer fields will return Python date objects, and the date encoding will be determined by the renderer.
May be any of None, 'iso-8601' or a Python strftime format string.
Default: 'iso-8601'
A list of format strings that should be used by default for parsing inputs to DateField serializer fields.
May be a list including the string 'iso-8601' or Python strftime format strings.
Default: ['iso-8601']
A format string that should be used by default for rendering the output of TimeField serializer fields. If None, then TimeField serializer fields will return Python time objects, and the time encoding will be determined by the renderer.
May be any of None, 'iso-8601' or a Python strftime format string.
Default: 'iso-8601'
A list of format strings that should be used by default for parsing inputs to TimeField serializer fields.
May be a list including the string 'iso-8601' or Python strftime format strings.
Default: ['iso-8601']
When set to True, JSON responses will allow unicode characters in responses. For example:
When set to False, JSON responses will escape non-ascii characters, like so:
Both styles conform to RFC 4627, and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses.
Default: True
When set to True, JSON responses will return compact representations, with no spacing after ':' and ',' characters. For example:
When set to False, JSON responses will return slightly more verbose representations, like so:
The default style is to return minified responses, in line with Heroku's API design guidelines.
Default: True
When set to True, JSON rendering and parsing will only observe syntactically valid JSON, raising an exception for the extended float values (nan, inf, -inf) accepted by Python's json module. This is the recommended setting, as these values are not generally supported. e.g., neither Javascript's JSON.Parse nor PostgreSQL's JSON data type accept these values.
When set to False, JSON rendering and parsing will be permissive. However, these values are still invalid and will need to be specially handled in your code.
Default: True
When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations.
When set to True, the serializer DecimalField class will return strings instead of Decimal objects. When set to False, serializers will return Decimal objects, which the default JSON encoder will return as floats.
Default: True
The following settings are used to generate the view names and descriptions, as used in responses to OPTIONS requests, and as used in the browsable API.
A string representing the function that should be used when generating view names.
This should be a function with the following signature:
If the view instance inherits ViewSet, it may have been initialized with several optional arguments:
Default: 'rest_framework.views.get_view_name'
A string representing the function that should be used when generating view descriptions.
This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support rst markup in your view docstrings being output in the browsable API.
This should be a function with the following signature:
If the view instance inherits ViewSet, it may have been initialized with several optional arguments:
Default: 'rest_framework.views.get_view_description'
Global settings for select field cutoffs for rendering relational fields in the browsable API.
Global setting for the html_cutoff value. Must be an integer.
Default: 1000
A string representing a global setting for html_cutoff_text.
Default: "More than {count} items..."
A string representing the function that should be used when returning a response for any given exception. If the function returns None, a 500 error will be raised.
This setting can be changed to support error responses other than the default {"detail": "Failure..."} responses. For example, you can use it to provide API responses like {"errors": [{"message": "Failure...", "code": ""} ...]}.
This should be a function with the following signature:
Default: 'rest_framework.views.exception_handler'
A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors.
Default: 'non_field_errors'
A string representing the key that should be used for the URL fields generated by HyperlinkedModelSerializer.
Default: 'url'
An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to None then less strict IP matching will be used by the throttle classes.
Default: None
settings.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