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 >
< 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-09-09 19:56:34 +04:00
< body onload = "prettyPrint()" class = "1-serialization" >
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-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 >
< 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-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 >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/formoverloading" > Browser based PUT, PATCH and DELETE< / a > < / li >
2012-09-14 16:05:54 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/browsable-api" > Working with the browsable API< / 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-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-09-08 11:03:30 +04:00
< 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 >
2012-09-02 00:24:33 +04:00
< / div > <!-- /.nav - collapse -->
< / div >
< / div >
< / div >
< div class = "container-fluid" >
< div class = "row-fluid" >
2012-09-08 11:03:30 +04:00
< div class = "span3" >
< div id = "table-of-contents" class = "well affix span3" >
< ul class = "nav nav-list side-nav" >
< li class = "main" > < a href = "#tutorial-1-serialization" > Tutorial 1: Serialization< / a > < / li >
2012-09-02 00:24:33 +04:00
< li > < a href = "#introduction" > Introduction< / a > < / li >
2012-09-03 16:10:11 +04:00
< li > < a href = "#setting-up-a-new-environment" > Setting up a new environment< / a > < / li >
2012-09-02 00:24:33 +04:00
< 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 >
2012-09-08 11:03:30 +04:00
< / ul >
< / div >
2012-09-02 00:24:33 +04:00
< / div >
2012-09-08 11:03:30 +04:00
< div id = "main-content" class = "span9" >
< h1 id = "tutorial-1-serialization" > Tutorial 1: Serialization< / h1 >
2012-09-02 00:24:33 +04:00
< 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 >
2012-09-03 16:10:11 +04:00
< 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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-bsh" >
mkdir ~/env
2012-09-05 16:05:36 +04:00
virtualenv --no-site-packages ~/env/tutorial
source ~/env/tutorial/bin/activate
2012-09-03 16:10:11 +04:00
< / code > < / pre >
< p > Now that we're inside a virtualenv environment, we can install our package requirements.< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > pip install django
2012-09-03 16:10:11 +04:00
pip install djangorestframework
< / code > < / pre >
2012-09-05 16:05:36 +04:00
< 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 >
2012-09-02 00:24:33 +04:00
< h2 id = "getting-started" > Getting started< / h2 >
2012-09-03 16:10:11 +04:00
< p > Okay, we're ready to get coding.
To get started, let's create a new project to work with.< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > django-admin.py startproject tutorial
2012-09-02 00:24:33 +04:00
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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > python manage.py startapp blog
2012-09-02 00:24:33 +04:00
< / 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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > DATABASES = {
2012-09-02 00:24:33 +04:00
'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 > djangorestframework< / code > app to < code > INSTALLED_APPS< / code > .< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > INSTALLED_APPS = (
2012-09-02 00:24:33 +04:00
...
'djangorestframework',
'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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > urlpatterns = patterns('',
2012-09-02 00:24:33 +04:00
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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > from django.db import models
2012-09-02 00:24:33 +04:00
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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > python manage.py syncdb
2012-09-02 00:24:33 +04:00
< / 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 project named < code > serializers.py< / code > and add the following.< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > from blog import models
2012-09-02 00:24:33 +04:00
from djangorestframework import serializers
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > python manage.py shell
2012-09-02 00:24:33 +04:00
< / 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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > from blog.models import Comment
2012-09-02 00:24:33 +04:00
from blog.serializers import CommentSerializer
from djangorestframework.renderers import JSONRenderer
from djangorestframework.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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > serializer = CommentSerializer(instance=c1)
2012-09-02 00:24:33 +04:00
serializer.data
2012-09-05 16:05:36 +04:00
# {'email': u'leila@example.com', 'content': u'nothing to say', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774, tzinfo=< UTC> )}
2012-09-02 00:24:33 +04:00
< / 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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > stream = JSONRenderer().render(serializer.data)
2012-09-02 00:24:33 +04:00
stream
# '{"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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > data = JSONParser().parse(stream)
2012-09-02 00:24:33 +04:00
< / code > < / pre >
< p > ...then we restore those native datatypes into to a fully populated object instance.< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > serializer = CommentSerializer(data)
2012-09-02 00:24:33 +04:00
serializer.is_valid()
# True
serializer.object
2012-09-05 16:05:36 +04:00
# < Comment: Comment object>
2012-09-02 00:24:33 +04:00
< / 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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > from blog.models import Comment
2012-09-02 00:24:33 +04:00
from blog.serializers import CommentSerializer
from djangorestframework.renderers import JSONRenderer
from djangorestframework.parsers import JSONParser
from django.http import HttpResponse
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 >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > def comment_root(request):
2012-09-02 00:24:33 +04:00
"""
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.error_data, status=400)
< / code > < / pre >
< p > We'll also need a view which corrosponds to an individual comment, and can be used to retrieve, update or delete the comment.< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > def comment_instance(request, pk):
2012-09-02 00:24:33 +04:00
"""
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.error_data, status=400)
elif request.method == 'DELETE':
comment.delete()
return HttpResponse(status=204)
< / code > < / pre >
< p > Finally we need to wire these views up, in the < code > tutorial/urls.py< / code > file.< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > from django.conf.urls import patterns, url
2012-09-02 00:24:33 +04:00
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 >
2012-09-05 21:26:37 +04:00
< 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 >
2012-09-02 00:24:33 +04:00
< / div > <!-- /span -->
< / div > <!-- /row -->
< / div > <!-- /.fluid - container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
2012-09-08 11:03:30 +04:00
< script src = "http://tomchristie.github.com/django-rest-framework/js/jquery-1.8.1-min.js" > < / script >
2012-09-08 23:24:07 +04:00
< script src = "http://tomchristie.github.com/django-rest-framework/js/prettify.js" > < / script >
2012-09-02 00:37:41 +04:00
< script src = "http://tomchristie.github.com/django-rest-framework/js/bootstrap-dropdown.js" > < / script >
< script src = "http://tomchristie.github.com/django-rest-framework/js/bootstrap-scrollspy.js" > < / script >
2012-09-08 11:03:30 +04:00
< script src = "http://tomchristie.github.com/django-rest-framework/js/bootstrap-collapse.js" > < / script >
2012-09-02 00:24:33 +04:00
< script >
2012-09-08 11:03:30 +04:00
//$('.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
$('.dropdown-menu').click(function(event) {
event.stopPropagation();
});
2012-09-02 00:24:33 +04:00
< / script >
< / body > < / html >