@@ -356,9 +358,10 @@ for user in User.objects.all():
...
@@ -356,9 +358,10 @@ for user in User.objects.all():
Token.objects.get_or_create(user=user)
Token.objects.get_or_create(user=user)
</code></pre>
</code></pre>
<p>When using <code>TokenAuthentication</code>, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the <code>obtain_auth_token</code> view to your URLconf:</p>
<p>When using <code>TokenAuthentication</code>, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the <code>obtain_auth_token</code> view to your URLconf:</p>
<p>Note that the URL part of the pattern can be whatever you want to use.</p>
<p>Note that the URL part of the pattern can be whatever you want to use.</p>
<p>The <code>obtain_auth_token</code> view will return a JSON response when valid <code>username</code> and <code>password</code> fields are POSTed to the view using form data or JSON:</p>
<p>The <code>obtain_auth_token</code> view will return a JSON response when valid <code>username</code> and <code>password</code> fields are POSTed to the view using form data or JSON:</p>
...
@@ -508,6 +511,8 @@ class ExampleAuthentication(authentication.BaseAuthentication):
...
@@ -508,6 +511,8 @@ class ExampleAuthentication(authentication.BaseAuthentication):
<p>The <ahref="http://hawkrest.readthedocs.org/en/latest/">HawkREST</a> library builds on the <ahref="http://mohawk.readthedocs.org/en/latest/">Mohawk</a> library to let you work with <ahref="https://github.com/hueniverse/hawk">Hawk</a> signed requests and responses in your API. <ahref="https://github.com/hueniverse/hawk">Hawk</a> lets two parties securely communicate with each other using messages signed by a shared key. It is based on <ahref="http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05">HTTP MAC access authentication</a> (which was based on parts of <ahref="http://oauth.net/core/1.0a">OAuth 1.0</a>).</p>
<p>The <ahref="http://hawkrest.readthedocs.org/en/latest/">HawkREST</a> library builds on the <ahref="http://mohawk.readthedocs.org/en/latest/">Mohawk</a> library to let you work with <ahref="https://github.com/hueniverse/hawk">Hawk</a> signed requests and responses in your API. <ahref="https://github.com/hueniverse/hawk">Hawk</a> lets two parties securely communicate with each other using messages signed by a shared key. It is based on <ahref="http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05">HTTP MAC access authentication</a> (which was based on parts of <ahref="http://oauth.net/core/1.0a">OAuth 1.0</a>).</p>
<p>HTTP Signature (currently a <ahref="https://datatracker.ietf.org/doc/draft-cavage-http-signatures/">IETF draft</a>) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to <ahref="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Amazon's HTTP Signature scheme</a>, used by many of its services, it permits stateless, per-request authentication. <ahref="https://github.com/etoccalino/">Elvio Toccalino</a> maintains the <ahref="https://github.com/etoccalino/django-rest-framework-httpsignature">djangorestframework-httpsignature</a> package which provides an easy to use HTTP Signature Authentication mechanism.</p>
<p>HTTP Signature (currently a <ahref="https://datatracker.ietf.org/doc/draft-cavage-http-signatures/">IETF draft</a>) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to <ahref="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Amazon's HTTP Signature scheme</a>, used by many of its services, it permits stateless, per-request authentication. <ahref="https://github.com/etoccalino/">Elvio Toccalino</a> maintains the <ahref="https://github.com/etoccalino/django-rest-framework-httpsignature">djangorestframework-httpsignature</a> package which provides an easy to use HTTP Signature Authentication mechanism.</p>
<h2id="djoser">Djoser</h2>
<p><ahref="https://github.com/sunscrapers/djoser">Djoser</a> library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.</p>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/3-class-based-views.html">3 - Class based views</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
<p>[The <code>OPTIONS</code>] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.</p>
<p>REST framework includes a configurable mechanism for determining how your API should respond to <code>OPTIONS</code> requests. This allows you to return API schema or other resource information.</p>
<p>There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP <code>OPTIONS</code> requests, so we provide an ad-hoc style that returns some useful information.</p>
<p>Here's an example response that demonstrates the information that is returned by default.</p>
<preclass="prettyprint lang-py"><code>HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
{
"name": "To Do List",
"description": "List existing 'To Do' items, or create a new item.",
"renders": [
"application/json",
"text/html"
],
"parses": [
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
],
"actions": {
"POST": {
"note": {
"type": "string",
"required": false,
"read_only": false,
"label": "title",
"max_length": 100
}
}
}
}
</code></pre>
<h2id="setting-the-metadata-scheme">Setting the metadata scheme</h2>
<p>You can set the metadata class globally using the <code>'DEFAULT_METADATA_CLASS'</code> settings key:</p>
<p>The REST framework package only includes a single metadata class implementation, named <code>SimpleMetadata</code>. If you want to use an alternative style you'll need to implement a custom metadata class.</p>
<p>If you have specific requirements for creating schema endpoints that are accessed with regular <code>GET</code> requests, you might consider re-using the metadata API for doing so.</p>
<p>For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.</p>
<p>There are a couple of reasons that you might choose to take this approach, including that <code>OPTIONS</code> responses <ahref="https://www.mnot.net/blog/2012/10/29/NO_OPTIONS">are not cacheable</a>.</p>
<p>If you want to provide a custom metadata class you should override <code>BaseMetadata</code> and implement the <code>determine_metadata(self, request, view)</code> method.</p>
<p>Useful things that you might want to do could include returning schema information, using a format such as <ahref="http://json-schema.org/">JSON schema</a>, or returning debug information to admin users.</p>
<h2id="example">Example</h2>
<p>The following class could be used to limit the information that is returned to <code>OPTIONS</code> requests.</p>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/3-class-based-views.html">3 - Class based views</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
<p>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.</p>
<p>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.</p>
<h2id="validation-in-rest-framework">Validation in REST framework</h2>
<p>Validation in Django REST framework serializers is handled a little differently to how validation works in Django's <code>ModelForm</code> class.</p>
<p>With <code>ModelForm</code> 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:</p>
<ul>
<li>It introduces a proper separation of concerns, making your code behaviour more obvious.</li>
<li>It is easy to switch between using shortcut <code>ModelSerializer</code> classes and using explicit <code>Serializer</code> classes. Any validation behaviour being used for <code>ModelSerializer</code> is simple to replicate.</li>
<li>Printing the <code>repr</code> of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behaviour being called on the model instance.</li>
</ul>
<p>When you're using <code>ModelSerializer</code> all of this is handled automatically for you. If you want to drop down to using a <code>Serializer</code> classes instead, then you need to define the validation rules explicitly.</p>
<h4id="example">Example</h4>
<p>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.</p>
<p>The interesting bit here is the <code>reference</code> field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.</p>
<p>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.</p>
<hr/>
<h2id="uniquevalidator">UniqueValidator</h2>
<p>This validator can be used to enforce the <code>unique=True</code> constraint on model fields.
It takes a single required argument, and an optional <code>messages</code> argument:</p>
<ul>
<li><code>queryset</code><em>required</em> - This is the queryset against which uniqueness should be enforced.</li>
<li><code>message</code> - The error message that should be used when validation fails.</li>
</ul>
<p>This validator should be applied to <em>serializer fields</em>, like so:</p>
<p>This validator can be used to enforce <code>unique_together</code> constraints on model instances.
It has two required arguments, and a single optional <code>messages</code> argument:</p>
<ul>
<li><code>queryset</code><em>required</em> - This is the queryset against which uniqueness should be enforced.</li>
<li><code>fields</code><em>required</em> - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.</li>
<li><code>message</code> - The error message that should be used when validation fails.</li>
</ul>
<p>The validator should be applied to <em>serializer classes</em>, like so:</p>
<p>These validators can be used to enforce the <code>unique_for_date</code>, <code>unique_for_month</code> and <code>unique_for_year</code> constraints on model instances. They take the following arguments:</p>
<ul>
<li><code>queryset</code><em>required</em> - This is the queryset against which uniqueness should be enforced.</li>
<li><code>field</code><em>required</em> - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.</li>
<li><code>date_field</code><em>required</em> - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.</li>
<li><code>message</code> - The error message that should be used when validation fails.</li>
</ul>
<p>The validator should be applied to <em>serializer classes</em>, like so:</p>
# Blog posts should have a slug that is unique for the current year.
validators = [
UniqueForYearValidator(
queryset=BlogPostItem.objects.all(),
field='slug',
date_field='published'
)
]
</code></pre>
<p>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 <code>default=...</code>, because the value being used for the default wouldn't be generated until after the validation has run.</p>
<p>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 <code>ModelSerializer</code> you'll probably simply rely on the defaults that REST framework generates for you, but if you are using <code>Serializer</code> or simply want more explicit control, use on of the styles demonstrated below.</p>
<h4id="using-with-a-writable-date-field">Using with a writable date field.</h4>
<p>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 <code>default</code> argument, or by setting <code>required=True</code>.</p>
<h4id="using-with-a-read-only-date-field">Using with a read-only date field.</h4>
<p>If you want the date field to be visible, but not editable by the user, then set <code>read_only=True</code> and additionally set a <code>default=...</code> argument.</p>
<p>The field will not be writable to the user, but the default value will still be passed through to the <code>validated_data</code>.</p>
<h4id="using-with-a-hidden-date-field">Using with a hidden date field.</h4>
<p>If you want the date field to be entirely hidden from the user, then use <code>HiddenField</code>. This field type does not accept user input, but instead always returns it's default value to the <code>validated_data</code> in the serializer.</p>
raise serializers.ValidationError('This field must be an even number.')
</code></pre>
<h2id="class-based">Class based</h2>
<p>To write a class based validator, use the <code>__call__</code> method. Class based validators are useful as they allow you to parameterize and reuse behavior.</p>
<p>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 declaring a <code>set_context</code> method on a class based validator.</p>
@@ -283,10 +283,10 @@ pip install django-filter # Filtering support
...
@@ -283,10 +283,10 @@ pip install django-filter # Filtering support
)
)
</code></pre>
</code></pre>
<p>If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root <code>urls.py</code> file.</p>
<p>If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root <code>urls.py</code> file.</p>
<p>Note that the URL path can be whatever you want, but you must include <code>'rest_framework.urls'</code> with the <code>'rest_framework'</code> namespace.</p>
<p>Note that the URL path can be whatever you want, but you must include <code>'rest_framework.urls'</code> with the <code>'rest_framework'</code> namespace.</p>
<p>The best place to get started with ViewSets and Routers is to take a look at the <ahref="../tutorial/6-viewsets-and-routers">newest section in the tutorial</a>, which demonstrates their usage.</p>
<p>The best place to get started with ViewSets and Routers is to take a look at the <ahref="../tutorial/6-viewsets-and-routers">newest section in the tutorial</a>, which demonstrates their usage.</p>
@@ -295,8 +295,8 @@ The lowest supported version of Django is now 1.4.2.</p>
...
@@ -295,8 +295,8 @@ The lowest supported version of Django is now 1.4.2.</p>
</ul>
</ul>
<h2id="other-features">Other features</h2>
<h2id="other-features">Other features</h2>
<p>There are also a number of other features and bugfixes as <ahref="release-notes#240">listed in the release notes</a>. In particular these include:</p>
<p>There are also a number of other features and bugfixes as <ahref="release-notes#240">listed in the release notes</a>. In particular these include:</p>
<p><ahref="../api-guide/settings/#view-names-and-descriptions">Customizable view name and description functions</a> for use with the browsable API, by using the <code>VIEW_NAME_FUNCTION</code> and <code>VIEW_DESCRIPTION_FUNCTION</code> settings.</p>
<p><ahref="../api-guide/settings#view-names-and-descriptions">Customizable view name and description functions</a> for use with the browsable API, by using the <code>VIEW_NAME_FUNCTION</code> and <code>VIEW_DESCRIPTION_FUNCTION</code> settings.</p>
<p>Smarter <ahref="../api-guide/throttling/#how-clients-are-identified">client IP identification for throttling</a>, with the addition of the <code>NUM_PROXIES</code> setting.</p>
<p>Smarter <ahref="../api-guide/throttling#how-clients-are-identified">client IP identification for throttling</a>, with the addition of the <code>NUM_PROXIES</code> setting.</p>
<p>Added the standardized <code>Retry-After</code> header to throttled responses, as per <ahref="http://tools.ietf.org/html/rfc6585">RFC 6585</a>. This should now be used in preference to the custom <code>X-Throttle-Wait-Seconds</code> header which will be fully deprecated in 3.0.</p>
<p>Added the standardized <code>Retry-After</code> header to throttled responses, as per <ahref="http://tools.ietf.org/html/rfc6585">RFC 6585</a>. This should now be used in preference to the custom <code>X-Throttle-Wait-Seconds</code> header which will be fully deprecated in 3.0.</p>
<h2id="deprecations">Deprecations</h2>
<h2id="deprecations">Deprecations</h2>
<p>All API changes in 2.3 that previously raised <code>PendingDeprecationWarning</code> will now raise a <code>DeprecationWarning</code>, which is loud by default.</p>
<p>All API changes in 2.3 that previously raised <code>PendingDeprecationWarning</code> will now raise a <code>DeprecationWarning</code>, which is loud by default.</p>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/3-class-based-views.html">3 - Class based views</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
<li><ahref="file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
<p>The 3.0 release is now ready for some tentative testing and upgrades for super keen early adopters. You can install the development version directly from GitHub like so:</p>
<p>See the <ahref="https://github.com/tomchristie/django-rest-framework/pull/1800">Version 3.0 GitHub issue</a> for more details on remaining work.</p>
<p>The most notable outstanding issues still to be resolved on the <code>version-3.0</code> branch are as follows:</p>
<ul>
<li>Finish forms support for serializers and in the browsable API.</li>
<li>Optimisations for serializing primary keys.</li>
<li>Refine style of validation errors in some cases, such as validation errors in <code>ListField</code>.</li>
</ul>
<p><strong>Your feedback on the upgrade process and 3.0 changes is hugely important!</strong></p>
<p>Please do get in touch via twitter, IRC, a GitHub ticket, or the discussion group.</p>
<hr/>
<h1id="rest-framework-30">REST framework 3.0</h1>
<p>The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.</p>
<p>This release is incremental in nature. There <em>are</em> some breaking API changes, and upgrading <em>will</em> require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.</p>
<p>The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.</p>
<h2id="new-features">New features</h2>
<p>Notable features of this new release include:</p>
<ul>
<li>Printable representations on serializers that allow you to inspect exactly what fields are present on the instance.</li>
<li>Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit <code>ModelSerializer</code> class and the explicit <code>Serializer</code> class.</li>
<li>A new <code>BaseSerializer</code> class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.</li>
<li>A cleaner fields API plus new <code>ListField</code> and <code>MultipleChoiceField</code> classes.</li>
<li>Super simple default implementations for the generic views.</li>
<li>Support for overriding how validation errors are handled by your API.</li>
<li>A metadata API that allows you to customize how <code>OPTIONS</code> requests are handled by your API.</li>
<li>A more compact JSON output with unicode style encoding turned on by default.</li>
</ul>
<p>Below is an in-depth guide to the API changes and migration notes for 3.0.</p>
<hr/>
<h2id="request-objects">Request objects</h2>
<h4id="the-data-and-query_params-properties">The <code>.data</code> and <code>.query_params</code> properties.</h4>
<p>The usage of <code>request.DATA</code> and <code>request.FILES</code> is now pending deprecation in favor of a single <code>request.data</code> attribute that contains <em>all</em> the parsed data.</p>
<p>Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports.</p>
<p>You may now pass all the request data to a serializer class in a single argument:</p>
<preclass="prettyprint lang-py"><code># Do this...
ExampleSerializer(data=request.data)
</code></pre>
<p>Instead of passing the files argument separately:</p>
<preclass="prettyprint lang-py"><code># Don't do this...
<p>Previously the serializers used a two-step object creation, as follows:</p>
<ol>
<li>Validating the data would create an object instance. This instance would be available as <code>serializer.object</code>.</li>
<li>Calling <code>serializer.save()</code> would then save the object instance to the database.</li>
</ol>
<p>This style is in-line with how the <code>ModelForm</code> class works in Django, but is problematic for a number of reasons:</p>
<ul>
<li>Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when <code>.save()</code> is called.</li>
<li>Instantiating model instances directly means that you cannot use model manager classes for instance creation, eg <code>ExampleModel.objects.create(...)</code>. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.</li>
<li>The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save?</li>
</ul>
<p>We now use single-step object creation, like so:</p>
<ol>
<li>Validating the data makes the cleaned data available as <code>serializer.validated_data</code>.</li>
<li>Calling <code>serializer.save()</code> then saves and returns the new object instance.</li>
</ol>
<p>The resulting API changes are further detailed below.</p>
<h4id="the-create-and-update-methods">The <code>.create()</code> and <code>.update()</code> methods.</h4>
<p>The <code>.restore_object()</code> method is now replaced with two separate methods, <code>.create()</code> and <code>.update()</code>.</p>
<p>When using the <code>.create()</code> and <code>.update()</code> methods you should both create <em>and save</em> the object instance. This is in contrast to the previous <code>.restore_object()</code> behavior that would instantiate the object but not save it.</p>
<p>The following example from the tutorial previously used <code>restore_object()</code> to handle both creating and updating object instances.</p>
<p>Note that these methods should return the newly created object instance.</p>
<h4id="use-validated_data-instead-of-object">Use <code>.validated_data</code> instead of <code>.object</code>.</h4>
<p>You must now use the <code>.validated_data</code> attribute if you need to inspect the data before saving, rather than using the <code>.object</code> attribute, which no longer exists.</p>
<p>For example the following code <em>is no longer valid</em>:</p>
name = serializer.object.name # Inspect validated field data.
logging.info('Creating ticket "%s"' % name)
serializer.object.user = request.user # Include the user when saving.
serializer.save()
</code></pre>
<p>Instead of using <code>.object</code> to inspect a partially constructed instance, you would now use <code>.validated_data</code> to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the <code>.save()</code> method as keyword arguments.</p>
<p>The corresponding code would now look like this:</p>
<p>Previously <code>serializers.ValidationError</code> error was simply a synonym for <code>django.core.exceptions.ValidationError</code>. This has now been altered so that it inherits from the standard <code>APIException</code> base class.</p>
<p>The reason behind this is that Django's <code>ValidationError</code> class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers.</p>
<p>For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you are always using the <code>serializers.ValidationError</code> exception class, and not Django's built-in exception.</p>
<p>We strongly recommend that you use the namespaced import style of <code>import serializers</code> and not <code>from serializers import ValidationError</code> in order to avoid any potential confusion.</p>
<h4id="change-to-validate_field_name">Change to <code>validate_<field_name></code>.</h4>
<p>The <code>validate_<field_name></code> method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field:</p>
raise serializers.ValidationError('This field should be a multiple of ten.')
return value
</code></pre>
<p>Any ad-hoc validation that applies to more than one field should go in the <code>.validate(self, attrs)</code> method as usual.</p>
<p>Because <code>.validate_<field_name></code> would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use <code>.validate()</code> instead.</p>
<p>You can either return <code>non_field_errors</code> from the validate method by raising a simple <code>ValidationError</code></p>
# serializer.errors == {'non_field_errors': ['A non field error']}
raise serailizers.ValidationError('A non field error')
</code></pre>
<p>Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the <code>ValidationError</code>, like so:</p>
# serializer.errors == {'my_field': ['A field error']}
raise serailizers.ValidationError({'my_field': 'A field error'})
</code></pre>
<p>This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.</p>
<h4id="limitations-of-modelserializer-validation">Limitations of ModelSerializer validation.</h4>
<p>This change also means that we no longer use the <code>.full_clean()</code> method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on <code>ModelSerializer</code> classes that can't also be easily replicated on regular <code>Serializer</code> classes.</p>
<p>This change comes with the following limitations:</p>
<ul>
<li>The model <code>.clean()</code> method will not be called as part of serializer validation. Use the serializer <code>.validate()</code> method to perform a final validation step on incoming data where required.</li>
<li>The <code>.unique_for_date</code>, <code>.unique_for_month</code> and <code>.unique_for_year</code> options on model fields are not automatically validated. Again, you'll need to handle these explicitly on the serializer if required.</li>
<p>REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic:</p>
<ul>
<li>There can be complex dependencies involved in order of saving multiple related model instances.</li>
<li>It's unclear what behavior the user should expect when related models are passed <code>None</code> data.</li>
<li>It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.</li>
</ul>
<p>Using the <code>depth</code> option on <code>ModelSerializer</code> will now create <strong>read-only nested serializers</strong> by default.</p>
<p>If you try to use a writable nested serializer without writing a custom <code>create()</code> and/or <code>update()</code> method you'll see an assertion error when you attempt to save the serializer. For example:</p>
<preclass="prettyprint lang-py"><code>>>> class ProfileSerializer(serializers.ModelSerializer):
>>> class Meta:
>>> model = Profile
>>> fields = ('address', 'phone')
>>>
>>> class UserSerializer(serializers.ModelSerializer):
AssertionError: The `.create()` method does not suport nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.
</code></pre>
<p>To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the <code>create()</code> and/or <code>update()</code> methods explicitly.</p>
<p>The <code>write_only_fields</code> option on <code>ModelSerializer</code> has been moved to <code>PendingDeprecation</code> and replaced with a more generic <code>extra_kwargs</code>.</p>
<p>The <code>read_only_fields</code> option remains as a convenient shortcut for the more common case. </p>
<h4id="changes-to-hyperlinkedmodelserializer">Changes to <code>HyperlinkedModelSerializer</code>.</h4>
<p>The <code>view_name</code> and <code>lookup_field</code> options have been moved to <code>PendingDeprecation</code>. They are no longer required, as you can use the <code>extra_kwargs</code> argument instead:</p>
<h4id="fields-for-model-methods-and-properties">Fields for model methods and properties.</h4>
<p>With <code>ModelSerilizer</code> you can now specify field names in the <code>fields</code> option that refer to model methods or properties. For example, suppose you have the following model:</p>
<p>You can also still use the <code>many=True</code> argument to serializer classes. It's worth noting that <code>many=True</code> argument transparently creates a <code>ListSerializer</code> instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. </p>
<p>See also the new <code>ListField</code> class, which validates input in the same way, but does not include the serializer interfaces of <code>.is_valid()</code>, <code>.data</code>, <code>.save()</code> and so on.</p>
<p>REST framework now includes a simple <code>BaseSerializer</code> class that can be used to easily support alternative serialization and deserialization styles.</p>
<p>This class implements the same basic API as the <code>Serializer</code> class:</p>
<ul>
<li><code>.data</code> - Returns the outgoing primitive representation.</li>
<li><code>.is_valid()</code> - Deserializes and validates incoming data.</li>
<li><code>.validated_data</code> - Returns the validated incoming data.</li>
<li><code>.errors</code> - Returns an errors during validation.</li>
<li><code>.save()</code> - Persists the validated data into an object instance.</li>
</ul>
<p>There are four mathods that can be overriding, depending on what functionality you want the serializer class to support:</p>
<ul>
<li><code>.to_representation()</code> - Override this to support serialization, for read operations.</li>
<li><code>.to_internal_value()</code> - Override this to support deserialization, for write operations.</li>
<li><code>.create()</code> and <code>.update()</code> - Overide either or both of these to support saving instances.</li>
<p>To implement a read-only serializer using the <code>BaseSerializer</code> class, we just need to override the <code>.to_representation()</code> method. Let's take a look at an example using a simple Django model:</p>
<p>To create a read-write serializer we first need to implement a <code>.to_internal_value()</code> method. This method returns the validated values that will be used to construct the object instance, and may raise a <code>ValidationError</code> if the supplied data is in an incorrect format.</p>
<p>Once you've implemented <code>.to_internal_value()</code>, the basic validation API will be available on the serializer, and you will be able to use <code>.is_valid()</code>, <code>.validated_data</code> and <code>.errors</code>.</p>
<p>If you want to also support <code>.save()</code> you'll need to also implement either or both of the <code>.create()</code> and <code>.update()</code> methods.</p>
<p>Here's a complete example of our previous <code>HighScoreSerializer</code>, that's been updated to support both read and write operations.</p>
'player_name': 'May not be more than 10 characters.'
})
# Return the validated values. This will be available as
# the `.validated_data` property.
return {
'score': int(score),
'player_name': player_name
}
def to_representation(self, obj):
return {
'score': obj.score,
'player_name': obj.player_name
}
def create(self, validated_data):
return HighScore.objects.create(**validated_data)
</code></pre>
<h4id="creating-new-generic-serializers-with-baseserializer">Creating new generic serializers with <code>BaseSerializer</code>.</h4>
<p>The <code>BaseSerializer</code> class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.</p>
<p>The following class is an example of a generic serializer that can handle coercing aribitrary objects into primitive representations. </p>
# Primitive types can be passed through unmodified.
output[attribute_name] = attribute
elif isinstance(attribute, list):
# Recursivly deal with items in lists.
output[attribute_name] = [
self.to_representation(item) for item in attribute
]
elif isinstance(attribute, dict):
# Recursivly deal with items in dictionarys.
output[attribute_name] = {
str(key): self.to_representation(value)
for key, value in attribute.items()
}
else:
# Force anything else to its string representation.
output[attribute_name] = str(attribute)
</code></pre>
<h2id="serializer-fields">Serializer fields</h2>
<h4id="the-field-and-readonly-field-classes">The <code>Field</code> and <code>ReadOnly</code> field classes.</h4>
<p>There are some minor tweaks to the field base classes.</p>
<p>Previously we had these two base classes:</p>
<ul>
<li><code>Field</code> as the base class for read-only fields. A default implementation was included for serializing data.</li>
<li><code>WritableField</code> as the base class for read-write fields.</li>
</ul>
<p>We now use the following:</p>
<ul>
<li><code>Field</code> is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.</li>
<li><code>ReadOnlyField</code> is a concrete implementation for read-only fields that simply returns the attribute value without modification.</li>
</ul>
<h4id="the-required-allow_none-allow_blank-and-default-arguments">The <code>required</code>, <code>allow_none</code>, <code>allow_blank</code> and <code>default</code> arguments.</h4>
<p>REST framework now has more explicit and clear control over validating empty values for fields.</p>
<p>Previously the meaning of the <code>required=False</code> keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be <code>None</code>.</p>
<p>We now have a better separation, with separate <code>required</code> and <code>allow_none</code> arguments.</p>
<p>The following set of arguments are used to control validation of empty values:</p>
<ul>
<li><code>required=False</code>: The value does not need to be present in the input, and will not be passed to <code>.create()</code> or <code>.update()</code> if it is not seen.</li>
<li><code>default=<value></code>: The value does not need to be present in the input, and a default value will be passed to <code>.create()</code> or <code>.update()</code> if it is not seen.</li>
<li><code>allow_none=True</code>: <code>None</code> is a valid input.</li>
<li><code>allow_blank=True</code>: <code>''</code> is valid input. For <code>CharField</code> and subclasses only.</li>
</ul>
<p>Typically you'll want to use <code>required=False</code> if the corresponding model field has a default value, and additionally set either <code>allow_none=True</code> or <code>allow_blank=True</code> if required.</p>
<p>The <code>default</code> argument is there if you need it, but you'll more typically want defaults to be set on model fields, rather than serializer fields.</p>
<p>The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an <code>IntegerField</code> would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior. </p>
<p>The <code>ListField</code> class has now been added. This field validates list input. It takes a <code>child</code> keyword argument which is used to specify the field used to validate each item in the list. For example:</p>
<p>See also the new <code>ListSerializer</code> class, which validates input in the same way, but also includes the serializer interfaces of <code>.is_valid()</code>, <code>.data</code>, <code>.save()</code> and so on.</p>
<h4id="the-choicefield-class-may-now-accept-a-flat-list">The <code>ChoiceField</code> class may now accept a flat list.</h4>
<p>The <code>ChoiceField</code> class may now accept a list of choices in addition to the existing style of using a list of pairs of <code>(name, display_value)</code>. The following is now valid:</p>
<p>The <code>MultipleChoiceField</code> class has been added. This field acts like <code>ChoiceField</code>, but returns a set, which may include none, one or many of the valid choices.</p>
<h4id="changes-to-the-custom-field-api">Changes to the custom field API.</h4>
<p>The <code>from_native(self, value)</code> and <code>to_native(self, data)</code> method names have been replaced with the more obviously named <code>to_internal_value(self, data)</code> and <code>to_representation(self, value)</code>.</p>
<p>The <code>field_from_native()</code> and <code>field_to_native()</code> methods are removed.</p>
<h4id="explicit-queryset-required-on-relational-fields">Explicit <code>queryset</code> required on relational fields.</h4>
<p>Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a <code>ModelSerializer</code>.</p>
<p>This code <em>would be valid</em> in <code>2.4.3</code>:</p>
<p>The queryset argument is now always required for writable relational fields.
This removes some magic and makes it easier and more obvious to move between implicit <code>ModelSerializer</code> classes and explicit <code>Serializer</code> classes.</p>
<p>The <code>queryset</code> argument is only ever required for writable fields, and is not required or valid for fields with <code>read_only=True</code>.</p>
<h4id="optional-argument-to-serializermethodfield">Optional argument to <code>SerializerMethodField</code>.</h4>
<p>The argument to <code>SerializerMethodField</code> is now optional, and defaults to <code>get_<field_name></code>. For example the following is valid:</p>
<p>In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code <em>will raise an error</em>:</p>
<p>I've see several codebases that unnecessarily include the <code>source</code> argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that <code>source</code> is usually not required.</p>
<p>The following usage will <em>now raise an error</em>:</p>
<h4id="the-uniquevalidator-and-uniquetogethervalidator-classes">The <code>UniqueValidator</code> and <code>UniqueTogetherValidator</code> classes.</h4>
<p>REST framework now provides two new validators that allow you to ensure field uniqueness, while still using a completely explicit <code>Serializer</code> class instead of using <code>ModelSerializer</code>.</p>
<p>The <code>UniqueValidator</code> should be applied to a serializer field, and takes a single <code>queryset</code> argument.</p>
<p>The <code>UniqueTogetherValidator</code> should be applied to a serializer, and takes a <code>queryset</code> argument and a <code>fields</code> argument which should be a list or tuple of field names.</p>
<h4id="simplification-of-view-logic">Simplification of view logic.</h4>
<p>The view logic for the default method handlers has been significantly simplified, due to the new serializers API.</p>
<h4id="changes-to-prepost-save-hooks">Changes to pre/post save hooks.</h4>
<p>The <code>pre_save</code> and <code>post_save</code> hooks no longer exist, but are replaced with <code>perform_create(self, serializer)</code> and <code>perform_update(self, serializer)</code>.</p>
<p>These methods should save the object instance by calling <code>serializer.save()</code>, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.</p>
<p>The <code>pre_delete</code> and <code>post_delete</code> hooks no longer exist, and are replaced with <code>.perform_destroy(self, instance)</code>, which should delete the instance and perform any custom actions.</p>
<h4id="removal-of-view-attributes">Removal of view attributes.</h4>
<p>The <code>.object</code> and <code>.object_list</code> attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic.</p>
<p>I would personally recommend that developers treat view instances as immutable objects in their application code.</p>
<h4id="put-as-create">PUT as create.</h4>
<p>Allowing <code>PUT</code> as create operations is problematic, as it necessarily exposes information about the existence or non-existance 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 <code>404</code> responses.</p>
<p>Both styles "<code>PUT</code> as 404" and "<code>PUT</code> as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.</p>
<p>If you need to restore the previous behavior you can include the <code>AllowPUTAsCreateMixin</code> class in your view. This class can be imported from <code>rest_framework.mixins</code>.</p>
<p>The generic views now raise <code>ValidationFailed</code> exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a <code>400 Bad Request</code> response directly.</p>
<p>This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.</p>
<h2id="the-metadata-api">The metadata API</h2>
<p>Behavior for dealing with <code>OPTIONS</code> requests was previously built directly into the class based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.</p>
<p>This makes it far easier to use a different style for <code>OPTIONS</code> responses throughout your API, and makes it possible to create third-party metadata policies.</p>
<h2id="api-style">API style</h2>
<p>There are some improvements in the default style we use in our API responses.</p>
<h4id="unicode-json-by-default">Unicode JSON by default.</h4>
<p>Unicode JSON is now the default. The <code>UnicodeJSONRenderer</code> class no longer exists, and the <code>UNICODE_JSON</code> setting has been added. To revert this behavior use the new setting:</p>
<h4id="file-fields-as-urls">File fields as URLs</h4>
<p>The <code>FileField</code> and <code>ImageField</code> classes are now represented as URLs by default. You should ensure you set Django's <ahref="https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-MEDIA_URL">standard <code>MEDIA_URL</code> setting</a> appropriately, and ensure your application <ahref="https://docs.djangoproject.com/en/dev/howto/static-files/#serving-uploaded-files-in-development">serves the uploaded files</a>.</p>
<p>You can revert this behavior, and display filenames in the representation by using the <code>UPLOADED_FILES_USE_URL</code> settings key:</p>
<p>Also note that you should pass the <code>request</code> object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form <code>https://example.com/url_path/filename.txt</code>. For example:</p>
<p>If the request is omitted from the context, the returned URLs will be of the form <code>/url_path/filename.txt</code>.</p>
<h4id="throttle-headers-using-retry-after">Throttle headers using <code>Retry-After</code>.</h4>
<p>The custom <code>X-Throttle-Wait-Second</code> header has now been dropped in favor of the standard <code>Retry-After</code> header. You can revert this behavior if needed by writing a custom exception handler for your application.</p>
<h4id="date-and-time-objects-as-iso-8859-1-strings-in-serializer-data">Date and time objects as ISO-8859-1 strings in serializer data.</h4>
<p>Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as <code>Date</code>, <code>Time</code> and <code>DateTime</code> objects, and later coerced to strings by the renderer.</p>
<p>You can modify this behavior globally by settings the existing <code>DATE_FORMAT</code>, <code>DATETIME_FORMAT</code> and <code>TIME_FORMAT</code> settings keys. Setting these values to <code>None</code> instead of their default value of <code>'iso-8859-1'</code> will result in native objects being returned in serializer data.</p>
# Return native `Date` and `Time` objects in `serializer.data`
'DATETIME_FORMAT': None
'DATE_FORMAT': None
'TIME_FORMAT': None
}
</code></pre>
<p>You can also modify serializer fields individually, using the <code>date_format</code>, <code>time_format</code> and <code>datetime_format</code> arguments:</p>
<preclass="prettyprint lang-py"><code># Return `DateTime` instances in `serializer.data`, not strings.
created = serializers.DateTimeField(format=None)
</code></pre>
<h4id="decimals-as-strings-in-serializer-data">Decimals as strings in serializer data.</h4>
<p>Decimals are now coerced to strings by default in the serializer output. Previously they were returned as <code>Decimal</code> objects, and later coerced to strings by the renderer.</p>
<p>You can modify this behavior globally by using the <code>COERCE_DECIMAL_TO_STRING</code> settings key.</p>
<p>Or modify it on an individual serializer field, using the <code>corece_to_string</code> keyword argument.</p>
<preclass="prettyprint lang-py"><code># Return `Decimal` instances in `serializer.data`, not strings.
amount = serializers.DecimalField(
max_digits=10,
decimal_places=2,
coerce_to_string=False
)
</code></pre>
<p>The default JSON renderer will return float objects for uncoerced <code>Decimal</code> instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.</p>
<p>3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.</p>
<p>The 3.1 release is planned to address improvements in the following components:</p>
<ul>
<li>Request parsing, mediatypes & the implementation of the browsable API.</li>
<li>Introduction of a new pagination API.</li>
<li>Better support for API versioning.</li>
</ul>
<p>The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.</p>
<p>You can follow development on the GitHub site, where we use <ahref="https://github.com/tomchristie/django-rest-framework/milestones">milestones to indicate planning timescales</a>.</p>
</div><!--/span-->
</div><!--/row-->
</div><!--/.fluid-container-->
</div><!--/.body content-->
<divid="push"></div>
</div><!--/.wrapper -->
<footerclass="span12">
<p>Sponsored by <ahref="http://dabapps.com/">DabApps</a>.</a></p>
<p>If you have some functionality that you would like to implement as a third party package it's worth contacting the <ahref="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">discussion group</a> as others may be willing to get involved. We strongly encourage third party package development and will always try to prioritize time spent helping their development, documentation and packaging.</p>
<p>If you have some functionality that you would like to implement as a third party package it's worth contacting the <ahref="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">discussion group</a> as others may be willing to get involved. We strongly encourage third party package development and will always try to prioritize time spent helping their development, documentation and packaging.</p>
<p>We recommend the <ahref="https://github.com/dabapps/django-reusable-app"><code>django-reusable-app</code></a> template as a good resource for getting up and running with implementing a third party Django package.</p>
<p>We recommend the <ahref="https://github.com/dabapps/django-reusable-app"><code>django-reusable-app</code></a> template as a good resource for getting up and running with implementing a third party Django package.</p>
<h2id="linking-to-your-package">Linking to your package</h2>
<h2id="linking-to-your-package">Linking to your package</h2>
<p>Once your package is decently documented and available on PyPI open a pull request or issue, and we'll add a link to it from the main REST framework documentation.</p>
<p>Once your package is decently documented and available on PyPI open a pull request or issue, and we'll add a link to it from the main REST framework documentation. You can add your package under <strong>Third party packages</strong> of the API Guide section that best applies, like <ahref="../api-guide/authentication">Authentication</a> or <ahref="../api-guide/permissions">Permissions</a>. You can also link your package under the <ahref="third-party-resources">Third Party Resources</a> section.</p>
<p>We also suggest adding it to the <ahref="https://www.djangopackages.com/grids/g/django-rest-framework/">REST Framework</a> grid on Django Packages.</p>
<p><strong>Date</strong>: <ahref="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.4+Release%22+">3rd November 2014</a>.</p>
<ul>
<li><strong>Security fix</strong>: Escape URLs when replacing <code>format=</code> query parameter, as used in dropdown on <code>GET</code> button in browsable API to allow explicit selection of JSON vs HTML output.</li>
<li>Maintain ordering of URLs in API root view for <code>DefaultRouter</code>.</li>
<li>Fix <code>follow=True</code> in <code>APIRequestFactory</code></li>
<li>Resolve issue with invalid <code>read_only=True</code>, <code>required=True</code> fields being automatically generated by <code>ModelSerializer</code> in some cases.</li>
<li>Resolve issue with <code>OPTIONS</code> requests returning incorrect information for views using <code>get_serializer_class</code> to dynamically determine serializer based on request method. </li>
</ul>
<h3id="243">2.4.3</h3>
<h3id="243">2.4.3</h3>
<p><strong>Date</strong>: <ahref="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.3+Release%22+">19th September 2014</a>.</p>
<p><strong>Date</strong>: <ahref="https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.3+Release%22+">19th September 2014</a>.</p>
<li><ahref="https://github.com/etoccalino/django-rest-framework-httpsignature">djangorestframework-httpsignature</a> - Provides an easy to use HTTP Signature Authentication mechanism.</li>
<li><ahref="https://github.com/etoccalino/django-rest-framework-httpsignature">djangorestframework-httpsignature</a> - Provides an easy to use HTTP Signature Authentication mechanism.</li>
<li><ahref="https://github.com/sunscrapers/djoser">djoser</a> - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.</li>
<p>It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed <code>json</code>, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.</p>
<p>It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed <code>json</code>, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.</p>
<h2id="testing-our-first-attempt-at-a-web-api">Testing our first attempt at a Web API</h2>
<h2id="testing-our-first-attempt-at-a-web-api">Testing our first attempt at a Web API</h2>
<p>The <code>r'^api-auth/'</code> part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the <code>'rest_framework'</code> namespace.</p>
<p>The <code>r'^api-auth/'</code> part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the <code>'rest_framework'</code> namespace.</p>
<p>Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.</p>
<p>Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.</p>
<p>The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.</p>
<p>The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.</p>
<p>Notice how we're creating multiple views from each <code>ViewSet</code> class, by binding the http methods to the required action for each view.</p>
<p>Notice how we're creating multiple views from each <code>ViewSet</code> class, by binding the http methods to the required action for each view.</p>
<p>Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.</p>
<p>Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.</p>
<p>Because we're using <code>ViewSet</code> classes rather than <code>View</code> classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a <code>Router</code> class. All we need to do is register the appropriate view sets with a router, and let it do the rest.</p>
<p>Because we're using <code>ViewSet</code> classes rather than <code>View</code> classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a <code>Router</code> class. All we need to do is register the appropriate view sets with a router, and let it do the rest.</p>
<p>Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.</p>
<p>Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.</p>
<p>The <code>DefaultRouter</code> class we're using also automatically creates the API root view for us, so we can now delete the <code>api_root</code> method from our <code>views</code> module.</p>
<p>The <code>DefaultRouter</code> class we're using also automatically creates the API root view for us, so we can now delete the <code>api_root</code> method from our <code>views</code> module.</p>