Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.
— Django Documentation
One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
If the generic views don't suit the needs of your API, you can drop down to using the regular APIView class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
Typically when using the generic views, you'll override the view, and set several class attributes.
For more complex cases you might also want to override various methods on the view class. For example.
For very simple cases you might want to pass through any class attributes using the .as_view() method. For example, your URLconf might include something like the following entry:
This class extends REST framework's APIView class, adding commonly required behavior for standard list and detail views.
Each of the concrete generic views provided is built by combining GenericAPIView, with one or more mixin classes.
Basic settings:
The following attributes control the basic view behavior.
Pagination:
The following attributes are used to control pagination when used with list views.
Filtering:
Base methods:
Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the queryset attribute.
This method should always be used rather than accessing self.queryset directly, as self.queryset gets evaluated only once, and those results are cached for all subsequent requests.
May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.
For example:
Returns an object instance that should be used for detail views. Defaults to using the lookup_field parameter to filter the base queryset.
May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.
For example:
Note that if your API doesn't include any object level permissions, you may optionally exclude the self.check_object_permissions, and simply return the object from the get_object_or_404 lookup.
Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
For example:
Returns the class that should be used for the serializer. Defaults to returning the serializer_class attribute.
May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.
For example:
Save and deletion hooks:
The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.
These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.
You can also use these hooks to provide additional validation, by raising a ValidationError(). This can be useful if you need some validation logic to apply at the point of database save. For example:
Other methods:
You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using GenericAPIView.
The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as .get() and .post(), directly. This allows for more flexible composition of behavior.
The mixin classes can be imported from rest_framework.mixins.
Provides a .list(request, *args, **kwargs) method, that implements listing a queryset.
If the queryset is populated, this returns a 200 OK response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
Provides a .create(request, *args, **kwargs) method, that implements creating and saving a new model instance.
If an object is created this returns a 201 Created response, with a serialized representation of the object as the body of the response. If the representation contains a key named url, then the Location header of the response will be populated with that value.
If the request data provided for creating the object was invalid, a 400 Bad Request response will be returned, with the error details as the body of the response.
Provides a .retrieve(request, *args, **kwargs) method, that implements returning an existing model instance in a response.
If an object can be retrieved this returns a 200 OK response, with a serialized representation of the object as the body of the response. Otherwise it will return a 404 Not Found.
Provides a .update(request, *args, **kwargs) method, that implements updating and saving an existing model instance.
Also provides a .partial_update(request, *args, **kwargs) method, which is similar to the update method, except that all fields for the update will be optional. This allows support for HTTP PATCH requests.
If an object is updated this returns a 200 OK response, with a serialized representation of the object as the body of the response.
If the request data provided for updating the object was invalid, a 400 Bad Request response will be returned, with the error details as the body of the response.
Provides a .destroy(request, *args, **kwargs) method, that implements deletion of an existing model instance.
If an object is deleted this returns a 204 No Content response, otherwise it will return a 404 Not Found.
The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.
The view classes can be imported from rest_framework.generics.
Used for create-only endpoints.
Provides a post method handler.
Extends: GenericAPIView, CreateModelMixin
Used for read-only endpoints to represent a collection of model instances.
Provides a get method handler.
Extends: GenericAPIView, ListModelMixin
Used for read-only endpoints to represent a single model instance.
Provides a get method handler.
Extends: GenericAPIView, RetrieveModelMixin
Used for delete-only endpoints for a single model instance.
Provides a delete method handler.
Extends: GenericAPIView, DestroyModelMixin
Used for update-only endpoints for a single model instance.
Provides put and patch method handlers.
Extends: GenericAPIView, UpdateModelMixin
Used for read-write endpoints to represent a collection of model instances.
Provides get and post method handlers.
Extends: GenericAPIView, ListModelMixin, CreateModelMixin
Used for read or update endpoints to represent a single model instance.
Provides get, put and patch method handlers.
Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin
Used for read or delete endpoints to represent a single model instance.
Provides get and delete method handlers.
Extends: GenericAPIView, RetrieveModelMixin, DestroyModelMixin
Used for read-write-delete endpoints to represent a single model instance.
Provides get, put, patch and delete method handlers.
Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin
Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.
For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:
You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.
Using custom mixins is a good option if you have custom behavior that needs to be used.
If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:
Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.
Prior to version 3.0 the REST framework mixins treated PUT as either an update or a create operation, depending on if the object already existed or not.
Allowing PUT as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning 404 responses.
Both styles "PUT as 404" and "PUT as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.
If you need to generic PUT-as-create behavior you may want to include something like this AllowPUTAsCreateMixin class as a mixin to your views.
The following third party packages provide additional generic view implementations.
Django Rest Multiple Models provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
mixins.pygenerics.py


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


