mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-23 01:57:00 +03:00
541 lines
30 KiB
HTML
541 lines
30 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 - Tutorial 1: Serialization</title>
|
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
|
<link rel="canonical" href="http://django-rest-framework.org/tutorial/1-serialization"/>
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<meta name="description" content="Django, API, REST, Tutorial 1: Serialization">
|
|
<meta name="author" content="Tom Christie">
|
|
|
|
<!-- Le styles -->
|
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
|
<link href="http://django-rest-framework.org/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]-->
|
|
|
|
<script type="text/javascript">
|
|
|
|
var _gaq = _gaq || [];
|
|
_gaq.push(['_setAccount', 'UA-18852272-2']);
|
|
_gaq.push(['_trackPageview']);
|
|
|
|
(function() {
|
|
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
|
|
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
|
|
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
|
|
})();
|
|
|
|
</script>
|
|
</head>
|
|
<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/master">GitHub</a>
|
|
<a class="repo-link btn btn-inverse btn-small " href="../tutorial/2-requests-and-responses">Next <i class="icon-arrow-right icon-white"></i></a>
|
|
<a class="repo-link btn btn-inverse btn-small " href="../tutorial/quickstart"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="modal"><i class="icon-search icon-white"></i> Search</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://django-rest-framework.org">Django REST framework</a>
|
|
<div class="nav-collapse collapse">
|
|
<ul class="nav">
|
|
<li><a href="http://django-rest-framework.org">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://django-rest-framework.org/tutorial/quickstart">Quickstart</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers">6 - Viewsets and routers</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://django-rest-framework.org/api-guide/requests">Requests</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/responses">Responses</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/views">Views</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views">Generic views</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets">Viewsets</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/routers">Routers</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/parsers">Parsers</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/renderers">Renderers</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/serializers">Serializers</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/fields">Serializer fields</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/relations">Serializer relations</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/authentication">Authentication</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/permissions">Permissions</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/throttling">Throttling</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/filtering">Filtering</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/pagination">Pagination</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/reverse">Returning URLs</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions">Exceptions</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes">Status codes</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/testing">Testing</a></li>
|
|
<li><a href="http://django-rest-framework.org/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://django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/browsable-api">The Browsable API</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/release-notes">Release Notes</a></li>
|
|
<li><a href="http://django-rest-framework.org/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">
|
|
|
|
<!-- Search Modal -->
|
|
<div id="searchModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
|
|
<div class="modal-header">
|
|
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
|
|
<h3 id="myModalLabel">Documentation search</h3>
|
|
</div>
|
|
<div class="modal-body">
|
|
<!-- Custom google search -->
|
|
<script>
|
|
(function() {
|
|
var cx = '015016005043623903336:rxraeohqk6w';
|
|
var gcse = document.createElement('script');
|
|
gcse.type = 'text/javascript';
|
|
gcse.async = true;
|
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
|
var s = document.getElementsByTagName('script')[0];
|
|
s.parentNode.insertBefore(gcse, s);
|
|
})();
|
|
</script>
|
|
<gcse:search></gcse:search>
|
|
</div>
|
|
<div class="modal-footer">
|
|
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
|
|
</div>
|
|
</div>
|
|
|
|
<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="#using-modelserializers">Using ModelSerializers</a></li>
|
|
<li><a href="#writing-regular-django-views-using-our-serializer">Writing regular Django views using our Serializer</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>
|
|
|
|
<div>
|
|
<hr>
|
|
|
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
|
|
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
|
|
|
<!-- Begin MailChimp Signup Form -->
|
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
|
<style type="text/css">
|
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
|
</style>
|
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
|
</form>
|
|
</div>
|
|
</style></div>
|
|
</ul>
|
|
|
|
|
|
<!--End mc_embed_signup-->
|
|
</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 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 <a href="quickstart">quickstart</a> documentation instead.</p>
|
|
<hr />
|
|
<p><strong>Note</strong>: The code for this tutorial is available in the <a href="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, <a href="http://restframework.herokuapp.com/">available here</a>.</p>
|
|
<hr />
|
|
<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 kept nicely isolated from any other projects we're working on.</p>
|
|
<pre class="prettyprint lang-bsh">
|
|
mkdir ~/env
|
|
virtualenv ~/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
|
|
pip install pygments # We'll be using this for the code highlighting
|
|
</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 snippets
|
|
</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>snippets</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',
|
|
'snippets',
|
|
)
|
|
</code></pre>
|
|
<p>We also need to wire up the root urlconf, in the <code>tutorial/urls.py</code> file, to include our snippet app's URLs.</p>
|
|
<pre class="prettyprint lang-py"><code>urlpatterns = patterns('',
|
|
url(r'^', include('snippets.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>Snippet</code> model that is used to store code snippets. Go ahead and edit the <code>snippets</code> app's <code>models.py</code> file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.</p>
|
|
<pre class="prettyprint lang-py"><code>from django.db import models
|
|
from pygments.lexers import get_all_lexers
|
|
from pygments.styles import get_all_styles
|
|
|
|
LEXERS = [item for item in get_all_lexers() if item[1]]
|
|
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
|
|
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
|
|
|
|
|
|
class Snippet(models.Model):
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
title = models.CharField(max_length=100, blank=True, default='')
|
|
code = models.TextField()
|
|
linenos = models.BooleanField(default=False)
|
|
language = models.CharField(choices=LANGUAGE_CHOICES,
|
|
default='python',
|
|
max_length=100)
|
|
style = models.CharField(choices=STYLE_CHOICES,
|
|
default='friendly',
|
|
max_length=100)
|
|
|
|
class Meta:
|
|
ordering = ('created',)
|
|
</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>The first thing we need to get started on our Web API is provide a way of serializing and deserializing the snippet instances into representations such as <code>json</code>. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the <code>snippets</code> directory named <code>serializers.py</code> and add the following.</p>
|
|
<pre class="prettyprint lang-py"><code>from django.forms import widgets
|
|
from rest_framework import serializers
|
|
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
|
|
|
|
|
|
class SnippetSerializer(serializers.Serializer):
|
|
pk = serializers.Field() # Note: `Field` is an untyped read-only field.
|
|
title = serializers.CharField(required=False,
|
|
max_length=100)
|
|
code = serializers.CharField(widget=widgets.Textarea,
|
|
max_length=100000)
|
|
linenos = serializers.BooleanField(required=False)
|
|
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
|
|
default='python')
|
|
style = serializers.ChoiceField(choices=STYLE_CHOICES,
|
|
default='friendly')
|
|
|
|
def restore_object(self, attrs, instance=None):
|
|
"""
|
|
Create or update a new snippet instance, given a dictionary
|
|
of deserialized field values.
|
|
|
|
Note that if we don't define this method, then deserializing
|
|
data will simply return a dictionary of items.
|
|
"""
|
|
if instance:
|
|
# Update existing instance
|
|
instance.title = attrs.get('title', instance.title)
|
|
instance.code = attrs.get('code', instance.code)
|
|
instance.linenos = attrs.get('linenos', instance.linenos)
|
|
instance.language = attrs.get('language', instance.language)
|
|
instance.style = attrs.get('style', instance.style)
|
|
return instance
|
|
|
|
# Create new instance
|
|
return Snippet(**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>Notice that we can also use various attributes that would typically be used on form fields, such as <code>widget=widgets.Textarea</code>. These can be used to control how the serializer should render when displayed as an HTML form. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.</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. </p>
|
|
<h2 id="working-with-serializers">Working with Serializers</h2>
|
|
<p>Before we go any further we'll familiarize 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, let's create a couple of code snippets to work with.</p>
|
|
<pre class="prettyprint lang-py"><code>from snippets.models import Snippet
|
|
from snippets.serializers import SnippetSerializer
|
|
from rest_framework.renderers import JSONRenderer
|
|
from rest_framework.parsers import JSONParser
|
|
|
|
snippet = Snippet(code='foo = "bar"\n')
|
|
snippet.save()
|
|
|
|
snippet = Snippet(code='print "hello, world"\n')
|
|
snippet.save()
|
|
</code></pre>
|
|
<p>We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.</p>
|
|
<pre class="prettyprint lang-py"><code>serializer = SnippetSerializer(snippet)
|
|
serializer.data
|
|
# {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
|
|
</code></pre>
|
|
<p>At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into <code>json</code>.</p>
|
|
<pre class="prettyprint lang-py"><code>content = JSONRenderer().render(serializer.data)
|
|
content
|
|
# '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
|
|
</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 = SnippetSerializer(data=data)
|
|
serializer.is_valid()
|
|
# True
|
|
serializer.object
|
|
# <Snippet: Snippet 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>
|
|
<p>We can also serialize querysets instead of model instances. To do so we simply add a <code>many=True</code> flag to the serializer arguments.</p>
|
|
<pre class="prettyprint lang-py"><code>serializer = SnippetSerializer(Snippet.objects.all(), many=True)
|
|
serializer.data
|
|
# [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}]
|
|
</code></pre>
|
|
<h2 id="using-modelserializers">Using ModelSerializers</h2>
|
|
<p>Our <code>SnippetSerializer</code> class is replicating a lot of information that's also contained in the <code>Snippet</code> model. It would be nice if we could keep our code a bit more concise.</p>
|
|
<p>In the same way that Django provides both <code>Form</code> classes and <code>ModelForm</code> classes, REST framework includes both <code>Serializer</code> classes, and <code>ModelSerializer</code> classes.</p>
|
|
<p>Let's look at refactoring our serializer using the <code>ModelSerializer</code> class.
|
|
Open the file <code>snippets/serializers.py</code> again, and edit the <code>SnippetSerializer</code> class.</p>
|
|
<pre class="prettyprint lang-py"><code>class SnippetSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = Snippet
|
|
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
|
|
</code></pre>
|
|
<h2 id="writing-regular-django-views-using-our-serializer">Writing regular Django views using our Serializer</h2>
|
|
<p>Let's see how we can write some API views using our new Serializer class.
|
|
For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.</p>
|
|
<p>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>snippets/views.py</code> file, and add the following.</p>
|
|
<pre class="prettyprint lang-py"><code>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
|
|
from snippets.models import Snippet
|
|
from snippets.serializers import SnippetSerializer
|
|
|
|
class JSONResponse(HttpResponse):
|
|
"""
|
|
An HttpResponse that renders its 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 snippets, or creating a new snippet.</p>
|
|
<pre class="prettyprint lang-py"><code>@csrf_exempt
|
|
def snippet_list(request):
|
|
"""
|
|
List all code snippets, or create a new snippet.
|
|
"""
|
|
if request.method == 'GET':
|
|
snippets = Snippet.objects.all()
|
|
serializer = SnippetSerializer(snippets, many=True)
|
|
return JSONResponse(serializer.data)
|
|
|
|
elif request.method == 'POST':
|
|
data = JSONParser().parse(request)
|
|
serializer = SnippetSerializer(data=data)
|
|
if serializer.is_valid():
|
|
serializer.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 snippet, and can be used to retrieve, update or delete the snippet.</p>
|
|
<pre class="prettyprint lang-py"><code>@csrf_exempt
|
|
def snippet_detail(request, pk):
|
|
"""
|
|
Retrieve, update or delete a code snippet.
|
|
"""
|
|
try:
|
|
snippet = Snippet.objects.get(pk=pk)
|
|
except Snippet.DoesNotExist:
|
|
return HttpResponse(status=404)
|
|
|
|
if request.method == 'GET':
|
|
serializer = SnippetSerializer(snippet)
|
|
return JSONResponse(serializer.data)
|
|
|
|
elif request.method == 'PUT':
|
|
data = JSONParser().parse(request)
|
|
serializer = SnippetSerializer(snippet, data=data)
|
|
if serializer.is_valid():
|
|
serializer.save()
|
|
return JSONResponse(serializer.data)
|
|
else:
|
|
return JSONResponse(serializer.errors, status=400)
|
|
|
|
elif request.method == 'DELETE':
|
|
snippet.delete()
|
|
return HttpResponse(status=204)
|
|
</code></pre>
|
|
<p>Finally we need to wire these views up. Create the <code>snippets/urls.py</code> file:</p>
|
|
<pre class="prettyprint lang-py"><code>from django.conf.urls import patterns, url
|
|
|
|
urlpatterns = patterns('snippets.views',
|
|
url(r'^snippets/$', 'snippet_list'),
|
|
url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail'),
|
|
)
|
|
</code></pre>
|
|
<p>It's worth noting that there are 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>Now we can start up a sample server that serves our snippets.</p>
|
|
<p>Quit out of the shell...</p>
|
|
<pre class="prettyprint lang-py"><code>quit()
|
|
</code></pre>
|
|
<p>...and start up Django's development server.</p>
|
|
<pre class="prettyprint lang-py"><code>python manage.py runserver
|
|
|
|
Validating models...
|
|
|
|
0 errors found
|
|
Django version 1.4.3, using settings 'tutorial.settings'
|
|
Development server is running at http://127.0.0.1:8000/
|
|
Quit the server with CONTROL-C.
|
|
</code></pre>
|
|
<p>In another terminal window, we can test the server.</p>
|
|
<p>We can get a list of all of the snippets.</p>
|
|
<pre class="prettyprint lang-py"><code>curl http://127.0.0.1:8000/snippets/
|
|
|
|
[{"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>Or we can get a particular snippet by referencing its id.</p>
|
|
<pre class="prettyprint lang-py"><code>curl http://127.0.0.1:8000/snippets/2/
|
|
|
|
{"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}
|
|
</code></pre>
|
|
<p>Similarly, you can have the same json displayed by visiting these URLs in a web browser.</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 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 <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://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
|
<script src="http://django-rest-framework.org/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();
|
|
});
|
|
|
|
// Dynamically force sidenav to no higher than browser window
|
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
|
|
|
$(function(){
|
|
$(window).resize(function(){
|
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
|
});
|
|
});
|
|
</script>
|
|
</body></html>
|