django-rest-framework/tutorial/2-requests-and-responses.html

269 lines
18 KiB
HTML
Raw Normal View History

2012-09-02 00:24:33 +04:00
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Django REST framework</title>
2012-10-05 18:26:53 +04:00
<link href="http://tomchristie.github.com/django-rest-framework/img/favicon.ico" rel="icon" type="image/x-icon">
2012-09-02 00:24:33 +04:00
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
2012-09-08 23:24:07 +04:00
<link href="http://tomchristie.github.com/django-rest-framework/css/prettify.css" rel="stylesheet">
2012-09-02 00:37:41 +04:00
<link href="http://tomchristie.github.com/django-rest-framework/css/bootstrap.css" rel="stylesheet">
<link href="http://tomchristie.github.com/django-rest-framework/css/bootstrap-responsive.css" rel="stylesheet">
2012-09-13 12:40:09 +04:00
<link href="http://tomchristie.github.com/django-rest-framework/css/default.css" rel="stylesheet">
2012-09-02 00:24:33 +04:00
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
2012-10-01 19:27:59 +04:00
<body onload="prettyPrint()" class="2-requests-and-responses-page">
2012-09-02 00:24:33 +04:00
2012-10-05 22:27:27 +04:00
<div class="wrapper">
2012-09-02 00:24:33 +04:00
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
2012-09-12 16:12:00 +04:00
<a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/restframework2">GitHub</a>
2012-09-02 00:24:33 +04:00
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
2012-09-02 00:37:41 +04:00
<a class="brand" href="http://tomchristie.github.com/django-rest-framework">Django REST framework</a>
2012-09-02 00:24:33 +04:00
<div class="nav-collapse collapse">
<ul class="nav">
2012-09-02 00:37:41 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework">Home</a></li>
2012-09-02 00:24:33 +04:00
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
<ul class="dropdown-menu">
2012-10-09 15:01:56 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/quickstart">Quickstart</a></li>
2012-09-02 00:37:41 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/1-serialization">1 - Serialization</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/2-requests-and-responses">2 - Requests and responses</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/3-class-based-views">3 - Class based views</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/4-authentication-permissions-and-throttling">4 - Authentication, permissions and throttling</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li>
<!-- <li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/6-resource-orientated-projects">6 - Resource orientated projects</a></li> -->
2012-09-02 00:24:33 +04:00
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
<ul class="dropdown-menu">
2012-09-02 00:37:41 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/requests">Requests</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/responses">Responses</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/views">Views</a></li>
2012-09-12 13:14:01 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/generic-views">Generic views</a></li>
2012-09-02 00:37:41 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/parsers">Parsers</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/renderers">Renderers</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/serializers">Serializers</a></li>
2012-10-05 20:10:33 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/fields">Serializer fields</a></li>
2012-09-02 00:37:41 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/authentication">Authentication</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/permissions">Permissions</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/throttling">Throttling</a></li>
2012-10-01 19:27:59 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/pagination">Pagination</a></li>
2012-09-12 13:14:01 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/content-negotiation">Content negotiation</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/format-suffixes">Format suffixes</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/reverse">Returning URLs</a></li>
2012-09-02 00:37:41 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/exceptions">Exceptions</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/status-codes">Status codes</a></li>
2012-09-05 16:05:36 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/settings">Settings</a></li>
2012-09-02 00:24:33 +04:00
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
<ul class="dropdown-menu">
2012-09-02 00:37:41 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/csrf">Working with AJAX and CSRF</a></li>
2012-10-13 18:09:05 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/browser-enhancements">Browser enhancements</a></li>
2012-10-13 18:35:46 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/browsable-api">The Browsable API</a></li>
2012-10-08 15:19:26 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li>
2012-09-05 16:05:36 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/contributing">Contributing to REST framework</a></li>
2012-10-08 15:19:26 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/migration">2.0 Migration Guide</a></li>
2012-10-17 16:50:08 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/release-notes">Release Notes</a></li>
2012-09-02 00:37:41 +04:00
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/credits">Credits</a></li>
2012-09-02 00:24:33 +04:00
</ul>
</li>
</ul>
<ul class="nav pull-right">
2012-10-09 17:13:19 +04:00
<!-- TODO
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Trunk</a></li>
<li><a href="#">2.0.0</a></li>
</ul>
</li>
2012-10-09 17:13:19 +04:00
-->
</ul>
2012-09-02 00:24:33 +04:00
</div><!--/.nav-collapse -->
</div>
</div>
</div>
2012-10-05 22:27:27 +04:00
<div class="body-content">
<div class="container-fluid">
<div class="row-fluid">
2012-10-05 16:22:18 +04:00
2012-10-05 22:27:27 +04:00
<div class="span3">
2012-10-08 15:19:26 +04:00
<!-- TODO
<p style="margin-top: -12px">
<a class="btn btn-mini btn-primary" style="width: 60px">&laquo; previous</a>
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next &raquo;</a>
</p>
-->
2012-10-05 22:27:27 +04:00
<div id="table-of-contents">
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
<li class="main"><a href="#tutorial-2-requests-and-responses">Tutorial 2: Requests and Responses</a></li>
2012-09-02 00:24:33 +04:00
<li><a href="#request-objects">Request objects</a></li>
<li><a href="#response-objects">Response objects</a></li>
<li><a href="#status-codes">Status codes</a></li>
<li><a href="#wrapping-api-views">Wrapping API views</a></li>
<li><a href="#pulling-it-all-together">Pulling it all together</a></li>
<li><a href="#adding-optional-format-suffixes-to-our-urls">Adding optional format suffixes to our URLs</a></li>
<li><a href="#hows-it-looking">How's it looking?</a></li>
<li><a href="#whats-next">What's next?</a></li>
2012-10-05 22:27:27 +04:00
</ul>
</div>
</div>
2012-09-02 00:24:33 +04:00
2012-10-05 22:27:27 +04:00
<div id="main-content" class="span9">
<h1 id="tutorial-2-requests-and-responses">Tutorial 2: Requests and Responses</h1>
2012-09-02 00:24:33 +04:00
<p>From this point we're going to really start covering the core of REST framework.
Let's introduce a couple of essential building blocks.</p>
<h2 id="request-objects">Request objects</h2>
<p>REST framework intoduces 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>
2012-09-08 23:24:07 +04:00
<pre class="prettyprint lang-py"><code>request.POST # Only handles form data. Only works for 'POST' method.
2012-09-02 00:24:33 +04:00
request.DATA # Handles arbitrary data. Works any HTTP request with content.
</code></pre>
<h2 id="response-objects">Response objects</h2>
<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>
2012-09-08 23:24:07 +04:00
<pre class="prettyprint lang-py"><code>return Response(data) # Renders to content type as requested by the client.
2012-09-02 00:24:33 +04:00
</code></pre>
<h2 id="status-codes">Status codes</h2>
<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>
<h2 id="wrapping-api-views">Wrapping API views</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>
2012-10-05 01:32:43 +04:00
<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>
2012-09-02 00:24:33 +04:00
<p>The wrappers also provide behaviour such as returning <code>405 Method Not Allowed</code> responses when appropriate, and handling any <code>ParseError</code> exception that occurs when accessing <code>request.DATA</code> with malformed input.</p>
<h2 id="pulling-it-all-together">Pulling it all together</h2>
<p>Okay, let's go ahead and start using these new components to write a few views. </p>
2012-09-05 16:05:36 +04:00
<p>We don't need our <code>JSONResponse</code> class anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.</p>
2012-09-08 23:24:07 +04:00
<pre class="prettyprint lang-py"><code>from blog.models import Comment
2012-09-05 16:05:36 +04:00
from blog.serializers import CommentSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
2012-09-02 00:24:33 +04:00
2012-09-05 16:05:36 +04:00
@api_view(['GET', 'POST'])
2012-09-02 00:24:33 +04:00
def comment_root(request):
"""
List all comments, or create a new comment.
2012-09-05 16:05:36 +04:00
"""
2012-09-02 00:24:33 +04:00
if request.method == 'GET':
comments = Comment.objects.all()
serializer = CommentSerializer(instance=comments)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CommentSerializer(request.DATA)
if serializer.is_valid():
comment = serializer.object
comment.save()
2012-09-05 16:05:36 +04:00
return Response(serializer.data, status=status.HTTP_201_CREATED)
2012-09-02 00:24:33 +04:00
else:
2012-09-17 23:21:26 +04:00
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2012-09-02 00:24:33 +04:00
</code></pre>
2012-09-05 16:05:36 +04:00
<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>
2012-09-08 23:24:07 +04:00
<pre class="prettyprint lang-py"><code>@api_view(['GET', 'PUT', 'DELETE'])
2012-09-02 00:24:33 +04:00
def comment_instance(request, pk):
"""
Retrieve, update or delete a comment instance.
"""
try:
comment = Comment.objects.get(pk=pk)
except Comment.DoesNotExist:
2012-09-05 16:05:36 +04:00
return Response(status=status.HTTP_404_NOT_FOUND)
2012-09-02 00:24:33 +04:00
if request.method == 'GET':
serializer = CommentSerializer(instance=comment)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = CommentSerializer(request.DATA, instance=comment)
if serializer.is_valid():
comment = serializer.object
comment.save()
return Response(serializer.data)
else:
2012-09-17 23:21:26 +04:00
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2012-09-02 00:24:33 +04:00
elif request.method == 'DELETE':
comment.delete()
2012-09-05 16:05:36 +04:00
return Response(status=status.HTTP_204_NO_CONTENT)
2012-09-02 00:24:33 +04:00
</code></pre>
2012-09-05 16:05:36 +04:00
<p>This should all feel very familiar - there's not a lot different to working with regular Django views.</p>
2012-09-02 00:24:33 +04:00
<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 <code>yaml</code> and 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>
<h2 id="adding-optional-format-suffixes-to-our-urls">Adding optional format suffixes to our URLs</h2>
2012-09-05 16:05:36 +04:00
<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 <a href="http://example.com/api/items/4.json">http://example.com/api/items/4.json</a>.</p>
2012-09-02 00:24:33 +04:00
<p>Start by adding a <code>format</code> keyword argument to both of the views, like so.</p>
2012-09-08 23:24:07 +04:00
<pre class="prettyprint lang-py"><code>def comment_root(request, format=None):
2012-09-02 00:24:33 +04:00
</code></pre>
<p>and</p>
2012-09-08 23:24:07 +04:00
<pre class="prettyprint lang-py"><code>def comment_instance(request, pk, format=None):
2012-09-02 00:24:33 +04:00
</code></pre>
<p>Now update the <code>urls.py</code> file slightly, to append a set of <code>format_suffix_patterns</code> in addition to the existing URLs.</p>
2012-09-08 23:24:07 +04:00
<pre class="prettyprint lang-py"><code>from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
2012-09-02 00:24:33 +04:00
2012-10-09 15:01:56 +04:00
urlpatterns = patterns('blog.views',
2012-09-02 00:24:33 +04:00
url(r'^$', 'comment_root'),
url(r'^(?P&lt;pk&gt;[0-9]+)$', 'comment_instance')
)
urlpatterns = format_suffix_patterns(urlpatterns)
</code></pre>
2012-10-05 01:32:43 +04:00
<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>
2012-09-02 00:24:33 +04:00
<h2 id="hows-it-looking">How's it looking?</h2>
<p>Go ahead and test the API from the command line, as we did in <a href="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>
2012-09-02 00:24:33 +04:00
<p><strong>TODO: Describe using accept headers, content-type headers, and format suffixed URLs</strong></p>
2012-09-07 16:57:03 +04:00
<p>Now go and open the API in a web browser, by visiting <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>."</p>
<p><strong>Note: Right now the Browseable API only works with the CBV's. Need to fix that.</strong></p>
<h3 id="browsability">Browsability</h3>
<p>Because the API chooses a return format based on what the client asks for, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a browser. This allows for the API to be easily browsable and usable by humans.</p>
<p>See the <a href="../topics/browsable-api">browsable api</a> topic for more information about the browsable API feature and how to customize it.</p>
2012-09-02 00:24:33 +04:00
<h2 id="whats-next">What's next?</h2>
2012-09-19 16:02:38 +04:00
<p>In <a href="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>
2012-10-05 22:27:27 +04:00
</div><!--/span-->
</div><!--/row-->
</div><!--/.fluid-container-->
</div><!--/.body content-->
2012-09-02 00:24:33 +04:00
2012-10-05 18:26:53 +04:00
<div id="push"></div>
2012-10-05 22:27:27 +04:00
</div><!--/.wrapper -->
2012-10-05 18:26:53 +04:00
2012-10-05 22:27:27 +04:00
<footer class="span12">
2012-10-05 22:33:52 +04:00
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
2012-10-05 22:27:27 +04:00
</footer>
2012-10-05 18:26:53 +04:00
2012-09-02 00:24:33 +04:00
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="http://tomchristie.github.com/django-rest-framework/js/jquery-1.8.1-min.js"></script>
2012-10-05 16:22:18 +04:00
<script src="http://tomchristie.github.com/django-rest-framework/js/prettify-1.0.js"></script>
<script src="http://tomchristie.github.com/django-rest-framework/js/bootstrap-2.1.1-min.js"></script>
2012-09-02 00:24:33 +04:00
<script>
//$('.side-nav').scrollspy()
var shiftWindow = function() { scrollBy(0, -50) };
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
2012-09-12 13:14:01 +04:00
2012-09-17 23:21:26 +04:00
$('.dropdown-menu').on('click touchstart', function(event) {
2012-09-12 13:14:01 +04:00
event.stopPropagation();
});
2012-09-02 00:24:33 +04:00
</script>
2012-10-01 19:27:59 +04:00
</body></html>