Versioning an interface is just a "polite" way to kill deployed clients.
— Roy Fielding.
API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes.
Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers.
There are a number of valid approaches to approaching versioning. Non-versioned systems can also be appropriate, particularly if you're engineering for very long-term systems with multiple clients outside of your control.
When API versioning is enabled, the request.version attribute will contain a string that corresponds to the version requested in the incoming client request.
By default, versioning is not enabled, and request.version will always return None.
How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example:
The reverse function included by REST framework ties in with the versioning scheme. You need to make sure to include the current request as a keyword argument, like so.
The above function will apply any URL transformations appropriate to the request version. For example:
When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer.
Doing so will allow any returned URLs to include the appropriate versioning.
The versioning scheme is defined by the DEFAULT_VERSIONING_CLASS settings key.
Unless it is explicitly set, the value for DEFAULT_VERSIONING_CLASS will be None. In this case the request.version attribute will always return None.
You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the versioning_class attribute.
The following settings keys are also used to control versioning:
You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the default_version, allowed_versions and version_param class variables. For example, if you want to use URLPathVersioning:
This scheme requires the client to specify the version as part of the media type in the Accept header. The version is included as a media type parameter, that supplements the main media type.
Here's an example HTTP request using the accept header versioning style.
In the example request above request.version attribute would return the string '1.0'.
Versioning based on accept headers is generally considered as best practice, although other styles may be suitable depending on your client requirements.
Strictly speaking the json media type is not specified as including additional parameters. If you are building a well-specified public API you might consider using a vendor media type. To do so, configure your renderers to use a JSON based renderer with a custom media type:
Your client requests would now look like this:
This scheme requires the client to specify the version as part of the URL path.
Your URL conf must include a pattern that matches the version with a 'version' keyword argument, so that this information is available to the versioning scheme.
To the client, this scheme is the same as URLPathVersioning. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.
With this scheme the request.version attribute is determined based on the namespace that matches the incoming request path.
In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace:
Both URLPathVersioning and NamespaceVersioning are reasonable if you just need a simple versioning scheme. The URLPathVersioning approach might be better suitable for small ad-hoc projects, and the NamespaceVersioning is probably easier to manage for larger projects.
The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL.
For example the following is an HTTP request to the http://v1.example.com/bookings/ URL:
By default this implementation expects the hostname to match this simple regular expression:
Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.
The HostNameVersioning scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as 127.0.0.1. There are various online tutorials on how to access localhost with a custom subdomain which you may find helpful in this case.
Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions.
This scheme is a simple style that includes the version as a query parameter in the URL. For example:
To implement a custom versioning scheme, subclass BaseVersioning and override the .determine_version method.
The following example uses a custom X-API-Version header to determine the requested version.
If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the .reverse() method on the class. See the source code for examples.
versioning.py


