<p>— Jacob Kaplan-Moss, <ahref="http://jacobian.org/writing/rest-worst-practices/">"REST worst practices"</a></p>
</blockquote>
<p>Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The <ahref="permissions.html">permission</a> and <ahref="throttling.html">throttling</a> policies can then use those credentials to determine if the request should be permitted.</p>
<p>Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The <ahref="permissions">permission</a> and <ahref="throttling">throttling</a> policies can then use those credentials to determine if the request should be permitted.</p>
<p>REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.</p>
<p>Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.</p>
<p>The <code>request.user</code> property will typically be set to an instance of the <code>contrib.auth</code> package's <code>User</code> class.</p>
<p>The <code>request.auth</code> property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.</p>
<hr/>
<p><strong>Note:</strong> Don't forget that <strong>authentication by itself won't allow or disallow an incoming request</strong>, it simply identifies the credentials that the request was made with.</p>
<p>For information on how to setup the permission polices for your API please see the <ahref="permissions.html">permissions documentation</a>.</p>
<p>For information on how to setup the permission polices for your API please see the <ahref="permissions">permissions documentation</a>.</p>
<hr/>
<h2id="how-authentication-is-determined">How authentication is determined</h2>
<p>The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set <code>request.user</code> and <code>request.auth</code> using the return value of the first class that successfully authenticates.</p>
<p>Raised when an incoming request includes incorrect authentication.</p>
<p>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 <ahref="authentication.html">authentication documentation</a> for more details.</p>
<p>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 <ahref="authentication">authentication documentation</a> for more details.</p>
<p>Raised when an unauthenticated request fails the permission checks.</p>
<p>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 <ahref="authentication.html">authentication documentation</a> for more details.</p>
<p>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 <ahref="authentication">authentication documentation</a> for more details.</p>
<p>Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.</p>
<p>Together with <ahref="authentication.html">authentication</a> and <ahref="throttling.html">throttling</a>, permissions determine whether a request should be granted or denied access.</p>
<p>Together with <ahref="authentication">authentication</a> and <ahref="throttling">throttling</a>, permissions determine whether a request should be granted or denied access.</p>
<p>Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the <code>request.user</code> and <code>request.auth</code> properties to determine if the incoming request should be permitted.</p>
<h2id="how-permissions-are-determined">How permissions are determined</h2>
<p>Permissions in REST framework are always defined as a list of permission classes. </p>
...
...
@@ -338,7 +339,7 @@ else:
<hr/>
<p><strong>Note</strong>: In versions 2.0 and 2.1, the signature for the permission checks always included an optional <code>obj</code> parameter, like so: <code>.has_permission(self, request, view, obj=None)</code>. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required.</p>
<p>As of version 2.2 this signature has now been replaced with two separate method calls, which is more explicit and obvious. The old style signature continues to work, but its use will result in a <code>PendingDeprecationWarning</code>, which is silent by default. In 2.3 this will be escalated to a <code>DeprecationWarning</code>, and in 2.4 the old-style signature will be removed.</p>
<p>For more details see the <ahref="../topics/2.2-announcement.html">2.2 release announcement</a>.</p>
<p>For more details see the <ahref="../topics/2.2-announcement">2.2 release announcement</a>.</p>
<hr/>
<h2id="examples">Examples</h2>
<p>The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.</p>
...
...
@@ -371,7 +372,7 @@ class BlacklistPermission(permissions.BasePermission):
return obj.owner == request.user
</code></pre>
<p>Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling <code>self.check_object_permissions(request, obj)</code> from the view once you have the object instance. This call will raise an appropriate <code>APIException</code> if any object-level permission checks fail, and will otherwise simply return.</p>
<p>Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the <ahref="filtering.html">filtering documentation</a> for more details.</p>
<p>Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the <ahref="filtering">filtering documentation</a> for more details.</p>
<hr/>
<h1id="third-party-packages">Third party packages</h1>
<p>The following third party packages are also available.</p>
@@ -575,7 +576,7 @@ They continue to function, but their usage will raise a <code>PendingDeprecation
<p>The <code>null=<bool></code> flag has been deprecated in favor of the <code>required=<bool></code> flag. It will continue to function, but will raise a <code>PendingDeprecationWarning</code>.</p>
<p>In the 2.3 release, these warnings will be escalated to a <code>DeprecationWarning</code>, which is loud by default.
In the 2.4 release, these parts of the API will be removed entirely.</p>
<p>For more details see the <ahref="../topics/2.2-announcement.html">2.2 release announcement</a>.</p>
<p>For more details see the <ahref="../topics/2.2-announcement">2.2 release announcement</a>.</p>
<h2id="how-the-renderer-is-determined">How the renderer is determined</h2>
<p>The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.</p>
<p>The basic process of content negotiation involves examining the request's <code>Accept</code> header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL <code>http://example.com/api/users_count.json</code> might be an endpoint that always returns JSON data.</p>
<p>For more information see the documentation on <ahref="content-negotiation.html">content negotiation</a>.</p>
<p>For more information see the documentation on <ahref="content-negotiation">content negotiation</a>.</p>
<h2id="setting-the-renderers">Setting the renderers</h2>
<p>The default set of renderers may be set globally, using the <code>DEFAULT_RENDERER_CLASSES</code> setting. For example, the following settings would use <code>YAML</code> as the main media type and also include the self describing API.</p>
<p>Renders the request data into <code>JSONP</code>. The <code>JSONP</code> media type provides a mechanism of allowing cross-domain AJAX requests, by wrapping a <code>JSON</code> response in a javascript callback.</p>
<p>The javascript callback function must be set by the client including a <code>callback</code> URL query parameter. For example <code>http://example.com/api/users?callback=jsonpCallback</code>. If the callback function is not explicitly set by the client it will default to <code>'callback'</code>.</p>
<p><strong>Note</strong>: If you require cross-domain AJAX requests, you may want to consider using the more modern approach of <ahref="http://www.w3.org/TR/cors/">CORS</a> as an alternative to <code>JSONP</code>. See the <ahref="../topics/ajax-csrf-cors.html">CORS documentation</a> for more details.</p>
<p><strong>Note</strong>: If you require cross-domain AJAX requests, you may want to consider using the more modern approach of <ahref="http://www.w3.org/TR/cors/">CORS</a> as an alternative to <code>JSONP</code>. See the <ahref="../topics/ajax-csrf-cors">CORS documentation</a> for more details.</p>
<p>This renderer is used for rendering HTML multipart form data. <strong>It is not suitable as a response renderer</strong>, but is instead used for creating test requests, using REST framework's <ahref="testing.html">test client and test request factory</a>.</p>
<p>This renderer is used for rendering HTML multipart form data. <strong>It is not suitable as a response renderer</strong>, but is instead used for creating test requests, using REST framework's <ahref="testing">test client and test request factory</a>.</p>
<li>It supports parsing the content of HTTP methods other than <code>POST</code>, meaning that you can access the content of <code>PUT</code> and <code>PATCH</code> requests.</li>
<li>It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.</li>
</ul>
<p>For more details see the <ahref="parsers.html">parsers documentation</a>.</p>
<p>For more details see the <ahref="parsers">parsers documentation</a>.</p>
<h2id="files">.FILES</h2>
<p><code>request.FILES</code> returns any uploaded files that may be present in the content of the request body. This is the same as the standard <code>HttpRequest</code> behavior, except that the same flexible request parsing is used for <code>request.DATA</code>.</p>
<p>For more details see the <ahref="parsers.html">parsers documentation</a>.</p>
<p>For more details see the <ahref="parsers">parsers documentation</a>.</p>
<h2id="query_params">.QUERY_PARAMS</h2>
<p><code>request.QUERY_PARAMS</code> is a more correctly named synonym for <code>request.GET</code>.</p>
<p>For clarity inside your code, we recommend using <code>request.QUERY_PARAMS</code> instead of the usual <code>request.GET</code>, as <em>any</em> HTTP method type may include query parameters.</p>
...
...
@@ -252,11 +253,11 @@
<h2id="user">.user</h2>
<p><code>request.user</code> typically returns an instance of <code>django.contrib.auth.models.User</code>, although the behavior depends on the authentication policy being used.</p>
<p>If the request is unauthenticated the default value of <code>request.user</code> is an instance of <code>django.contrib.auth.models.AnonymousUser</code>.</p>
<p>For more details see the <ahref="authentication.html">authentication documentation</a>.</p>
<p>For more details see the <ahref="authentication">authentication documentation</a>.</p>
<h2id="auth">.auth</h2>
<p><code>request.auth</code> returns any additional authentication context. The exact behavior of <code>request.auth</code> depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against.</p>
<p>If the request is unauthenticated, or if no additional context is present, the default value of <code>request.auth</code> is <code>None</code>.</p>
<p>For more details see the <ahref="authentication.html">authentication documentation</a>.</p>
<p>For more details see the <ahref="authentication">authentication documentation</a>.</p>
<h2id="authenticators">.authenticators</h2>
<p>The <code>APIView</code> class or <code>@api_view</code> decorator will ensure that this property is automatically set to a list of <code>Authentication</code> instances, based on the <code>authentication_classes</code> set on the view or based on the <code>DEFAULT_AUTHENTICATORS</code> setting.</p>
<p>You won't typically need to access this property.</p>
...
...
@@ -266,17 +267,17 @@
<h2id="method">.method</h2>
<p><code>request.method</code> returns the <strong>uppercased</strong> string representation of the request's HTTP method.</p>
<p>Browser-based <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code> forms are transparently supported.</p>
<p>For more information see the <ahref="../topics/browser-enhancements.html">browser enhancements documentation</a>. </p>
<p>For more information see the <ahref="../topics/browser-enhancements">browser enhancements documentation</a>. </p>
<h2id="content_type">.content_type</h2>
<p><code>request.content_type</code>, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided.</p>
<p>You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior.</p>
<p>If you do need to access the content type of the request you should use the <code>.content_type</code> property in preference to using <code>request.META.get('HTTP_CONTENT_TYPE')</code>, as it provides transparent support for browser-based non-form content.</p>
<p>For more information see the <ahref="../topics/browser-enhancements.html">browser enhancements documentation</a>. </p>
<p>For more information see the <ahref="../topics/browser-enhancements">browser enhancements documentation</a>. </p>
<h2id="stream">.stream</h2>
<p><code>request.stream</code> returns a stream representing the content of the request body.</p>
<p>You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.</p>
<p>If you do need to access the raw content directly, you should use the <code>.stream</code> property in preference to using <code>request.content</code>, as it provides transparent support for browser-based non-form content.</p>
<p>For more information see the <ahref="../topics/browser-enhancements.html">browser enhancements documentation</a>. </p>
<p>For more information see the <ahref="../topics/browser-enhancements">browser enhancements documentation</a>. </p>
<p>As REST framework's <code>Request</code> extends Django's <code>HttpRequest</code>, all the other standard attributes and methods are also available. For example the <code>request.META</code> and <code>request.session</code> dictionaries are available as normal.</p>
<li><code>data</code>: The serialized data for the response.</li>
<li><code>status</code>: A status code for the response. Defaults to 200. See also <ahref="status-codes.html">status codes</a>.</li>
<li><code>status</code>: A status code for the response. Defaults to 200. See also <ahref="status-codes">status codes</a>.</li>
<li><code>template_name</code>: A template name to use if <code>HTMLRenderer</code> is selected.</li>
<li><code>headers</code>: A dictionary of HTTP headers to use in the response.</li>
<li><code>content_type</code>: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly.</li>
@@ -524,7 +525,7 @@ The <code>ModelSerializer</code> class lets you automatically create a Serialize
<h2id="relational-fields">Relational fields</h2>
<p>When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for <code>ModelSerializer</code> is to use the primary keys of the related instances.</p>
<p>Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.</p>
<p>For full details see the <ahref="relations.html">serializer relations</a> documentation.</p>
<p>For full details see the <ahref="relations">serializer relations</a> documentation.</p>
<p>The <code>HyperlinkedModelSerializer</code> class is similar to the <code>ModelSerializer</code> class except that it uses hyperlinks to represent relationships, rather than primary keys.</p>
<p><ahref="https://dev.twitter.com/docs/error-codes-responses">Twitter API rate limiting response</a></p>
</blockquote>
<p>Throttling is similar to <ahref="permissions.html">permissions</a>, 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.</p>
<p>Throttling is similar to <ahref="permissions">permissions</a>, 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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come <em>after</em> (below) the <code>@api_view</code> decorator. For example, to create a view that uses a <ahref="api-guide/throttling.html">throttle</a> to ensure it can only be called once per day by a particular user, use the <code>@throttle_classes</code> decorator, passing a list of throttle classes:</p>
<p>To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come <em>after</em> (below) the <code>@api_view</code> decorator. For example, to create a view that uses a <ahref="api-guide/throttling">throttle</a> to ensure it can only be called once per day by a particular user, use the <code>@throttle_classes</code> decorator, passing a list of throttle classes:</p>
<p>Some reasons you might want to use REST framework:</p>
<ul>
<li>The <ahref="http://restframework.herokuapp.com/">Web browseable API</a> is a huge usability win for your developers.</li>
<li><ahref="api-guide/authentication.html">Authentication policies</a> including <ahref="api-guide/authentication.html#oauthauthentication">OAuth1a</a> and <ahref="api-guide/authentication.html#oauth2authentication">OAuth2</a> out of the box.</li>
<li><ahref="api-guide/serializers.html">Serialization</a> that supports both <ahref="api-guide/serializers.html#modelserializer">ORM</a> and <ahref="api-guide/serializers.html#serializers">non-ORM</a> data sources.</li>
<li>Customizable all the way down - just use <ahref="api-guide/views.html#function-based-views">regular function-based views</a> if you don't need the <ahref="api-guide/generic-views.html">more</a><ahref="api-guide/viewsets.html">powerful</a><ahref="api-guide/routers.html">features</a>.</li>
<li><ahref="api-guide/authentication">Authentication policies</a> including <ahref="api-guide/authentication.html#oauthauthentication">OAuth1a</a> and <ahref="api-guide/authentication.html#oauth2authentication">OAuth2</a> out of the box.</li>
<li><ahref="api-guide/serializers">Serialization</a> that supports both <ahref="api-guide/serializers.html#modelserializer">ORM</a> and <ahref="api-guide/serializers.html#serializers">non-ORM</a> data sources.</li>
<li>Customizable all the way down - just use <ahref="api-guide/views.html#function-based-views">regular function-based views</a> if you don't need the <ahref="api-guide/generic-views">more</a><ahref="api-guide/viewsets">powerful</a><ahref="api-guide/routers">features</a>.</li>
<li><ahref=".">Extensive documentation</a>, and <ahref="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">great community support</a>.</li>
</ul>
<p>There is a live example API for testing purposes, <ahref="http://restframework.herokuapp.com/">available here</a>.</p>
...
...
@@ -317,57 +318,57 @@ urlpatterns = patterns('',
)
</code></pre>
<h2id="quickstart">Quickstart</h2>
<p>Can't wait to get started? The <ahref="tutorial/quickstart.html">quickstart guide</a> is the fastest way to get up and running, and building APIs with REST framework.</p>
<p>Can't wait to get started? The <ahref="tutorial/quickstart">quickstart guide</a> is the fastest way to get up and running, and building APIs with REST framework.</p>
<h2id="tutorial">Tutorial</h2>
<p>The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.</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.html">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>
<h2id="simpler-views">Simpler views</h2>
<p>This release rationalises the API and implementation of the generic views, dropping the dependency on Django's <code>SingleObjectMixin</code> and <code>MultipleObjectMixin</code> classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.</p>
<p>This improvement is reflected in improved documentation for the <code>GenericAPIView</code> base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses.</p>
<p>API may stand for Application <em>Programming</em> Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the <code>HTML</code> format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using <code>POST</code>, <code>PUT</code>, and <code>DELETE</code>.</p>
<h2id="urls">URLs</h2>
<p>If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The <code>rest_framework</code> package includes a <ahref="../api-guide/reverse.html"><code>reverse</code></a> helper for this purpose.</p>
<p>If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The <code>rest_framework</code> package includes a <ahref="../api-guide/reverse"><code>reverse</code></a> helper for this purpose.</p>
<h2id="formats">Formats</h2>
<p>By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using <code>?format=</code> in the request, so you can look at the raw JSON response in a browser by adding <code>?format=json</code> to the URL. There are helpful extensions for viewing JSON in <ahref="https://addons.mozilla.org/en-US/firefox/addon/jsonview/">Firefox</a> and <ahref="https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc">Chrome</a>.</p>
<p>To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.</p>
<p>In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the <em>media types</em> that are used. The available actions take may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.</p>
<p>To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The <ahref="rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a> section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.</p>
<p>To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The <ahref="rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a> section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.</p>
<p>We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great.</p>
<h2id="summary">Summary</h2>
<p>In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.</p>
<p>If you're interested please take a browse around the documentation. <ahref="../tutorial/1-serialization.html">The tutorial</a> is a great place to get started.</p>
<p>If you're interested please take a browse around the documentation. <ahref="../tutorial/1-serialization">The tutorial</a> is a great place to get started.</p>
<p>There's also a <ahref="http://restframework.herokuapp.com/">live sandbox version of the tutorial API</a> available for testing.</p>
@@ -223,7 +224,7 @@ the Design of Network-based Software Architectures</a>.</li>
<p>REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.</p>
<p>It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.</p>
<p>REST framework also includes <ahref="../api-guide/serializers.html">serialization</a> and <ahref="../api-guide/parsers.html">parser</a>/<ahref="../api-guide/renderers.html">renderer</a> components that make it easy to build appropriate media types, <ahref="../api-guide/fields.html">hyperlinked relations</a> for building well-connected systems, and great support for <ahref="../api-guide/content-negotiation.html">content negotiation</a>.</p>
<p>REST framework also includes <ahref="../api-guide/serializers">serialization</a> and <ahref="../api-guide/parsers">parser</a>/<ahref="../api-guide/renderers">renderer</a> components that make it easy to build appropriate media types, <ahref="../api-guide/fields">hyperlinked relations</a> for building well-connected systems, and great support for <ahref="../api-guide/content-negotiation">content negotiation</a>.</p>
<p>What REST framework doesn't do is give you is machine readable hypermedia formats such as <ahref="http://stateless.co/hal_specification.html">HAL</a>, <ahref="http://www.amundsen.com/media-types/collection/">Collection+JSON</a>, <ahref="http://jsonapi.org/">JSON API</a> or HTML <ahref="http://microformats.org/wiki/Main_Page">microformats</a> by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.</p>
<p>This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.</p>
<p>The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the <ahref="quickstart.html">quickstart</a> documentation instead.</p>
<p>The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the <ahref="quickstart">quickstart</a> documentation instead.</p>
<hr/>
<p><strong>Note</strong>: The code for this tutorial is available in the <ahref="https://github.com/tomchristie/rest-framework-tutorial">tomchristie/rest-framework-tutorial</a> repository on GitHub. The completed implementation is also online as a sandbox version for testing, <ahref="http://restframework.herokuapp.com/">available here</a>.</p>
<hr/>
...
...
@@ -498,7 +499,7 @@ Quit the server with CONTROL-C.
<h2id="where-are-we-now">Where are we now</h2>
<p>We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.</p>
<p>Our API views don't do anything particularly special at the moment, beyond serving <code>json</code> responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.</p>
<p>We'll see how we can start to improve things in <ahref="2-requests-and-responses.html">part 2 of the tutorial</a>.</p>
<p>We'll see how we can start to improve things in <ahref="2-requests-and-responses">part 2 of the tutorial</a>.</p>
<p>We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.</p>
<h2id="hows-it-looking">How's it looking?</h2>
<p>Go ahead and test the API from the command line, as we did in <ahref="1-serialization.html">tutorial part 1</a>. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.</p>
<p>Go ahead and test the API from the command line, as we did in <ahref="1-serialization">tutorial part 1</a>. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.</p>
<p>We can get a list of all of the snippets, as before.</p>
<p>Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.</p>
<p>Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.</p>
<p>See the <ahref="../topics/browsable-api.html">browsable api</a> topic for more information about the browsable API feature and how to customize it.</p>
<p>See the <ahref="../topics/browsable-api">browsable api</a> topic for more information about the browsable API feature and how to customize it.</p>
<h2id="whats-next">What's next?</h2>
<p>In <ahref="3-class-based-views.html">tutorial part 3</a>, we'll start using class based views, and see how generic views reduce the amount of code we need to write.</p>
<p>In <ahref="3-class-based-views">tutorial part 3</a>, we'll start using class based views, and see how generic views reduce the amount of code we need to write.</p>
@@ -329,7 +330,7 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
serializer_class = SnippetSerializer
</code></pre>
<p>Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.</p>
<p>Next we'll move onto <ahref="4-authentication-and-permissions.html">part 4 of the tutorial</a>, where we'll take a look at how we can deal with authentication and permissions for our API.</p>
<p>Next we'll move onto <ahref="4-authentication-and-permissions">part 4 of the tutorial</a>, where we'll take a look at how we can deal with authentication and permissions for our API.</p>
@@ -263,7 +264,10 @@ class UserSerializer(serializers.ModelSerializer):
</code></pre>
<p>Because <code>'snippets'</code> is a <em>reverse</em> relationship on the User model, it will not be included by default when using the <code>ModelSerializer</code> class, so we needed to add an explicit field for it.</p>
<p>We'll also add a couple of views to <code>views.py</code>. We'd like to just use read-only views for the user representations, so we'll use the <code>ListAPIView</code> and <code>RetrieveAPIView</code> generic class based views.</p>
<preclass="prettyprint lang-py"><code>from django.contrib.auth.models import User
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
...
...
@@ -347,7 +351,7 @@ class IsOwnerOrReadOnly(permissions.BasePermission):
</code></pre>
<p>Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.</p>
<h2id="authenticating-with-the-api">Authenticating with the API</h2>
<p>Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any <ahref="../api-guide/authentication.html">authentication classes</a>, so the defaults are currently applied, which are <code>SessionAuthentication</code> and <code>BasicAuthentication</code>.</p>
<p>Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any <ahref="../api-guide/authentication">authentication classes</a>, so the defaults are currently applied, which are <code>SessionAuthentication</code> and <code>BasicAuthentication</code>.</p>
<p>When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.</p>
<p>If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.</p>
<p>If we try to create a snippet without authenticating, we'll get an error:</p>
...
...
@@ -362,7 +366,7 @@ class IsOwnerOrReadOnly(permissions.BasePermission):
</code></pre>
<h2id="summary">Summary</h2>
<p>We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.</p>
<p>In <ahref="5-relationships-and-hyperlinked-apis.html">part 5</a> of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.</p>
<p>In <ahref="5-relationships-and-hyperlinked-apis">part 5</a> of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.</p>
<p>If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.</p>
<p>You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.</p>
<p>In <ahref="6-viewsets-and-routers.html">part 6</a> of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.</p>
<p>In <ahref="6-viewsets-and-routers">part 6</a> of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.</p>
<p>If you want to get a more in depth understanding of how REST framework fits together head on over to <ahref="1-serialization.html">the tutorial</a>, or start browsing the <ahref="../#api-guide">API guide</a>.</p>
<p>If you want to get a more in depth understanding of how REST framework fits together head on over to <ahref="1-serialization">the tutorial</a>, or start browsing the <ahref="../#api-guide">API guide</a>.</p>