<p>REST framework introduces a <code>Request</code> object that extends the regular <code>HttpRequest</code>, and provides more flexible request parsing. The core functionality of the <code>Request</code> object is the <code>request.data</code> attribute, which is similar to <code>request.POST</code>, but more useful for working with Web APIs.</p>
<pre><code>request.POST # Only handles form data. Only works for 'POST' method.
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
<p>REST framework also introduces a <code>Response</code> object, which is a type of <code>TemplateResponse</code> that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.</p>
<pre><code>return Response(data) # Renders to content type as requested by the client.
<p>Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as <code>HTTP_400_BAD_REQUEST</code> in the <code>status</code> module. It's a good idea to use these throughout rather than using numeric identifiers.</p>
<h2id="wrapping-api-views"><aclass="toclink"href="#wrapping-api-views">Wrapping API views</a></h2>
<p>REST framework provides two wrappers you can use to write API views.</p>
<ol>
<li>The <code>@api_view</code> decorator for working with function based views.</li>
<li>The <code>APIView</code> class for working with class-based views.</li>
</ol>
<p>These wrappers provide a few bits of functionality such as making sure you receive <code>Request</code> instances in your view, and adding context to <code>Response</code> objects so that content negotiation can be performed.</p>
<p>The wrappers also provide behaviour such as returning <code>405 Method Not Allowed</code> responses when appropriate, and handling any <code>ParseError</code> exceptions that occur when accessing <code>request.data</code> with malformed input.</p>
<p>Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.</p>
<p>Here is the view for an individual snippet, in the <code>views.py</code> module.</p>
<p>This should all feel very familiar - it is not a lot different from working with regular Django views.</p>
<p>Notice that we're no longer explicitly tying our requests or responses to a given content type. <code>request.data</code> can handle incoming <code>json</code> requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.</p>
<h2id="adding-optional-format-suffixes-to-our-urls"><aclass="toclink"href="#adding-optional-format-suffixes-to-our-urls">Adding optional format suffixes to our URLs</a></h2>
<p>To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as <ahref="http://example.com/api/items/4.json">http://example.com/api/items/4.json</a>.</p>
<p>Start by adding a <code>format</code> keyword argument to both of the views, like so.</p>
<p>Now update the <code>snippets/urls.py</code> file slightly, to append a set of <code>format_suffix_patterns</code> in addition to the existing URLs.</p>
<pre><code>from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
<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"><aclass="toclink"href="#hows-it-looking">How's it looking?</a></h2>
<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>
<pre><code>http http://127.0.0.1:8000/snippets/
HTTP/1.1 200 OK
...
[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
</code></pre>
<p>We can control the format of the response that we get back, either by using the <code>Accept</code> header:</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/">browsable api</a> topic for more information about the browsable API feature and how to customize it.</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>
</div><!--/span-->
</div><!--/row-->
</div><!--/.fluid-container-->
</div><!--/.body content-->
<divid="push"></div>
</div><!--/.wrapper -->
<footerclass="span12">
<p>Documentation built with <ahref="http://www.mkdocs.org/">MkDocs</a>.