HTTP/1.1 420 Enhance Your Calm
Twitter API rate limiting response
Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.
As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.
Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.
Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
Before running the main body of the view each throttle in the list is checked. If any throttle check fails an exceptions.Throttled exception will be raised, and the main body of the view will not run.
The default throttling policy may be set globally, using the DEFAULT_THROTTLE_CLASSES and DEFAULT_THROTTLE_RATES settings. For example.
The rate descriptions used in DEFAULT_THROTTLE_RATES may include second, minute, hour or day as the throttle period.
You can also set the throttling policy on a per-view or per-viewset basis, using the APIView class-based views.
If you're using the @api_view decorator with function based views you can use the following decorator.
It's also possible to set throttle classes for routes that are created using the @action decorator. Throttle classes set in this way will override any viewset level class settings.
The X-Forwarded-For HTTP header and REMOTE_ADDR WSGI variable are used to uniquely identify client IP addresses for throttling. If the X-Forwarded-For header is present then it will be used, otherwise the value of the REMOTE_ADDR variable from the WSGI environment will be used.
If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the NUM_PROXIES setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the X-Forwarded-For header, once any application proxy IP addresses have first been excluded. If set to zero, then the REMOTE_ADDR value will always be used as the identifying IP address.
It is important to understand that if you configure the NUM_PROXIES setting, then all clients behind a unique NAT'd gateway will be treated as a single client.
Further context on how the X-Forwarded-For header works, and identifying a remote client IP can be found here.
The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate cache settings. The default value of LocMemCache backend should be okay for simple setups. See Django's cache documentation for more details.
If you need to use a cache other than 'default', you can do so by creating a custom throttle class and setting the cache attribute. For example:
You'll need to remember to also set your custom throttle class in the 'DEFAULT_THROTTLE_CLASSES' settings key, or using the throttle_classes view attribute.
The AnonRateThrottle will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
The allowed request rate is determined from one of the following (in order of preference).
AnonRateThrottle is suitable if you want to restrict the rate of requests from unknown sources.
The UserRateThrottle will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.
The allowed request rate is determined from one of the following (in order of preference).
An API may have multiple UserRateThrottles in place at the same time. To do so, override UserRateThrottle and set a unique "scope" for each class.
For example, multiple user throttle rates could be implemented by using the following classes...
...and the following settings.
UserRateThrottle is suitable if you want simple global rate restrictions per-user.
The ScopedRateThrottle class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a .throttle_scope property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.
The allowed request rate is determined by the DEFAULT_THROTTLE_RATES setting using a key from the request "scope".
For example, given the following views...
...and the following settings.
User requests to either ContactListView or ContactDetailView would be restricted to a total of 1000 requests per-day. User requests to UploadView would be restricted to 20 requests per day.
To create a custom throttle, override BaseThrottle and implement .allow_request(self, request, view). The method should return True if the request should be allowed, and False otherwise.
Optionally you may also override the .wait() method. If implemented, .wait() should return a recommended number of seconds to wait before attempting the next request, or None. The .wait() method will only be called if .allow_request() has previously returned False.
If the .wait() method is implemented and the request is throttled, then a Retry-After header will be included in the response.
The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
throttling.py


Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.
— Doug Hellmann, Python Exception Handling Techniques
REST framework's views handle various exceptions, and deal with returning appropriate error responses.
The handled exceptions are:
In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.
Most error responses will include a key detail in the body of the response.
For example, the following request:
Might receive an error response indicating that the DELETE method is not allowed on that resource:
Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the NON_FIELD_ERRORS_KEY setting.
An example validation error might look like this:
You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.
The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.
For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:
In order to alter the style of the response, you could write the following custom exception handler:
The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as context['view'].
The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER setting key. For example:
If not specified, the 'EXCEPTION_HANDLER' setting defaults to the standard exception handler provided by REST framework:
Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails.
Signature: APIException()
The base class for all exceptions raised inside an APIView class or @api_view.
To provide a custom exception, subclass APIException and set the .status_code, .default_detail, and default_code attributes on the class.
For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so:
There are a number of different properties available for inspecting the status of an API exception. You can use these to build custom exception handling for your project.
The available attributes and methods are:
In most cases the error detail will be a simple item:
In the case of validation errors the error detail will be either a list or dictionary of items:
Signature: ParseError(detail=None, code=None)
Raised if the request contains malformed data when accessing request.data.
By default this exception results in a response with the HTTP status code "400 Bad Request".
Signature: AuthenticationFailed(detail=None, code=None)
Raised when an incoming request includes incorrect authentication.
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.
Signature: NotAuthenticated(detail=None, code=None)
Raised when an unauthenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.
Signature: PermissionDenied(detail=None, code=None)
Raised when an authenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "403 Forbidden".
Signature: NotFound(detail=None, code=None)
Raised when a resource does not exists at the given URL. This exception is equivalent to the standard Http404 Django exception.
By default this exception results in a response with the HTTP status code "404 Not Found".
Signature: MethodNotAllowed(method, detail=None, code=None)
Raised when an incoming request occurs that does not map to a handler method on the view.
By default this exception results in a response with the HTTP status code "405 Method Not Allowed".
Signature: NotAcceptable(detail=None, code=None)
Raised when an incoming request occurs with an Accept header that cannot be satisfied by any of the available renderers.
By default this exception results in a response with the HTTP status code "406 Not Acceptable".
Signature: UnsupportedMediaType(media_type, detail=None, code=None)
Raised if there are no parsers that can handle the content type of the request data when accessing request.data.
By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".
Signature: Throttled(wait=None, detail=None, code=None)
Raised when an incoming request fails the throttling checks.
By default this exception results in a response with the HTTP status code "429 Too Many Requests".
Signature: ValidationError(detail, code=None)
The ValidationError exception is slightly different from the other APIException classes:
The ValidationError class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid with the raise_exception keyword argument:
The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.
By default this exception results in a response with the HTTP status code "400 Bad Request".
Django REST Framework provides two error views suitable for providing generic JSON 500 Server Error and 400 Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an API-only application.)
Use these as per Django's Customizing error views documentation.
Returns a response with status code 500 and application/json content type.
Set as handler500:
Returns a response with status code 400 and application/json content type.
Set as handler400:
exceptions.py


