mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-12-04 15:34:05 +03:00
376 lines
22 KiB
HTML
376 lines
22 KiB
HTML
<!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>
|
|
<link href="http://tomchristie.github.com/django-rest-framework/img/favicon.ico" rel="icon" type="image/x-icon">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<meta name="description" content="">
|
|
<meta name="author" content="">
|
|
|
|
<!-- Le styles -->
|
|
<link href="http://tomchristie.github.com/django-rest-framework/css/prettify.css" rel="stylesheet">
|
|
<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">
|
|
<link href="http://tomchristie.github.com/django-rest-framework/css/default.css" rel="stylesheet">
|
|
|
|
<!-- 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]-->
|
|
<body onload="prettyPrint()" class="1-serialization-page">
|
|
|
|
<div class="wrapper">
|
|
|
|
<div class="navbar navbar-inverse navbar-fixed-top">
|
|
<div class="navbar-inner">
|
|
<div class="container-fluid">
|
|
<a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/restframework2">GitHub</a>
|
|
<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>
|
|
<a class="brand" href="http://tomchristie.github.com/django-rest-framework">Django REST framework</a>
|
|
<div class="nav-collapse collapse">
|
|
<ul class="nav">
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework">Home</a></li>
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/quickstart">Quickstart</a></li>
|
|
<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> -->
|
|
</ul>
|
|
</li>
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
<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>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/generic-views">Generic views</a></li>
|
|
<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>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/fields">Serializer fields</a></li>
|
|
<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>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/pagination">Pagination</a></li>
|
|
<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>
|
|
<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>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/settings">Settings</a></li>
|
|
</ul>
|
|
</li>
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/csrf">Working with AJAX and CSRF</a></li>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/browser-enhancements">Browser enhancements</a></li>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/browsable-api">The Browsable API</a></li>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/contributing">Contributing to REST framework</a></li>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/migration">2.0 Migration Guide</a></li>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/release-notes">Release Notes</a></li>
|
|
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/credits">Credits</a></li>
|
|
</ul>
|
|
</li>
|
|
</ul>
|
|
<ul class="nav pull-right">
|
|
<!-- 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>
|
|
-->
|
|
</ul>
|
|
</div><!--/.nav-collapse -->
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="body-content">
|
|
<div class="container-fluid">
|
|
<div class="row-fluid">
|
|
|
|
<div class="span3">
|
|
<!-- TODO
|
|
<p style="margin-top: -12px">
|
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
|
</p>
|
|
-->
|
|
<div id="table-of-contents">
|
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
|
<li class="main"><a href="#tutorial-1-serialization">Tutorial 1: Serialization</a></li>
|
|
<li><a href="#introduction">Introduction</a></li>
|
|
<li><a href="#setting-up-a-new-environment">Setting up a new environment</a></li>
|
|
<li><a href="#getting-started">Getting started</a></li>
|
|
<li><a href="#creating-a-model-to-work-with">Creating a model to work with</a></li>
|
|
<li><a href="#creating-a-serializer-class">Creating a Serializer class</a></li>
|
|
<li><a href="#working-with-serializers">Working with Serializers</a></li>
|
|
<li><a href="#writing-regular-django-views-using-our-serializers">Writing regular Django views using our Serializers</a></li>
|
|
<li><a href="#testing-our-first-attempt-at-a-web-api">Testing our first attempt at a Web API</a></li>
|
|
<li><a href="#where-are-we-now">Where are we now</a></li>
|
|
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="main-content" class="span9">
|
|
<h1 id="tutorial-1-serialization">Tutorial 1: Serialization</h1>
|
|
<h2 id="introduction">Introduction</h2>
|
|
<p>This 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.</p>
|
|
<h2 id="setting-up-a-new-environment">Setting up a new environment</h2>
|
|
<p>Before we do anything else we'll create a new virtual environment, using <a href="http://www.virtualenv.org/en/latest/index.html">virtualenv</a>. This will make sure our package configuration is keep nicely isolated from any other projects we're working on.</p>
|
|
<pre class="prettyprint lang-bsh">
|
|
mkdir ~/env
|
|
virtualenv --no-site-packages ~/env/tutorial
|
|
source ~/env/tutorial/bin/activate
|
|
</code></pre>
|
|
<p>Now that we're inside a virtualenv environment, we can install our package requirements.</p>
|
|
<pre class="prettyprint lang-py"><code>pip install django
|
|
pip install djangorestframework
|
|
</code></pre>
|
|
<p><strong>Note:</strong> To exit the virtualenv environment at any time, just type <code>deactivate</code>. For more information see the <a href="http://www.virtualenv.org/en/latest/index.html">virtualenv documentation</a>.</p>
|
|
<h2 id="getting-started">Getting started</h2>
|
|
<p>Okay, we're ready to get coding.
|
|
To get started, let's create a new project to work with.</p>
|
|
<pre class="prettyprint lang-py"><code>cd ~
|
|
django-admin.py startproject tutorial
|
|
cd tutorial
|
|
</code></pre>
|
|
<p>Once that's done we can create an app that we'll use to create a simple Web API.</p>
|
|
<pre class="prettyprint lang-py"><code>python manage.py startapp blog
|
|
</code></pre>
|
|
<p>The simplest way to get up and running will probably be to use an <code>sqlite3</code> database for the tutorial. Edit the <code>tutorial/settings.py</code> file, and set the default database <code>"ENGINE"</code> to <code>"sqlite3"</code>, and <code>"NAME"</code> to <code>"tmp.db"</code>.</p>
|
|
<pre class="prettyprint lang-py"><code>DATABASES = {
|
|
'default': {
|
|
'ENGINE': 'django.db.backends.sqlite3',
|
|
'NAME': 'tmp.db',
|
|
'USER': '',
|
|
'PASSWORD': '',
|
|
'HOST': '',
|
|
'PORT': '',
|
|
}
|
|
}
|
|
</code></pre>
|
|
<p>We'll also need to add our new <code>blog</code> app and the <code>rest_framework</code> app to <code>INSTALLED_APPS</code>.</p>
|
|
<pre class="prettyprint lang-py"><code>INSTALLED_APPS = (
|
|
...
|
|
'rest_framework',
|
|
'blog'
|
|
)
|
|
</code></pre>
|
|
<p>We also need to wire up the root urlconf, in the <code>tutorial/urls.py</code> file, to include our blog views.</p>
|
|
<pre class="prettyprint lang-py"><code>urlpatterns = patterns('',
|
|
url(r'^', include('blog.urls')),
|
|
)
|
|
</code></pre>
|
|
<p>Okay, we're ready to roll.</p>
|
|
<h2 id="creating-a-model-to-work-with">Creating a model to work with</h2>
|
|
<p>For the purposes of this tutorial we're going to start by creating a simple <code>Comment</code> model that is used to store comments against a blog post. Go ahead and edit the <code>blog</code> app's <code>models.py</code> file.</p>
|
|
<pre class="prettyprint lang-py"><code>from django.db import models
|
|
|
|
class Comment(models.Model):
|
|
email = models.EmailField()
|
|
content = models.CharField(max_length=200)
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
</code></pre>
|
|
<p>Don't forget to sync the database for the first time.</p>
|
|
<pre class="prettyprint lang-py"><code>python manage.py syncdb
|
|
</code></pre>
|
|
<h2 id="creating-a-serializer-class">Creating a Serializer class</h2>
|
|
<p>We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as <code>json</code>. We do this by declaring serializers that work very similarly to Django's forms. Create a file in the <code>blog</code> directory named <code>serializers.py</code> and add the following.</p>
|
|
<pre class="prettyprint lang-py"><code>from blog import models
|
|
from rest_framework import serializers
|
|
|
|
class CommentSerializer(serializers.Serializer):
|
|
id = serializers.IntegerField(readonly=True)
|
|
email = serializers.EmailField()
|
|
content = serializers.CharField(max_length=200)
|
|
created = serializers.DateTimeField(readonly=True)
|
|
|
|
def restore_object(self, attrs, instance=None):
|
|
"""
|
|
Create or update a new comment instance.
|
|
"""
|
|
if instance:
|
|
instance.email = attrs['email']
|
|
instance.content = attrs['content']
|
|
instance.created = attrs['created']
|
|
return instance
|
|
return models.Comment(**attrs)
|
|
</code></pre>
|
|
<p>The first part of serializer class defines the fields that get serialized/deserialized. The <code>restore_object</code> method defines how fully fledged instances get created when deserializing data.</p>
|
|
<p>We can actually also save ourselves some time by using the <code>ModelSerializer</code> class, as we'll see later, but for now we'll keep our serializer definition explicit.<br />
|
|
</p>
|
|
<h2 id="working-with-serializers">Working with Serializers</h2>
|
|
<p>Before we go any further we'll familiarise ourselves with using our new Serializer class. Let's drop into the Django shell.</p>
|
|
<pre class="prettyprint lang-py"><code>python manage.py shell
|
|
</code></pre>
|
|
<p>Okay, once we've got a few imports out of the way, we'd better create a few comments to work with.</p>
|
|
<pre class="prettyprint lang-py"><code>from blog.models import Comment
|
|
from blog.serializers import CommentSerializer
|
|
from rest_framework.renderers import JSONRenderer
|
|
from rest_framework.parsers import JSONParser
|
|
|
|
c1 = Comment(email='leila@example.com', content='nothing to say')
|
|
c2 = Comment(email='tom@example.com', content='foo bar')
|
|
c3 = Comment(email='anna@example.com', content='LOLZ!')
|
|
c1.save()
|
|
c2.save()
|
|
c3.save()
|
|
</code></pre>
|
|
<p>We've now got a few comment instances to play with. Let's take a look at serializing one of those instances.</p>
|
|
<pre class="prettyprint lang-py"><code>serializer = CommentSerializer(instance=c1)
|
|
serializer.data
|
|
# {'id': 1, 'email': u'leila@example.com', 'content': u'nothing to say', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774, tzinfo=<UTC>)}
|
|
</code></pre>
|
|
<p>At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into <code>json</code>.</p>
|
|
<pre class="prettyprint lang-py"><code>content = JSONRenderer().render(serializer.data)
|
|
content
|
|
# '{"id": 1, "email": "leila@example.com", "content": "nothing to say", "created": "2012-08-22T16:20:09.822"}'
|
|
</code></pre>
|
|
<p>Deserialization is similar. First we parse a stream into python native datatypes... </p>
|
|
<pre class="prettyprint lang-py"><code>import StringIO
|
|
|
|
stream = StringIO.StringIO(content)
|
|
data = JSONParser().parse(stream)
|
|
</code></pre>
|
|
<p>...then we restore those native datatypes into to a fully populated object instance.</p>
|
|
<pre class="prettyprint lang-py"><code>serializer = CommentSerializer(data)
|
|
serializer.is_valid()
|
|
# True
|
|
serializer.object
|
|
# <Comment: Comment object>
|
|
</code></pre>
|
|
<p>Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.</p>
|
|
<h2 id="writing-regular-django-views-using-our-serializers">Writing regular Django views using our Serializers</h2>
|
|
<p>Let's see how we can write some API views using our new Serializer class.
|
|
We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into <code>json</code>.</p>
|
|
<p>Edit the <code>blog/views.py</code> file, and add the following.</p>
|
|
<pre class="prettyprint lang-py"><code>from blog.models import Comment
|
|
from blog.serializers import CommentSerializer
|
|
from django.http import HttpResponse
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
from rest_framework.renderers import JSONRenderer
|
|
from rest_framework.parsers import JSONParser
|
|
|
|
class JSONResponse(HttpResponse):
|
|
"""
|
|
An HttpResponse that renders it's content into JSON.
|
|
"""
|
|
|
|
def __init__(self, data, **kwargs):
|
|
content = JSONRenderer().render(data)
|
|
kwargs['content_type'] = 'application/json'
|
|
super(JSONResponse, self).__init__(content, **kwargs)
|
|
</code></pre>
|
|
<p>The root of our API is going to be a view that supports listing all the existing comments, or creating a new comment.</p>
|
|
<pre class="prettyprint lang-py"><code>@csrf_exempt
|
|
def comment_root(request):
|
|
"""
|
|
List all comments, or create a new comment.
|
|
"""
|
|
if request.method == 'GET':
|
|
comments = Comment.objects.all()
|
|
serializer = CommentSerializer(instance=comments)
|
|
return JSONResponse(serializer.data)
|
|
|
|
elif request.method == 'POST':
|
|
data = JSONParser().parse(request)
|
|
serializer = CommentSerializer(data)
|
|
if serializer.is_valid():
|
|
comment = serializer.object
|
|
comment.save()
|
|
return JSONResponse(serializer.data, status=201)
|
|
else:
|
|
return JSONResponse(serializer.errors, status=400)
|
|
</code></pre>
|
|
<p>Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as <code>csrf_exempt</code>. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now. </p>
|
|
<p>We'll also need a view which corresponds to an individual comment, and can be used to retrieve, update or delete the comment.</p>
|
|
<pre class="prettyprint lang-py"><code>@csrf_exempt
|
|
def comment_instance(request, pk):
|
|
"""
|
|
Retrieve, update or delete a comment instance.
|
|
"""
|
|
try:
|
|
comment = Comment.objects.get(pk=pk)
|
|
except Comment.DoesNotExist:
|
|
return HttpResponse(status=404)
|
|
|
|
if request.method == 'GET':
|
|
serializer = CommentSerializer(instance=comment)
|
|
return JSONResponse(serializer.data)
|
|
|
|
elif request.method == 'PUT':
|
|
data = JSONParser().parse(request)
|
|
serializer = CommentSerializer(data, instance=comment)
|
|
if serializer.is_valid():
|
|
comment = serializer.object
|
|
comment.save()
|
|
return JSONResponse(serializer.data)
|
|
else:
|
|
return JSONResponse(serializer.errors, status=400)
|
|
|
|
elif request.method == 'DELETE':
|
|
comment.delete()
|
|
return HttpResponse(status=204)
|
|
</code></pre>
|
|
<p>Finally we need to wire these views up. Create the <code>blog/urls.py</code> file:</p>
|
|
<pre class="prettyprint lang-py"><code>from django.conf.urls import patterns, url
|
|
|
|
urlpatterns = patterns('blog.views',
|
|
url(r'^$', 'comment_root'),
|
|
url(r'^(?P<pk>[0-9]+)$', 'comment_instance')
|
|
)
|
|
</code></pre>
|
|
<p>It's worth noting that there's 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>
|
|
<h2 id="testing-our-first-attempt-at-a-web-api">Testing our first attempt at a Web API</h2>
|
|
<p><strong>TODO: Describe using runserver and making example requests from console</strong></p>
|
|
<p><strong>TODO: Describe opening in a web browser and viewing json output</strong></p>
|
|
<h2 id="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 serve <code>json</code> responses, and there's 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 <a href="2-requests-and-responses">part 2 of the tutorial</a>.</p>
|
|
</div><!--/span-->
|
|
</div><!--/row-->
|
|
</div><!--/.fluid-container-->
|
|
</div><!--/.body content-->
|
|
|
|
<div id="push"></div>
|
|
</div><!--/.wrapper -->
|
|
|
|
<footer class="span12">
|
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
|
</footer>
|
|
|
|
<!-- 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>
|
|
<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>
|
|
<script>
|
|
//$('.side-nav').scrollspy()
|
|
var shiftWindow = function() { scrollBy(0, -50) };
|
|
if (location.hash) shiftWindow();
|
|
window.addEventListener("hashchange", shiftWindow);
|
|
|
|
$('.dropdown-menu').on('click touchstart', function(event) {
|
|
event.stopPropagation();
|
|
});
|
|
</script>
|
|
</body></html>
|