Validators can be useful for re-using validation logic between different types of fields.
— Django documentation
Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.
However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class.
With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
When you're using ModelSerializer all of this is handled automatically for you. If you want to drop down to using Serializer classes instead, then you need to define the validation rules explicitly.
As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.
Here's a basic ModelSerializer that we can use for creating or updating instances of CustomerReportRecord:
If we open up the Django shell using manage.py shell we can now
The interesting bit here is the reference field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.
Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.
This validator can be used to enforce the unique=True constraint on model fields. It takes a single required argument, and an optional messages argument:
This validator should be applied to serializer fields, like so:
This validator can be used to enforce unique_together constraints on model instances. It has two required arguments, and a single optional messages argument:
The validator should be applied to serializer classes, like so:
Note: The UniqueTogetherValidator class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.
These validators can be used to enforce the unique_for_date, unique_for_month and unique_for_year constraints on model instances. They take the following arguments:
The validator should be applied to serializer classes, like so:
The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class default=..., because the value being used for the default wouldn't be generated until after the validation has run.
There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using ModelSerializer you'll probably simply rely on the defaults that REST framework generates for you, but if you are using Serializer or simply want more explicit control, use on of the styles demonstrated below.
If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a default argument, or by setting required=True.
If you want the date field to be visible, but not editable by the user, then set read_only=True and additionally set a default=... argument.
If you want the date field to be entirely hidden from the user, then use HiddenField. This field type does not accept user input, but instead always returns its default value to the validated_data in the serializer.
Note: The UniqueFor<Range>Validator classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.
Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that is available as input to the validator.
Two patterns that you may want to use for this sort of validation include:
REST framework includes a couple of defaults that may be useful in this context.
A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.
A default class that can be used to only set a default argument during create operations. During updates the field is omitted.
It takes a single argument, which is the default value or callable that should be used during create operations.
There are some ambiguous cases where you'll need to instead handle validation explicitly, rather than relying on the default serializer classes that ModelSerializer generates.
In these cases you may want to disable the automatically generated validators, by specifying an empty list for the serializer Meta.validators attribute.
By default "unique together" validation enforces that all fields be required=True. In some cases, you might want to explicit apply required=False to one of the fields, in which case the desired behaviour of the validation is ambiguous.
In this case you will typically need to exclude the validator from the serializer class, and instead write any validation logic explicitly, either in the .validate() method, or else in the view.
For example:
When applying an update to an existing instance, uniqueness validators will exclude the current instance from the uniqueness check. The current instance is available in the context of the uniqueness check, because it exists as an attribute on the serializer, having initially been passed using instance=... when instantiating the serializer.
In the case of update operations on nested serializers there's no way of applying this exclusion, because the instance is not available.
Again, you'll probably want to explicitly remove the validator from the serializer class, and write the code for the validation constraint explicitly, in a .validate() method, or in the view.
If you're not sure exactly what behavior a ModelSerializer class will generate it is usually a good idea to run manage.py shell, and print an instance of the serializer, so that you can inspect the fields and validators that it automatically generates for you.
Also keep in mind that with complex cases it can often be better to explicitly define your serializer classes, rather than relying on the default ModelSerializer behavior. This involves a little more code, but ensures that the resulting behavior is more transparent.
You can use any of Django's existing validators, or write your own custom validators.
A validator may be any callable that raises a serializers.ValidationError on failure.
You can specify custom field-level validation by adding .validate_<field_name> methods to your Serializer subclass. This is documented in the Serializer docs
To write a class-based validator, use the __call__ method. Class-based validators are useful as they allow you to parameterize and reuse behavior.
In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by setting a requires_context = True attribute on the validator. The __call__ method will then be called with the serializer_field or serializer as an additional argument.
validators.py


After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.
— Ruby on Rails Documentation
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().
The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.
Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.
Let's define a simple viewset that can be used to list or retrieve all the users in the system.
If we need to, we can bind this viewset into two separate views, like so:
Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.
Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:
There are two main advantages of using a ViewSet class over using a View class.
Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
During dispatch, the following attributes are available on the ViewSet.
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the list action similar to this:
If you have ad-hoc methods that should be routable, you can mark them as such with the @action decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the detail argument to True or False. The router will configure its URL patterns accordingly. e.g., the DefaultRouter will configure detail actions to contain pk in their URL patterns.
A more complete example of extra actions:
The action decorator will route GET requests by default, but may also accept other HTTP methods by setting the methods argument. For example:
The decorator allows you to override any viewset-level configuration such as permission_classes, serializer_class, filter_backends...:
The two new actions will then be available at the urls ^users/{pk}/set_password/$ and ^users/{pk}/unset_password/$. Use the url_path and url_name parameters to change the URL segment and the reverse URL name of the action.
To view all extra actions, call the .get_extra_actions() method.
Extra actions can map additional HTTP methods to separate ViewSet methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.
If you need to get the URL of an action, use the .reverse_action() method. This is a convenience wrapper for reverse(), automatically passing the view's request object and prepending the url_name with the .basename attribute.
Note that the basename is provided by the router during ViewSet registration. If you are not using a router, then you must provide the basename argument to the .as_view() method.
Using the example from the previous section:
Alternatively, you can use the url_name attribute set by the @action decorator.
The url_name argument for .reverse_action() should match the same argument to the @action decorator. Additionally, this method can be used to reverse the default actions, such as list and create.
The ViewSet class inherits from APIView. You can use any of the standard attributes such as permission_classes, authentication_classes in order to control the API policy on the viewset.
The ViewSet class does not provide any implementations of actions. In order to use a ViewSet class you'll override the class and define the action implementations explicitly.
The GenericViewSet class inherits from GenericAPIView, and provides the default set of get_object, get_queryset methods and other generic view base behavior, but does not include any actions by default.
In order to use a GenericViewSet class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.
The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy().
Because ModelViewSet extends GenericAPIView, you'll normally need to provide at least the queryset and serializer_class attributes. For example:
Note that you can use any of the standard attributes or method overrides provided by GenericAPIView. For example, to use a ViewSet that dynamically determines the queryset it should operate on, you might do something like this:
Note however that upon removal of the queryset property from your ViewSet, any associated router will be unable to derive the basename of your Model automatically, and so you will have to specify the basename kwarg as part of your router registration.
Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.
The ReadOnlyModelViewSet class also inherits from GenericAPIView. As with ModelViewSet it also includes implementations for various actions, but unlike ModelViewSet only provides the 'read-only' actions, .list() and .retrieve().
As with ModelViewSet, you'll normally need to provide at least the queryset and serializer_class attributes. For example:
Again, as with ModelViewSet, you can use any of the standard attributes and method overrides available to GenericAPIView.
You may need to provide custom ViewSet classes that do not have the full set of ModelViewSet actions, or that customize the behavior in some other way.
To create a base viewset class that provides create, list and retrieve operations, inherit from GenericViewSet, and mixin the required actions:
By creating your own base ViewSet classes, you can provide common behavior that can be reused in multiple viewsets across your API.
viewsets.py


Base class for all estimators in scikit-learn.
All estimators should specify all the parameters that can be set at the class level in their __init__ as explicit keyword arguments (no *args or **kwargs).
get_params([deep])
Get parameters for this estimator.
set_params(**params)
Set the parameters of this estimator.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Inductive Clustering
Approximate nearest neighbors in TSNE


Base class for all estimators in scikit-learn.
All estimators should specify all the parameters that can be set at the class level in their __init__ as explicit keyword arguments (no *args or **kwargs).
get_params([deep])
Get parameters for this estimator.
set_params(**params)
Set the parameters of this estimator.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.


Mixin class for all bicluster estimators in scikit-learn.
Convenient way to get row and column indicators together.
get_indices(i)
Row and column indices of the i’th bicluster.
get_shape(i)
Shape of the i’th bicluster.
get_submatrix(i, data)
Return the submatrix corresponding to bicluster i.
Convenient way to get row and column indicators together.
Returns the rows_ and columns_ members.
Row and column indices of the i’th bicluster.
Only works if rows_ and columns_ attributes exist.
The index of the cluster.
Indices of rows in the dataset that belong to the bicluster.
Indices of columns in the dataset that belong to the bicluster.
Shape of the i’th bicluster.
The index of the cluster.
Number of rows in the bicluster.
Number of columns in the bicluster.
Return the submatrix corresponding to bicluster i.
The index of the cluster.
The data.
The submatrix corresponding to bicluster i.
Works with sparse matrices. Only works if rows_ and columns_ attributes exist.


Convenient way to get row and column indicators together.
Returns the rows_ and columns_ members.


Row and column indices of the i’th bicluster.
Only works if rows_ and columns_ attributes exist.
The index of the cluster.
Indices of rows in the dataset that belong to the bicluster.
Indices of columns in the dataset that belong to the bicluster.


Shape of the i’th bicluster.
The index of the cluster.
Number of rows in the bicluster.
Number of columns in the bicluster.


Return the submatrix corresponding to bicluster i.
The index of the cluster.
The data.
The submatrix corresponding to bicluster i.
Works with sparse matrices. Only works if rows_ and columns_ attributes exist.


Mixin class for all classifiers in scikit-learn.
score(X, y[, sample_weight])
Return the mean accuracy on the given test data and labels.
Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.


Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.


Constructs a new unfitted estimator with the same parameters.
Clone does a deep copy of the model in an estimator without actually copying attached data. It yields a new estimator with the same parameters that has not been fitted on any data.
If the estimator’s random_state parameter is an integer (or if the estimator doesn’t have a random_state parameter), an exact clone is returned: the clone and the original estimator will give the exact same results. Otherwise, statistical clone is returned: the clone might yield different results from the original estimator. More details can be found in Controlling randomness.
The estimator or group of estimators to be cloned.
If safe is False, clone will fall back to a deep copy on objects that are not estimators.


Mixin class for all cluster estimators in scikit-learn.
fit_predict(X[, y])
Perform clustering on X and returns cluster labels.
Perform clustering on X and returns cluster labels.
Input data.
Not used, present for API consistency by convention.
Cluster labels.


Perform clustering on X and returns cluster labels.
Input data.
Not used, present for API consistency by convention.
Cluster labels.


Mixin class for all density estimators in scikit-learn.
score(X[, y])
Return the score of the model on the data X.
Return the score of the model on the data X.
Test samples.
Not used, present for API consistency by convention.


Return the score of the model on the data X.
Test samples.
Not used, present for API consistency by convention.


Return True if the given estimator is (probably) a classifier.
Estimator object to test.
True if estimator is a classifier and False otherwise.


Return True if the given estimator is (probably) a regressor.
Estimator object to test.
True if estimator is a regressor and False otherwise.


Mixin class for all regression estimators in scikit-learn.
score(X, y[, sample_weight])
Return the coefficient of determination \(R^2\) of the prediction.
Return the coefficient of determination \(R^2\) of the prediction.
The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
True values for X.
Sample weights.
\(R^2\) of self.predict(X) wrt. y.
The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).


Return the coefficient of determination \(R^2\) of the prediction.
The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
True values for X.
Sample weights.
\(R^2\) of self.predict(X) wrt. y.
The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).


Mixin class for all transformers in scikit-learn.
fit_transform(X[, y])
Fit to data, then transform it.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Approximate nearest neighbors in TSNE


Mixin class for all transformers in scikit-learn.
fit_transform(X[, y])
Fit to data, then transform it.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.


Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.


Probability calibration with isotonic regression or logistic regression.
This class uses cross-validation to both estimate the parameters of a classifier and subsequently calibrate a classifier. With default ensemble=True, for each cv split it fits a copy of the base estimator to the training subset, and calibrates it using the testing subset. For prediction, predicted probabilities are averaged across these individual calibrated classifiers. When ensemble=False, cross-validation is used to obtain unbiased predictions, via cross_val_predict, which are then used for calibration. For prediction, the base estimator, trained using all the data, is used. This is the method implemented when probabilities=True for sklearn.svm estimators.
Already fitted classifiers can be calibrated via the parameter cv="prefit". In this case, no cross-validation is used and all provided data is used for calibration. The user has to take care manually that data for model fitting and calibration are disjoint.
The calibration is based on the decision_function method of the base_estimator if it exists, else on predict_proba.
Read more in the User Guide.
The classifier whose output need to be calibrated to provide more accurate predict_proba outputs. The default classifier is a LinearSVC.
The method to use for calibration. Can be ‘sigmoid’ which corresponds to Platt’s method (i.e. a logistic regression model) or ‘isotonic’ which is a non-parametric approach. It is not advised to use isotonic calibration with too few calibration samples (<<1000) since it tends to overfit.
Determines the cross-validation splitting strategy. Possible inputs for cv are:
For integer/None inputs, if y is binary or multiclass, StratifiedKFold is used. If y is neither binary nor multiclass, KFold is used.
Refer to the User Guide for the various cross-validation strategies that can be used here.
If “prefit” is passed, it is assumed that base_estimator has been fitted already and all data is used for calibration.
Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors.
Base estimator clones are fitted in parallel across cross-validation iterations. Therefore parallelism happens only when cv != "prefit".
See Glossary for more details.
New in version 0.24.
Determines how the calibrator is fitted when cv is not 'prefit'. Ignored if cv='prefit'.
If True, the base_estimator is fitted using training data and calibrated using testing data, for each cv fold. The final estimator is an ensemble of n_cv fitted classifer and calibrator pairs, where n_cv is the number of cross-validation folds. The output is the average predicted probabilities of all pairs.
If False, cv is used to compute unbiased predictions, via cross_val_predict, which are then used for calibration. At prediction time, the classifier used is the base_estimator trained on all the data. Note that this method is also internally implemented in sklearn.svm estimators with the probabilities=True parameter.
New in version 0.24.
The class labels.
The list of classifier and calibrator pairs.
Changed in version 0.24: Single calibrated classifier case when ensemble=False.
Obtaining calibrated probability estimates from decision trees and naive Bayesian classifiers, B. Zadrozny & C. Elkan, ICML 2001
Transforming Classifier Scores into Accurate Multiclass Probability Estimates, B. Zadrozny & C. Elkan, (KDD 2002)
Probabilistic Outputs for Support Vector Machines and Comparisons to Regularized Likelihood Methods, J. Platt, (1999)
Predicting Good Probabilities with Supervised Learning, A. Niculescu-Mizil & R. Caruana, ICML 2005
fit(X, y[, sample_weight])
Fit the calibrated model.
get_params([deep])
Get parameters for this estimator.
predict(X)
Predict the target of new samples.
predict_proba(X)
Calibrated probabilities of classification.
score(X, y[, sample_weight])
Return the mean accuracy on the given test data and labels.
set_params(**params)
Set the parameters of this estimator.
Fit the calibrated model.
Training data.
Target values.
Sample weights. If None, then samples are equally weighted.
Returns an instance of self.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict the target of new samples. The predicted class is the class that has the highest probability, and can thus be different from the prediction of the uncalibrated classifier.
The samples.
The predicted class.
Calibrated probabilities of classification.
This function returns calibrated probabilities of classification according to each class on an array of test vectors X.
The samples.
The predicted probas.
Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.


Probability calibration with isotonic regression or logistic regression.
This class uses cross-validation to both estimate the parameters of a classifier and subsequently calibrate a classifier. With default ensemble=True, for each cv split it fits a copy of the base estimator to the training subset, and calibrates it using the testing subset. For prediction, predicted probabilities are averaged across these individual calibrated classifiers. When ensemble=False, cross-validation is used to obtain unbiased predictions, via cross_val_predict, which are then used for calibration. For prediction, the base estimator, trained using all the data, is used. This is the method implemented when probabilities=True for sklearn.svm estimators.
Already fitted classifiers can be calibrated via the parameter cv="prefit". In this case, no cross-validation is used and all provided data is used for calibration. The user has to take care manually that data for model fitting and calibration are disjoint.
The calibration is based on the decision_function method of the base_estimator if it exists, else on predict_proba.
Read more in the User Guide.
The classifier whose output need to be calibrated to provide more accurate predict_proba outputs. The default classifier is a LinearSVC.
The method to use for calibration. Can be ‘sigmoid’ which corresponds to Platt’s method (i.e. a logistic regression model) or ‘isotonic’ which is a non-parametric approach. It is not advised to use isotonic calibration with too few calibration samples (<<1000) since it tends to overfit.
Determines the cross-validation splitting strategy. Possible inputs for cv are:
For integer/None inputs, if y is binary or multiclass, StratifiedKFold is used. If y is neither binary nor multiclass, KFold is used.
Refer to the User Guide for the various cross-validation strategies that can be used here.
If “prefit” is passed, it is assumed that base_estimator has been fitted already and all data is used for calibration.
Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors.
Base estimator clones are fitted in parallel across cross-validation iterations. Therefore parallelism happens only when cv != "prefit".
See Glossary for more details.
New in version 0.24.
Determines how the calibrator is fitted when cv is not 'prefit'. Ignored if cv='prefit'.
If True, the base_estimator is fitted using training data and calibrated using testing data, for each cv fold. The final estimator is an ensemble of n_cv fitted classifer and calibrator pairs, where n_cv is the number of cross-validation folds. The output is the average predicted probabilities of all pairs.
If False, cv is used to compute unbiased predictions, via cross_val_predict, which are then used for calibration. At prediction time, the classifier used is the base_estimator trained on all the data. Note that this method is also internally implemented in sklearn.svm estimators with the probabilities=True parameter.
New in version 0.24.
The class labels.
The list of classifier and calibrator pairs.
Changed in version 0.24: Single calibrated classifier case when ensemble=False.
Obtaining calibrated probability estimates from decision trees and naive Bayesian classifiers, B. Zadrozny & C. Elkan, ICML 2001
Transforming Classifier Scores into Accurate Multiclass Probability Estimates, B. Zadrozny & C. Elkan, (KDD 2002)
Probabilistic Outputs for Support Vector Machines and Comparisons to Regularized Likelihood Methods, J. Platt, (1999)
Predicting Good Probabilities with Supervised Learning, A. Niculescu-Mizil & R. Caruana, ICML 2005
fit(X, y[, sample_weight])
Fit the calibrated model.
get_params([deep])
Get parameters for this estimator.
predict(X)
Predict the target of new samples.
predict_proba(X)
Calibrated probabilities of classification.
score(X, y[, sample_weight])
Return the mean accuracy on the given test data and labels.
set_params(**params)
Set the parameters of this estimator.
Fit the calibrated model.
Training data.
Target values.
Sample weights. If None, then samples are equally weighted.
Returns an instance of self.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict the target of new samples. The predicted class is the class that has the highest probability, and can thus be different from the prediction of the uncalibrated classifier.
The samples.
The predicted class.
Calibrated probabilities of classification.
This function returns calibrated probabilities of classification according to each class on an array of test vectors X.
The samples.
The predicted probas.
Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Probability Calibration curves
Probability calibration of classifiers
Probability Calibration for 3-class classification


Fit the calibrated model.
Training data.
Target values.
Sample weights. If None, then samples are equally weighted.
Returns an instance of self.


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Predict the target of new samples. The predicted class is the class that has the highest probability, and can thus be different from the prediction of the uncalibrated classifier.
The samples.
The predicted class.


Calibrated probabilities of classification.
This function returns calibrated probabilities of classification according to each class on an array of test vectors X.
The samples.
The predicted probas.


Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.


Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.


Compute true and predicted probabilities for a calibration curve.
The method assumes the inputs come from a binary classifier, and discretize the [0, 1] interval into bins.
Calibration curves may also be referred to as reliability diagrams.
Read more in the User Guide.
True targets.
Probabilities of the positive class.
Whether y_prob needs to be normalized into the [0, 1] interval, i.e. is not a proper probability. If True, the smallest value in y_prob is linearly mapped onto 0 and the largest one onto 1.
Number of bins to discretize the [0, 1] interval. A bigger number requires more data. Bins with no samples (i.e. without corresponding values in y_prob) will not be returned, thus the returned arrays may have less than n_bins values.
Strategy used to define the widths of the bins.
The bins have identical widths.
The bins have the same number of samples and depend on y_prob.
The proportion of samples whose class is the positive class, in each bin (fraction of positives).
The mean predicted probability in each bin.
Alexandru Niculescu-Mizil and Rich Caruana (2005) Predicting Good Probabilities With Supervised Learning, in Proceedings of the 22nd International Conference on Machine Learning (ICML). See section 4 (Qualitative Analysis of Predictions).


Perform Affinity Propagation Clustering of data.
Read more in the User Guide.
Damping factor (between 0.5 and 1) is the extent to which the current value is maintained relative to incoming values (weighted 1 - damping). This in order to avoid numerical oscillations when updating these values (messages).
Maximum number of iterations.
Number of iterations with no change in the number of estimated clusters that stops the convergence.
Make a copy of input data.
Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, ie of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities.
Which affinity to use. At the moment ‘precomputed’ and euclidean are supported. ‘euclidean’ uses the negative squared euclidean distance between points.
Whether to be verbose.
Pseudo-random number generator to control the starting state. Use an int for reproducible results across function calls. See the Glossary.
New in version 0.23: this parameter was previously hardcoded as 0.
Indices of cluster centers.
Cluster centers (if affinity != precomputed).
Labels of each point.
Stores the affinity matrix used in fit.
Number of iterations taken to converge.
For an example, see examples/cluster/plot_affinity_propagation.py.
The algorithmic complexity of affinity propagation is quadratic in the number of points.
When fit does not converge, cluster_centers_ becomes an empty array and all training samples will be labelled as -1. In addition, predict will then label every sample as -1.
When all training samples have equal similarities and equal preferences, the assignment of cluster centers and labels depends on the preference. If the preference is smaller than the similarities, fit will result in a single cluster center and label 0 for every sample. Otherwise, every training sample becomes its own cluster center and is assigned a unique label.
Brendan J. Frey and Delbert Dueck, “Clustering by Passing Messages Between Data Points”, Science Feb. 2007
fit(X[, y])
Fit the clustering from features, or affinity matrix.
fit_predict(X[, y])
Fit the clustering from features or affinity matrix, and return cluster labels.
get_params([deep])
Get parameters for this estimator.
predict(X)
Predict the closest cluster each sample in X belongs to.
set_params(**params)
Set the parameters of this estimator.
Fit the clustering from features, or affinity matrix.
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
Not used, present here for API consistency by convention.
Fit the clustering from features or affinity matrix, and return cluster labels.
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
Not used, present here for API consistency by convention.
Cluster labels.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict the closest cluster each sample in X belongs to.
New data to predict. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.
Cluster labels.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.


Perform Affinity Propagation Clustering of data.
Read more in the User Guide.
Damping factor (between 0.5 and 1) is the extent to which the current value is maintained relative to incoming values (weighted 1 - damping). This in order to avoid numerical oscillations when updating these values (messages).
Maximum number of iterations.
Number of iterations with no change in the number of estimated clusters that stops the convergence.
Make a copy of input data.
Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, ie of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities.
Which affinity to use. At the moment ‘precomputed’ and euclidean are supported. ‘euclidean’ uses the negative squared euclidean distance between points.
Whether to be verbose.
Pseudo-random number generator to control the starting state. Use an int for reproducible results across function calls. See the Glossary.
New in version 0.23: this parameter was previously hardcoded as 0.
Indices of cluster centers.
Cluster centers (if affinity != precomputed).
Labels of each point.
Stores the affinity matrix used in fit.
Number of iterations taken to converge.
For an example, see examples/cluster/plot_affinity_propagation.py.
The algorithmic complexity of affinity propagation is quadratic in the number of points.
When fit does not converge, cluster_centers_ becomes an empty array and all training samples will be labelled as -1. In addition, predict will then label every sample as -1.
When all training samples have equal similarities and equal preferences, the assignment of cluster centers and labels depends on the preference. If the preference is smaller than the similarities, fit will result in a single cluster center and label 0 for every sample. Otherwise, every training sample becomes its own cluster center and is assigned a unique label.
Brendan J. Frey and Delbert Dueck, “Clustering by Passing Messages Between Data Points”, Science Feb. 2007
fit(X[, y])
Fit the clustering from features, or affinity matrix.
fit_predict(X[, y])
Fit the clustering from features or affinity matrix, and return cluster labels.
get_params([deep])
Get parameters for this estimator.
predict(X)
Predict the closest cluster each sample in X belongs to.
set_params(**params)
Set the parameters of this estimator.
Fit the clustering from features, or affinity matrix.
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
Not used, present here for API consistency by convention.
Fit the clustering from features or affinity matrix, and return cluster labels.
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
Not used, present here for API consistency by convention.
Cluster labels.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict the closest cluster each sample in X belongs to.
New data to predict. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.
Cluster labels.
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.
Estimator parameters.
Estimator instance.
Demo of affinity propagation clustering algorithm
Comparing different clustering algorithms on toy datasets


Fit the clustering from features, or affinity matrix.
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
Not used, present here for API consistency by convention.


Fit the clustering from features or affinity matrix, and return cluster labels.
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
Not used, present here for API consistency by convention.
Cluster labels.


Predict the closest cluster each sample in X belongs to.
New data to predict. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.
Cluster labels.


Perform Affinity Propagation Clustering of data.
Read more in the User Guide.
Matrix of similarities between points.
Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, i.e. of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities (resulting in a moderate number of clusters). For a smaller amount of clusters, this can be set to the minimum value of the similarities.
Number of iterations with no change in the number of estimated clusters that stops the convergence.
Maximum number of iterations
Damping factor between 0.5 and 1.
If copy is False, the affinity matrix is modified inplace by the algorithm, for memory efficiency.
The verbosity level.
Whether or not to return the number of iterations.
Pseudo-random number generator to control the starting state. Use an int for reproducible results across function calls. See the Glossary.
New in version 0.23: this parameter was previously hardcoded as 0.
Index of clusters centers.
Cluster labels for each point.
Number of iterations run. Returned only if return_n_iter is set to True.
For an example, see examples/cluster/plot_affinity_propagation.py.
When the algorithm does not converge, it returns an empty array as cluster_center_indices and -1 as label for each training sample.
When all training samples have equal similarities and equal preferences, the assignment of cluster centers and labels depends on the preference. If the preference is smaller than the similarities, a single cluster center and label 0 for every sample will be returned. Otherwise, every training sample becomes its own cluster center and is assigned a unique label.
Brendan J. Frey and Delbert Dueck, “Clustering by Passing Messages Between Data Points”, Science Feb. 2007