diff options
Diffstat (limited to 'tutorial')
| -rw-r--r-- | tutorial/1-serialization.html | 539 | ||||
| -rw-r--r-- | tutorial/1-serialization/index.html | 744 | ||||
| -rw-r--r-- | tutorial/2-requests-and-responses.html | 378 | ||||
| -rw-r--r-- | tutorial/2-requests-and-responses/index.html | 573 | ||||
| -rw-r--r-- | tutorial/3-class-based-views.html | 370 | ||||
| -rw-r--r-- | tutorial/3-class-based-views/index.html | 550 | ||||
| -rw-r--r-- | tutorial/4-authentication-and-permissions.html | 406 | ||||
| -rw-r--r-- | tutorial/4-authentication-and-permissions/index.html | 607 | ||||
| -rw-r--r-- | tutorial/5-relationships-and-hyperlinked-apis.html | 372 | ||||
| -rw-r--r-- | tutorial/5-relationships-and-hyperlinked-apis/index.html | 560 | ||||
| -rw-r--r-- | tutorial/6-viewsets-and-routers.html | 361 | ||||
| -rw-r--r-- | tutorial/6-viewsets-and-routers/index.html | 550 | ||||
| -rw-r--r-- | tutorial/quickstart.html | 380 | ||||
| -rw-r--r-- | tutorial/quickstart/index.html | 571 | 
14 files changed, 4155 insertions, 2806 deletions
| diff --git a/tutorial/1-serialization.html b/tutorial/1-serialization.html deleted file mode 100644 index a94ef276..00000000 --- a/tutorial/1-serialization.html +++ /dev/null @@ -1,539 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -    <meta charset="utf-8"> -    <title>Tutorial 1: Serialization - Django REST framework</title> -    <link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon"> -    <link rel="canonical" href="http://www.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://www.django-rest-framework.org/css/prettify.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet"> -    <link href="http://www.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> -    <style> -span.fusion-wrap a { -  display: block; -  margin-top: 10px; -  color: black; -} - -a.fusion-poweredby { -  display: block; -  margin-top: 10px; -} -@media (max-width: 767px) { -  div.promo {display: none;} -} -</style> -  </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://www.django-rest-framework.org">Django REST framework</a> -          <div class="nav-collapse collapse"> -            <ul class="nav"> -              <li><a href="http://www.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://www.django-rest-framework.org/tutorial/quickstart">Quickstart</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/api-guide/requests">Requests</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/responses">Responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/views">Views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/generic-views">Generic views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/viewsets">Viewsets</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/routers">Routers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/parsers">Parsers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/renderers">Renderers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/serializers">Serializers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/fields">Serializer fields</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/relations">Serializer relations</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/authentication">Authentication</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/permissions">Permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/throttling">Throttling</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/filtering">Filtering</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/pagination">Pagination</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/reverse">Returning URLs</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/exceptions">Exceptions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/status-codes">Status codes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/testing">Testing</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browsable-api">The Browsable API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/third-party-resources">Third Party Resources</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/contributing">Contributing to REST framework</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.4-announcement">2.4 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/kickstarter-announcement">Kickstarter Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/release-notes">Release Notes</a></li> -                  <li><a href="http://www.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 class="promo"> -               -              </div> -</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 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"> -virtualenv env -source env/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 = [ -    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 makemigrations snippets -python manage.py migrate</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 to 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 the 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># This import will use either `StringIO.StringIO` or `io.BytesIO` -# as appropriate, depending on if we're running Python 2 or Python 3. -from rest_framework.compat import BytesIO - -stream = BytesIO(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) -        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) -        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 -from snippets import views - -urlpatterns = [ -    url(r'^snippets/$', views.snippet_list), -    url(r'^snippets/(?P<pk>[0-9]+)/$', views.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://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script> -    <script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script> -    <script src="http://www.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> diff --git a/tutorial/1-serialization/index.html b/tutorial/1-serialization/index.html new file mode 100644 index 00000000..e861ac0a --- /dev/null +++ b/tutorial/1-serialization/index.html @@ -0,0 +1,744 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> +  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> +  <meta charset="utf-8"> +  <title>1 - Serialization - Django REST framework</title> +  <link href="../../img/favicon.ico" rel="icon" type="image/x-icon"> +  <link rel="canonical" href="http://www.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, 1 - Serialization"> +  <meta name="author" content="Tom Christie"> + +  <!-- Le styles --> +  <link href="../../css/prettify.css" rel="stylesheet"> +  <link href="../../css/bootstrap.css" rel="stylesheet"> +  <link href="../../css/bootstrap-responsive.css" rel="stylesheet"> +  <link href="../../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> + +  <style> +    span.fusion-wrap a { +      display: block; +      margin-top: 10px; +      color: black; +    } +    a.fusion-poweredby { +      display: block; +      margin-top: 10px; +    } +    @media (max-width: 767px) { +      div.promo { +        display: none; +      } +    } +  </style> +</head> +<body onload="prettyPrint()" class="-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 " rel="prev" href="../2-requests-and-responses"> +            Next <i class="icon-arrow-right icon-white"></i> +          </a> +          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../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://www.django-rest-framework.org">Django REST framework</a> +          <div class="nav-collapse collapse"> +             +            <!-- Main navigation --> +            <ul class="nav navbar-nav"> +              <li ><a href="/">Home</a></li> +                +              <li class="dropdown active"> +                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a> +                <ul class="dropdown-menu"> +                   +                  <li > +                    <a href="../quickstart">Quickstart</a> +                  </li> +                   +                  <li class="active" > +                    <a href=".">1 - Serialization</a> +                  </li> +                   +                  <li > +                    <a href="../2-requests-and-responses">2 - Requests and responses</a> +                  </li> +                   +                  <li > +                    <a href="../3-class-based-views">3 - Class based views</a> +                  </li> +                   +                  <li > +                    <a href="../4-authentication-and-permissions">4 - Authentication and permissions</a> +                  </li> +                   +                  <li > +                    <a href="../5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a> +                  </li> +                   +                  <li > +                    <a href="../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="../../api-guide/requests">Requests</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/responses">Responses</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/views">Views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/generic-views">Generic views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/viewsets">Viewsets</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/routers">Routers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/parsers">Parsers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/renderers">Renderers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/serializers">Serializers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/fields">Serializer fields</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/relations">Serializer relations</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/validators">Validators</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/authentication">Authentication</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/permissions">Permissions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/throttling">Throttling</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/filtering">Filtering</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/pagination">Pagination</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/content-negotiation">Content negotiation</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/format-suffixes">Format suffixes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/reverse">Returning URLs</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/exceptions">Exceptions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/status-codes">Status codes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/testing">Testing</a> +                  </li> +                   +                  <li > +                    <a href="../../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="../../topics/documenting-your-api">Documenting your API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/ajax-csrf-cors">AJAX, CSRF & CORS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browser-enhancements">Browser enhancements</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browsable-api">The Browsable API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/third-party-resources">Third Party Resources</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/contributing">Contributing to REST framework</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-framework-2-announcement">2.0 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.2-announcement">2.2 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.3-announcement">2.3 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.4-announcement">2.4 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/kickstarter-announcement">Kickstarter Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/release-notes">Release Notes</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/credits">Credits</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> +                   + +                 + +                 + +              </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 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><code>:::bash +virtualenv env +source env/bin/activate +</code></pre> +<p>Now that we're inside a virtualenv environment, we can install our package requirements.</p> +<pre><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><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><code>python manage.py startapp snippets +</code></pre> +<p>We'll need to add our new <code>snippets</code> app and the <code>rest_framework</code> app to <code>INSTALLED_APPS</code>. Let's edit the <code>tutorial/settings.py</code> file:</p> +<pre><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><code>urlpatterns = [ +    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/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><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>We'll also need to create an initial migration for our snippet model, and sync the database for the first time.</p> +<pre><code>python manage.py makemigrations snippets +python manage.py migrate +</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 to 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><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.IntegerField(read_only=True) +    title = serializers.CharField(required=False, +                                  max_length=100) +    code = serializers.CharField(style={'type': 'textarea'}) +    linenos = serializers.BooleanField(required=False) +    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, +                                       default='python') +    style = serializers.ChoiceField(choices=STYLE_CHOICES, +                                    default='friendly') + +    def create(self, validated_attrs): +        """ +        Create and return a new `Snippet` instance, given the validated data. +        """ +        return Snippet.objects.create(**validated_attrs) + +    def update(self, instance, validated_attrs): +        """ +        Update and return an existing `Snippet` instance, given the validated data. +        """ +        instance.title = validated_attrs.get('title', instance.title) +        instance.code = validated_attrs.get('code', instance.code) +        instance.linenos = validated_attrs.get('linenos', instance.linenos) +        instance.language = validated_attrs.get('language', instance.language) +        instance.style = validated_attrs.get('style', instance.style) +        instance.save() +        return instance +</code></pre> +<p>The first part of the serializer class defines the fields that get serialized/deserialized.  The <code>create()</code> and <code>update()</code> methods define how fully fledged instances are created or modified when calling <code>serializer.save()</code></p> +<p>A serializer class is very similar to a Django <code>Form</code> class, and includes similar validation flags on the various fields, such as <code>required</code>, <code>max_length</code> and <code>default</code>.</p> +<p>The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The <code>style={'type': 'textarea'}</code> flag above is equivelent to using <code>widget=widgets.Textarea</code> on a Django <code>Form</code> class. 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><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><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><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><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><code># This import will use either `StringIO.StringIO` or `io.BytesIO` +# as appropriate, depending on if we're running Python 2 or Python 3. +from rest_framework.compat import BytesIO + +stream = BytesIO(content) +data = JSONParser().parse(stream) +</code></pre> +<p>...then we restore those native datatypes into to a fully populated object instance.</p> +<pre><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><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><code>class SnippetSerializer(serializers.ModelSerializer): +    class Meta: +        model = Snippet +        fields = ('id', 'title', 'code', 'linenos', 'language', 'style') +</code></pre> +<p>Once nice property that serializers have is that you can inspect all the fields an serializer instance, by printing it's representation. Open the Django shell with <code>python manange.py shell</code>, then try the following:</p> +<pre><code>>>> from snippets.serializers import SnippetSerializer +>>> serializer = SnippetSerializer() +>>> print repr(serializer)  # In python 3 use `print(repr(serializer))` +SnippetSerializer(): +    id = IntegerField(label='ID', read_only=True) +    title = CharField(allow_blank=True, max_length=100, required=False) +    code = CharField(style={'type': 'textarea'}) +    linenos = BooleanField(required=False) +    language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... +    style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... +</code></pre> +<p>It's important to remember that <code>ModelSerializer</code> classes don't do anything particularly magically, they are simply a shortcut to creating a serializer class with:</p> +<ul> +<li>An automatically determined set of fields.</li> +<li>Simple default implementations for the <code>create()</code> and <code>update()</code> methods.</li> +</ul> +<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><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><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) +        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><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) +        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><code>from django.conf.urls import patterns, url +from snippets import views + +urlpatterns = [ +    url(r'^snippets/$', views.snippet_list), +    url(r'^snippets/(?P<pk>[0-9]+)/$', views.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><code>quit() +</code></pre> +<p>...and start up Django's development server.</p> +<pre><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><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><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="../../js/jquery-1.8.1-min.js"></script> +  <script src="../../js/prettify-1.0.js"></script> +  <script src="../../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>
\ No newline at end of file diff --git a/tutorial/2-requests-and-responses.html b/tutorial/2-requests-and-responses.html deleted file mode 100644 index 8add5464..00000000 --- a/tutorial/2-requests-and-responses.html +++ /dev/null @@ -1,378 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -    <meta charset="utf-8"> -    <title>Tutorial 2: Requests and Responses - Django REST framework</title> -    <link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon"> -    <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses"/> -    <meta name="viewport" content="width=device-width, initial-scale=1.0"> -    <meta name="description" content="Django, API, REST, Tutorial 2: Requests and Responses"> -    <meta name="author" content="Tom Christie"> - -    <!-- Le styles --> -    <link href="http://www.django-rest-framework.org/css/prettify.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet"> -    <link href="http://www.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> -    <style> -span.fusion-wrap a { -  display: block; -  margin-top: 10px; -  color: black; -} - -a.fusion-poweredby { -  display: block; -  margin-top: 10px; -} -@media (max-width: 767px) { -  div.promo {display: none;} -} -</style> -  </head> -  <body onload="prettyPrint()" class="2-requests-and-responses-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/3-class-based-views">Next <i class="icon-arrow-right icon-white"></i></a> -            <a class="repo-link btn btn-inverse btn-small " href="../tutorial/1-serialization"><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://www.django-rest-framework.org">Django REST framework</a> -          <div class="nav-collapse collapse"> -            <ul class="nav"> -              <li><a href="http://www.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://www.django-rest-framework.org/tutorial/quickstart">Quickstart</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/api-guide/requests">Requests</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/responses">Responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/views">Views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/generic-views">Generic views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/viewsets">Viewsets</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/routers">Routers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/parsers">Parsers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/renderers">Renderers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/serializers">Serializers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/fields">Serializer fields</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/relations">Serializer relations</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/authentication">Authentication</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/permissions">Permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/throttling">Throttling</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/filtering">Filtering</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/pagination">Pagination</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/reverse">Returning URLs</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/exceptions">Exceptions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/status-codes">Status codes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/testing">Testing</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browsable-api">The Browsable API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/third-party-resources">Third Party Resources</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/contributing">Contributing to REST framework</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.4-announcement">2.4 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/kickstarter-announcement">Kickstarter Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/release-notes">Release Notes</a></li> -                  <li><a href="http://www.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-2-requests-and-responses">Tutorial 2: Requests and Responses</a></li> -<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> - -              <div class="promo"> -               -              </div> -</ul> - -            </div> -          </div> - -          <div id="main-content" class="span9"> -            <h1 id="tutorial-2-requests-and-responses">Tutorial 2: Requests and Responses</h1> -<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 introduces a <code>Request</code> object that extends the regular <code>HttpRequest</code>, and provides more flexible request parsing.  The core functionality of the <code>Request</code> object is the <code>request.DATA</code> attribute, which is similar to <code>request.POST</code>, but more useful for working with Web APIs.</p> -<pre class="prettyprint lang-py"><code>request.POST  # Only handles form data.  Only works for 'POST' method. -request.DATA  # Handles arbitrary data.  Works for 'POST', 'PUT' and 'PATCH' methods. -</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> -<pre class="prettyprint lang-py"><code>return Response(data)  # Renders to content type as requested by the client. -</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> -<p>These wrappers provide a few bits of functionality such as making sure you receive <code>Request</code> instances in your view, and adding context to <code>Response</code> objects so that content negotiation can be performed.</p> -<p>The wrappers also provide behaviour such as returning <code>405 Method Not Allowed</code> responses when appropriate, and handling any <code>ParseError</code> 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> -<p>We don't need our <code>JSONResponse</code> class in <code>views.py</code> anymore, so go ahead and delete that.  Once that's done we can start refactoring our views slightly.</p> -<pre class="prettyprint lang-py"><code>from rest_framework import status -from rest_framework.decorators import api_view -from rest_framework.response import Response -from snippets.models import Snippet -from snippets.serializers import SnippetSerializer - - -@api_view(['GET', 'POST']) -def snippet_list(request): -    """ -    List all snippets, or create a new snippet. -    """ -    if request.method == 'GET': -        snippets = Snippet.objects.all() -        serializer = SnippetSerializer(snippets, many=True) -        return Response(serializer.data) - -    elif request.method == 'POST': -        serializer = SnippetSerializer(data=request.DATA) -        if serializer.is_valid(): -            serializer.save() -            return Response(serializer.data, status=status.HTTP_201_CREATED) -        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -</code></pre> -<p>Our instance view is an improvement over the previous example.  It's a little more concise, and the code now feels very similar to if we were working with the Forms API.  We're also using named status codes, which makes the response meanings more obvious.</p> -<p>Here is the view for an individual snippet, in the <code>views.py</code> module.</p> -<pre class="prettyprint lang-py"><code>@api_view(['GET', 'PUT', 'DELETE']) -def snippet_detail(request, pk): -    """ -    Retrieve, update or delete a snippet instance. -    """ -    try: -        snippet = Snippet.objects.get(pk=pk) -    except Snippet.DoesNotExist: -        return Response(status=status.HTTP_404_NOT_FOUND) - -    if request.method == 'GET': -        serializer = SnippetSerializer(snippet) -        return Response(serializer.data) - -    elif request.method == 'PUT': -        serializer = SnippetSerializer(snippet, data=request.DATA) -        if serializer.is_valid(): -            serializer.save() -            return Response(serializer.data) -        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - -    elif request.method == 'DELETE': -        snippet.delete() -        return Response(status=status.HTTP_204_NO_CONTENT) -</code></pre> -<p>This should all feel very familiar - it is not a lot different from working with regular Django views.</p> -<p>Notice that we're no longer explicitly tying our requests or responses to a given content type.  <code>request.DATA</code> can handle incoming <code>json</code> requests, but it can also handle <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> -<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> -<p>Start by adding a <code>format</code> keyword argument to both of the views, like so.</p> -<pre class="prettyprint lang-py"><code>def snippet_list(request, format=None): -</code></pre> -<p>and</p> -<pre class="prettyprint lang-py"><code>def snippet_detail(request, pk, format=None): -</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> -<pre class="prettyprint lang-py"><code>from django.conf.urls import patterns, url -from rest_framework.urlpatterns import format_suffix_patterns -from snippets import views - -urlpatterns = [ -    url(r'^snippets/$', views.snippet_list), -    url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail), -] - -urlpatterns = format_suffix_patterns(urlpatterns) -</code></pre> -<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> -<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> -<p>We can get a list of all of the snippets, as before.</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>We can control the format of the response that we get back, either by using the <code>Accept</code> header:</p> -<pre class="prettyprint lang-py"><code>curl http://127.0.0.1:8000/snippets/ -H 'Accept: application/json'  # Request JSON -curl http://127.0.0.1:8000/snippets/ -H 'Accept: text/html'         # Request HTML -</code></pre> -<p>Or by appending a format suffix:</p> -<pre class="prettyprint lang-py"><code>curl http://127.0.0.1:8000/snippets/.json  # JSON suffix -curl http://127.0.0.1:8000/snippets/.api   # Browsable API suffix -</code></pre> -<p>Similarly, we can control the format of the request that we send, using the <code>Content-Type</code> header.</p> -<pre class="prettyprint lang-py"><code># POST using form data -curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123" - -{"id": 3, "title": "", "code": "print 123", "linenos": false, "language": "python", "style": "friendly"} - -# POST using JSON -curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json" - -{"id": 4, "title": "", "code": "print 456", "linenos": true, "language": "python", "style": "friendly"} -</code></pre> -<p>Now go and open the API in a web browser, by visiting <a href="http://127.0.0.1:8000/snippets/">http://127.0.0.1:8000/snippets/</a>.</p> -<h3 id="browsability">Browsability</h3> -<p>Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser.  This allows for the API to return a fully web-browsable HTML representation.</p> -<p>Having a web-browsable API is a huge usability win, and makes developing and using your API much easier.  It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.</p> -<p>See the <a href="../topics/browsable-api">browsable api</a> topic for more information about the browsable API feature and how to customize it.</p> -<h2 id="whats-next">What's next?</h2> -<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> -          </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://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script> -    <script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script> -    <script src="http://www.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> diff --git a/tutorial/2-requests-and-responses/index.html b/tutorial/2-requests-and-responses/index.html new file mode 100644 index 00000000..aab35769 --- /dev/null +++ b/tutorial/2-requests-and-responses/index.html @@ -0,0 +1,573 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> +  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> +  <meta charset="utf-8"> +  <title>2 - Requests and responses - Django REST framework</title> +  <link href="../../img/favicon.ico" rel="icon" type="image/x-icon"> +  <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses/" /> +  <meta name="viewport" content="width=device-width, initial-scale=1.0"> +  <meta name="description" content="Django, API, REST, 2 - Requests and responses"> +  <meta name="author" content="Tom Christie"> + +  <!-- Le styles --> +  <link href="../../css/prettify.css" rel="stylesheet"> +  <link href="../../css/bootstrap.css" rel="stylesheet"> +  <link href="../../css/bootstrap-responsive.css" rel="stylesheet"> +  <link href="../../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> + +  <style> +    span.fusion-wrap a { +      display: block; +      margin-top: 10px; +      color: black; +    } +    a.fusion-poweredby { +      display: block; +      margin-top: 10px; +    } +    @media (max-width: 767px) { +      div.promo { +        display: none; +      } +    } +  </style> +</head> +<body onload="prettyPrint()" class="-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 " rel="prev" href="../3-class-based-views"> +            Next <i class="icon-arrow-right icon-white"></i> +          </a> +          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../1-serialization"> +            <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://www.django-rest-framework.org">Django REST framework</a> +          <div class="nav-collapse collapse"> +             +            <!-- Main navigation --> +            <ul class="nav navbar-nav"> +              <li ><a href="/">Home</a></li> +                +              <li class="dropdown active"> +                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a> +                <ul class="dropdown-menu"> +                   +                  <li > +                    <a href="../quickstart">Quickstart</a> +                  </li> +                   +                  <li > +                    <a href="../1-serialization">1 - Serialization</a> +                  </li> +                   +                  <li class="active" > +                    <a href=".">2 - Requests and responses</a> +                  </li> +                   +                  <li > +                    <a href="../3-class-based-views">3 - Class based views</a> +                  </li> +                   +                  <li > +                    <a href="../4-authentication-and-permissions">4 - Authentication and permissions</a> +                  </li> +                   +                  <li > +                    <a href="../5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a> +                  </li> +                   +                  <li > +                    <a href="../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="../../api-guide/requests">Requests</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/responses">Responses</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/views">Views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/generic-views">Generic views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/viewsets">Viewsets</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/routers">Routers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/parsers">Parsers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/renderers">Renderers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/serializers">Serializers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/fields">Serializer fields</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/relations">Serializer relations</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/validators">Validators</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/authentication">Authentication</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/permissions">Permissions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/throttling">Throttling</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/filtering">Filtering</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/pagination">Pagination</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/content-negotiation">Content negotiation</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/format-suffixes">Format suffixes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/reverse">Returning URLs</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/exceptions">Exceptions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/status-codes">Status codes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/testing">Testing</a> +                  </li> +                   +                  <li > +                    <a href="../../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="../../topics/documenting-your-api">Documenting your API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/ajax-csrf-cors">AJAX, CSRF & CORS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browser-enhancements">Browser enhancements</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browsable-api">The Browsable API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/third-party-resources">Third Party Resources</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/contributing">Contributing to REST framework</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-framework-2-announcement">2.0 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.2-announcement">2.2 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.3-announcement">2.3 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.4-announcement">2.4 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/kickstarter-announcement">Kickstarter Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/release-notes">Release Notes</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/credits">Credits</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-2-requests-and-responses">Tutorial 2: Requests and Responses</a> +                  </li> + +                   +                    <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> +                   + +                 + +                 + +              </ul> + +            </div> +          </div> + +          <div id="main-content" class="span9"> +             + +            <h1 id="tutorial-2-requests-and-responses">Tutorial 2: Requests and Responses</h1> +<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 introduces a <code>Request</code> object that extends the regular <code>HttpRequest</code>, and provides more flexible request parsing.  The core functionality of the <code>Request</code> object is the <code>request.DATA</code> attribute, which is similar to <code>request.POST</code>, but more useful for working with Web APIs.</p> +<pre><code>request.POST  # Only handles form data.  Only works for 'POST' method. +request.DATA  # Handles arbitrary data.  Works for 'POST', 'PUT' and 'PATCH' methods. +</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> +<pre><code>return Response(data)  # Renders to content type as requested by the client. +</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> +<p>These wrappers provide a few bits of functionality such as making sure you receive <code>Request</code> instances in your view, and adding context to <code>Response</code> objects so that content negotiation can be performed.</p> +<p>The wrappers also provide behaviour such as returning <code>405 Method Not Allowed</code> responses when appropriate, and handling any <code>ParseError</code> 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> +<p>We don't need our <code>JSONResponse</code> class in <code>views.py</code> anymore, so go ahead and delete that.  Once that's done we can start refactoring our views slightly.</p> +<pre><code>from rest_framework import status +from rest_framework.decorators import api_view +from rest_framework.response import Response +from snippets.models import Snippet +from snippets.serializers import SnippetSerializer + + +@api_view(['GET', 'POST']) +def snippet_list(request): +    """ +    List all snippets, or create a new snippet. +    """ +    if request.method == 'GET': +        snippets = Snippet.objects.all() +        serializer = SnippetSerializer(snippets, many=True) +        return Response(serializer.data) + +    elif request.method == 'POST': +        serializer = SnippetSerializer(data=request.DATA) +        if serializer.is_valid(): +            serializer.save() +            return Response(serializer.data, status=status.HTTP_201_CREATED) +        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) +</code></pre> +<p>Our instance view is an improvement over the previous example.  It's a little more concise, and the code now feels very similar to if we were working with the Forms API.  We're also using named status codes, which makes the response meanings more obvious.</p> +<p>Here is the view for an individual snippet, in the <code>views.py</code> module.</p> +<pre><code>@api_view(['GET', 'PUT', 'DELETE']) +def snippet_detail(request, pk): +    """ +    Retrieve, update or delete a snippet instance. +    """ +    try: +        snippet = Snippet.objects.get(pk=pk) +    except Snippet.DoesNotExist: +        return Response(status=status.HTTP_404_NOT_FOUND) + +    if request.method == 'GET': +        serializer = SnippetSerializer(snippet) +        return Response(serializer.data) + +    elif request.method == 'PUT': +        serializer = SnippetSerializer(snippet, data=request.DATA) +        if serializer.is_valid(): +            serializer.save() +            return Response(serializer.data) +        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + +    elif request.method == 'DELETE': +        snippet.delete() +        return Response(status=status.HTTP_204_NO_CONTENT) +</code></pre> +<p>This should all feel very familiar - it is not a lot different from working with regular Django views.</p> +<p>Notice that we're no longer explicitly tying our requests or responses to a given content type.  <code>request.DATA</code> can handle incoming <code>json</code> requests, but it can also handle <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> +<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> +<p>Start by adding a <code>format</code> keyword argument to both of the views, like so.</p> +<pre><code>def snippet_list(request, format=None): +</code></pre> +<p>and</p> +<pre><code>def snippet_detail(request, pk, format=None): +</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> +<pre><code>from django.conf.urls import patterns, url +from rest_framework.urlpatterns import format_suffix_patterns +from snippets import views + +urlpatterns = [ +    url(r'^snippets/$', views.snippet_list), +    url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail), +] + +urlpatterns = format_suffix_patterns(urlpatterns) +</code></pre> +<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> +<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> +<p>We can get a list of all of the snippets, as before.</p> +<pre><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>We can control the format of the response that we get back, either by using the <code>Accept</code> header:</p> +<pre><code>curl http://127.0.0.1:8000/snippets/ -H 'Accept: application/json'  # Request JSON +curl http://127.0.0.1:8000/snippets/ -H 'Accept: text/html'         # Request HTML +</code></pre> +<p>Or by appending a format suffix:</p> +<pre><code>curl http://127.0.0.1:8000/snippets/.json  # JSON suffix +curl http://127.0.0.1:8000/snippets/.api   # Browsable API suffix +</code></pre> +<p>Similarly, we can control the format of the request that we send, using the <code>Content-Type</code> header.</p> +<pre><code># POST using form data +curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123" + +{"id": 3, "title": "", "code": "print 123", "linenos": false, "language": "python", "style": "friendly"} + +# POST using JSON +curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json" + +{"id": 4, "title": "", "code": "print 456", "linenos": true, "language": "python", "style": "friendly"} +</code></pre> +<p>Now go and open the API in a web browser, by visiting <a href="http://127.0.0.1:8000/snippets/">http://127.0.0.1:8000/snippets/</a>.</p> +<h3 id="browsability">Browsability</h3> +<p>Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser.  This allows for the API to return a fully web-browsable HTML representation.</p> +<p>Having a web-browsable API is a huge usability win, and makes developing and using your API much easier.  It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.</p> +<p>See the <a href="../../topics/browsable-api">browsable api</a> topic for more information about the browsable API feature and how to customize it.</p> +<h2 id="whats-next">What's next?</h2> +<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> + +          </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="../../js/jquery-1.8.1-min.js"></script> +  <script src="../../js/prettify-1.0.js"></script> +  <script src="../../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>
\ No newline at end of file diff --git a/tutorial/3-class-based-views.html b/tutorial/3-class-based-views.html deleted file mode 100644 index c8a1d728..00000000 --- a/tutorial/3-class-based-views.html +++ /dev/null @@ -1,370 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -    <meta charset="utf-8"> -    <title>Tutorial 3: Class Based Views - Django REST framework</title> -    <link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon"> -    <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/3-class-based-views"/> -    <meta name="viewport" content="width=device-width, initial-scale=1.0"> -    <meta name="description" content="Django, API, REST, Tutorial 3: Class Based Views"> -    <meta name="author" content="Tom Christie"> - -    <!-- Le styles --> -    <link href="http://www.django-rest-framework.org/css/prettify.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet"> -    <link href="http://www.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> -    <style> -span.fusion-wrap a { -  display: block; -  margin-top: 10px; -  color: black; -} - -a.fusion-poweredby { -  display: block; -  margin-top: 10px; -} -@media (max-width: 767px) { -  div.promo {display: none;} -} -</style> -  </head> -  <body onload="prettyPrint()" class="3-class-based-views-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/4-authentication-and-permissions">Next <i class="icon-arrow-right icon-white"></i></a> -            <a class="repo-link btn btn-inverse btn-small " href="../tutorial/2-requests-and-responses"><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://www.django-rest-framework.org">Django REST framework</a> -          <div class="nav-collapse collapse"> -            <ul class="nav"> -              <li><a href="http://www.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://www.django-rest-framework.org/tutorial/quickstart">Quickstart</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/api-guide/requests">Requests</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/responses">Responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/views">Views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/generic-views">Generic views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/viewsets">Viewsets</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/routers">Routers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/parsers">Parsers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/renderers">Renderers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/serializers">Serializers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/fields">Serializer fields</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/relations">Serializer relations</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/authentication">Authentication</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/permissions">Permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/throttling">Throttling</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/filtering">Filtering</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/pagination">Pagination</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/reverse">Returning URLs</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/exceptions">Exceptions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/status-codes">Status codes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/testing">Testing</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browsable-api">The Browsable API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/third-party-resources">Third Party Resources</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/contributing">Contributing to REST framework</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.4-announcement">2.4 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/kickstarter-announcement">Kickstarter Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/release-notes">Release Notes</a></li> -                  <li><a href="http://www.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-3-class-based-views">Tutorial 3: Class Based Views</a></li> -<li><a href="#rewriting-our-api-using-class-based-views">Rewriting our API using class based views</a></li> -<li><a href="#using-mixins">Using mixins</a></li> -<li><a href="#using-generic-class-based-views">Using generic class based views</a></li> - -              <div class="promo"> -               -              </div> -</ul> - -            </div> -          </div> - -          <div id="main-content" class="span9"> -            <h1 id="tutorial-3-class-based-views">Tutorial 3: Class Based Views</h1> -<p>We can also write our API views using class based views, rather than function based views.  As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>.</p> -<h2 id="rewriting-our-api-using-class-based-views">Rewriting our API using class based views</h2> -<p>We'll start by rewriting the root view as a class based view.  All this involves is a little bit of refactoring of <code>views.py</code>.</p> -<pre class="prettyprint lang-py"><code>from snippets.models import Snippet -from snippets.serializers import SnippetSerializer -from django.http import Http404 -from rest_framework.views import APIView -from rest_framework.response import Response -from rest_framework import status - - -class SnippetList(APIView): -    """ -    List all snippets, or create a new snippet. -    """ -    def get(self, request, format=None): -        snippets = Snippet.objects.all() -        serializer = SnippetSerializer(snippets, many=True) -        return Response(serializer.data) - -    def post(self, request, format=None): -        serializer = SnippetSerializer(data=request.DATA) -        if serializer.is_valid(): -            serializer.save() -            return Response(serializer.data, status=status.HTTP_201_CREATED) -        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -</code></pre> -<p>So far, so good.  It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods.  We'll also need to update the instance view in <code>views.py</code>.</p> -<pre class="prettyprint lang-py"><code>class SnippetDetail(APIView): -    """ -    Retrieve, update or delete a snippet instance. -    """ -    def get_object(self, pk): -        try: -            return Snippet.objects.get(pk=pk) -        except Snippet.DoesNotExist: -            raise Http404 - -    def get(self, request, pk, format=None): -        snippet = self.get_object(pk) -        serializer = SnippetSerializer(snippet) -        return Response(serializer.data) - -    def put(self, request, pk, format=None): -        snippet = self.get_object(pk) -        serializer = SnippetSerializer(snippet, data=request.DATA) -        if serializer.is_valid(): -            serializer.save() -            return Response(serializer.data) -        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - -    def delete(self, request, pk, format=None): -        snippet = self.get_object(pk) -        snippet.delete() -        return Response(status=status.HTTP_204_NO_CONTENT) -</code></pre> -<p>That's looking good.  Again, it's still pretty similar to the function based view right now.</p> -<p>We'll also need to refactor our <code>urls.py</code> slightly now we're using class based views.</p> -<pre class="prettyprint lang-py"><code>from django.conf.urls import patterns, url -from rest_framework.urlpatterns import format_suffix_patterns -from snippets import views - -urlpatterns = [ -    url(r'^snippets/$', views.SnippetList.as_view()), -    url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()), -] - -urlpatterns = format_suffix_patterns(urlpatterns) -</code></pre> -<p>Okay, we're done.  If you run the development server everything should be working just as before.</p> -<h2 id="using-mixins">Using mixins</h2> -<p>One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour.</p> -<p>The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create.  Those bits of common behaviour are implemented in REST framework's mixin classes.</p> -<p>Let's take a look at how we can compose the views by using the mixin classes.  Here's our <code>views.py</code> module again.</p> -<pre class="prettyprint lang-py"><code>from snippets.models import Snippet -from snippets.serializers import SnippetSerializer -from rest_framework import mixins -from rest_framework import generics - -class SnippetList(mixins.ListModelMixin, -                  mixins.CreateModelMixin, -                  generics.GenericAPIView): -    queryset = Snippet.objects.all() -    serializer_class = SnippetSerializer - -    def get(self, request, *args, **kwargs): -        return self.list(request, *args, **kwargs) - -    def post(self, request, *args, **kwargs): -        return self.create(request, *args, **kwargs) -</code></pre> -<p>We'll take a moment to examine exactly what's happening here.  We're building our view using <code>GenericAPIView</code>, and adding in <code>ListModelMixin</code> and <code>CreateModelMixin</code>.</p> -<p>The base class provides the core functionality, and the mixin classes provide the <code>.list()</code> and <code>.create()</code> actions.  We're then explicitly binding the <code>get</code> and <code>post</code> methods to the appropriate actions.  Simple enough stuff so far.</p> -<pre class="prettyprint lang-py"><code>class SnippetDetail(mixins.RetrieveModelMixin, -                    mixins.UpdateModelMixin, -                    mixins.DestroyModelMixin, -                    generics.GenericAPIView): -    queryset = Snippet.objects.all() -    serializer_class = SnippetSerializer - -    def get(self, request, *args, **kwargs): -        return self.retrieve(request, *args, **kwargs) - -    def put(self, request, *args, **kwargs): -        return self.update(request, *args, **kwargs) - -    def delete(self, request, *args, **kwargs): -        return self.destroy(request, *args, **kwargs) -</code></pre> -<p>Pretty similar.  Again we're using the <code>GenericAPIView</code> class to provide the core functionality, and adding in mixins to provide the <code>.retrieve()</code>, <code>.update()</code> and <code>.destroy()</code> actions.</p> -<h2 id="using-generic-class-based-views">Using generic class based views</h2> -<p>Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further.  REST framework provides a set of already mixed-in generic views that we can use to trim down our <code>views.py</code> module even more.</p> -<pre class="prettyprint lang-py"><code>from snippets.models import Snippet -from snippets.serializers import SnippetSerializer -from rest_framework import generics - - -class SnippetList(generics.ListCreateAPIView): -    queryset = Snippet.objects.all() -    serializer_class = SnippetSerializer - - -class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): -    queryset = Snippet.objects.all() -    serializer_class = SnippetSerializer -</code></pre> -<p>Wow, that's pretty concise.  We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.</p> -<p>Next we'll move onto <a href="4-authentication-and-permissions">part 4 of the tutorial</a>, where we'll take a look at how we can deal with authentication and permissions for our API.</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://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script> -    <script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script> -    <script src="http://www.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> diff --git a/tutorial/3-class-based-views/index.html b/tutorial/3-class-based-views/index.html new file mode 100644 index 00000000..43358478 --- /dev/null +++ b/tutorial/3-class-based-views/index.html @@ -0,0 +1,550 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> +  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> +  <meta charset="utf-8"> +  <title>3 - Class based views - Django REST framework</title> +  <link href="../../img/favicon.ico" rel="icon" type="image/x-icon"> +  <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/3-class-based-views/" /> +  <meta name="viewport" content="width=device-width, initial-scale=1.0"> +  <meta name="description" content="Django, API, REST, 3 - Class based views"> +  <meta name="author" content="Tom Christie"> + +  <!-- Le styles --> +  <link href="../../css/prettify.css" rel="stylesheet"> +  <link href="../../css/bootstrap.css" rel="stylesheet"> +  <link href="../../css/bootstrap-responsive.css" rel="stylesheet"> +  <link href="../../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> + +  <style> +    span.fusion-wrap a { +      display: block; +      margin-top: 10px; +      color: black; +    } +    a.fusion-poweredby { +      display: block; +      margin-top: 10px; +    } +    @media (max-width: 767px) { +      div.promo { +        display: none; +      } +    } +  </style> +</head> +<body onload="prettyPrint()" class="-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 " rel="prev" href="../4-authentication-and-permissions"> +            Next <i class="icon-arrow-right icon-white"></i> +          </a> +          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../2-requests-and-responses"> +            <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://www.django-rest-framework.org">Django REST framework</a> +          <div class="nav-collapse collapse"> +             +            <!-- Main navigation --> +            <ul class="nav navbar-nav"> +              <li ><a href="/">Home</a></li> +                +              <li class="dropdown active"> +                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a> +                <ul class="dropdown-menu"> +                   +                  <li > +                    <a href="../quickstart">Quickstart</a> +                  </li> +                   +                  <li > +                    <a href="../1-serialization">1 - Serialization</a> +                  </li> +                   +                  <li > +                    <a href="../2-requests-and-responses">2 - Requests and responses</a> +                  </li> +                   +                  <li class="active" > +                    <a href=".">3 - Class based views</a> +                  </li> +                   +                  <li > +                    <a href="../4-authentication-and-permissions">4 - Authentication and permissions</a> +                  </li> +                   +                  <li > +                    <a href="../5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a> +                  </li> +                   +                  <li > +                    <a href="../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="../../api-guide/requests">Requests</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/responses">Responses</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/views">Views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/generic-views">Generic views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/viewsets">Viewsets</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/routers">Routers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/parsers">Parsers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/renderers">Renderers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/serializers">Serializers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/fields">Serializer fields</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/relations">Serializer relations</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/validators">Validators</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/authentication">Authentication</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/permissions">Permissions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/throttling">Throttling</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/filtering">Filtering</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/pagination">Pagination</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/content-negotiation">Content negotiation</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/format-suffixes">Format suffixes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/reverse">Returning URLs</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/exceptions">Exceptions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/status-codes">Status codes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/testing">Testing</a> +                  </li> +                   +                  <li > +                    <a href="../../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="../../topics/documenting-your-api">Documenting your API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/ajax-csrf-cors">AJAX, CSRF & CORS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browser-enhancements">Browser enhancements</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browsable-api">The Browsable API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/third-party-resources">Third Party Resources</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/contributing">Contributing to REST framework</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-framework-2-announcement">2.0 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.2-announcement">2.2 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.3-announcement">2.3 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.4-announcement">2.4 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/kickstarter-announcement">Kickstarter Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/release-notes">Release Notes</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/credits">Credits</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-3-class-based-views">Tutorial 3: Class Based Views</a> +                  </li> + +                   +                    <li> +                      <a href="#rewriting-our-api-using-class-based-views">Rewriting our API using class based views</a> +                    </li> +                   +                    <li> +                      <a href="#using-mixins">Using mixins</a> +                    </li> +                   +                    <li> +                      <a href="#using-generic-class-based-views">Using generic class based views</a> +                    </li> +                   + +                 + +                 + +              </ul> + +            </div> +          </div> + +          <div id="main-content" class="span9"> +             + +            <h1 id="tutorial-3-class-based-views">Tutorial 3: Class Based Views</h1> +<p>We can also write our API views using class based views, rather than function based views.  As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>.</p> +<h2 id="rewriting-our-api-using-class-based-views">Rewriting our API using class based views</h2> +<p>We'll start by rewriting the root view as a class based view.  All this involves is a little bit of refactoring of <code>views.py</code>.</p> +<pre><code>from snippets.models import Snippet +from snippets.serializers import SnippetSerializer +from django.http import Http404 +from rest_framework.views import APIView +from rest_framework.response import Response +from rest_framework import status + + +class SnippetList(APIView): +    """ +    List all snippets, or create a new snippet. +    """ +    def get(self, request, format=None): +        snippets = Snippet.objects.all() +        serializer = SnippetSerializer(snippets, many=True) +        return Response(serializer.data) + +    def post(self, request, format=None): +        serializer = SnippetSerializer(data=request.DATA) +        if serializer.is_valid(): +            serializer.save() +            return Response(serializer.data, status=status.HTTP_201_CREATED) +        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) +</code></pre> +<p>So far, so good.  It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods.  We'll also need to update the instance view in <code>views.py</code>.</p> +<pre><code>class SnippetDetail(APIView): +    """ +    Retrieve, update or delete a snippet instance. +    """ +    def get_object(self, pk): +        try: +            return Snippet.objects.get(pk=pk) +        except Snippet.DoesNotExist: +            raise Http404 + +    def get(self, request, pk, format=None): +        snippet = self.get_object(pk) +        serializer = SnippetSerializer(snippet) +        return Response(serializer.data) + +    def put(self, request, pk, format=None): +        snippet = self.get_object(pk) +        serializer = SnippetSerializer(snippet, data=request.DATA) +        if serializer.is_valid(): +            serializer.save() +            return Response(serializer.data) +        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + +    def delete(self, request, pk, format=None): +        snippet = self.get_object(pk) +        snippet.delete() +        return Response(status=status.HTTP_204_NO_CONTENT) +</code></pre> +<p>That's looking good.  Again, it's still pretty similar to the function based view right now.</p> +<p>We'll also need to refactor our <code>urls.py</code> slightly now we're using class based views.</p> +<pre><code>from django.conf.urls import patterns, url +from rest_framework.urlpatterns import format_suffix_patterns +from snippets import views + +urlpatterns = [ +    url(r'^snippets/$', views.SnippetList.as_view()), +    url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()), +] + +urlpatterns = format_suffix_patterns(urlpatterns) +</code></pre> +<p>Okay, we're done.  If you run the development server everything should be working just as before.</p> +<h2 id="using-mixins">Using mixins</h2> +<p>One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour.</p> +<p>The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create.  Those bits of common behaviour are implemented in REST framework's mixin classes.</p> +<p>Let's take a look at how we can compose the views by using the mixin classes.  Here's our <code>views.py</code> module again.</p> +<pre><code>from snippets.models import Snippet +from snippets.serializers import SnippetSerializer +from rest_framework import mixins +from rest_framework import generics + +class SnippetList(mixins.ListModelMixin, +                  mixins.CreateModelMixin, +                  generics.GenericAPIView): +    queryset = Snippet.objects.all() +    serializer_class = SnippetSerializer + +    def get(self, request, *args, **kwargs): +        return self.list(request, *args, **kwargs) + +    def post(self, request, *args, **kwargs): +        return self.create(request, *args, **kwargs) +</code></pre> +<p>We'll take a moment to examine exactly what's happening here.  We're building our view using <code>GenericAPIView</code>, and adding in <code>ListModelMixin</code> and <code>CreateModelMixin</code>.</p> +<p>The base class provides the core functionality, and the mixin classes provide the <code>.list()</code> and <code>.create()</code> actions.  We're then explicitly binding the <code>get</code> and <code>post</code> methods to the appropriate actions.  Simple enough stuff so far.</p> +<pre><code>class SnippetDetail(mixins.RetrieveModelMixin, +                    mixins.UpdateModelMixin, +                    mixins.DestroyModelMixin, +                    generics.GenericAPIView): +    queryset = Snippet.objects.all() +    serializer_class = SnippetSerializer + +    def get(self, request, *args, **kwargs): +        return self.retrieve(request, *args, **kwargs) + +    def put(self, request, *args, **kwargs): +        return self.update(request, *args, **kwargs) + +    def delete(self, request, *args, **kwargs): +        return self.destroy(request, *args, **kwargs) +</code></pre> +<p>Pretty similar.  Again we're using the <code>GenericAPIView</code> class to provide the core functionality, and adding in mixins to provide the <code>.retrieve()</code>, <code>.update()</code> and <code>.destroy()</code> actions.</p> +<h2 id="using-generic-class-based-views">Using generic class based views</h2> +<p>Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further.  REST framework provides a set of already mixed-in generic views that we can use to trim down our <code>views.py</code> module even more.</p> +<pre><code>from snippets.models import Snippet +from snippets.serializers import SnippetSerializer +from rest_framework import generics + + +class SnippetList(generics.ListCreateAPIView): +    queryset = Snippet.objects.all() +    serializer_class = SnippetSerializer + + +class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): +    queryset = Snippet.objects.all() +    serializer_class = SnippetSerializer +</code></pre> +<p>Wow, that's pretty concise.  We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.</p> +<p>Next we'll move onto <a href="../4-authentication-and-permissions">part 4 of the tutorial</a>, where we'll take a look at how we can deal with authentication and permissions for our API.</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="../../js/jquery-1.8.1-min.js"></script> +  <script src="../../js/prettify-1.0.js"></script> +  <script src="../../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>
\ No newline at end of file diff --git a/tutorial/4-authentication-and-permissions.html b/tutorial/4-authentication-and-permissions.html deleted file mode 100644 index f72c8930..00000000 --- a/tutorial/4-authentication-and-permissions.html +++ /dev/null @@ -1,406 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -    <meta charset="utf-8"> -    <title>Tutorial 4: Authentication & Permissions - Django REST framework</title> -    <link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon"> -    <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions"/> -    <meta name="viewport" content="width=device-width, initial-scale=1.0"> -    <meta name="description" content="Django, API, REST, Tutorial 4: Authentication & Permissions"> -    <meta name="author" content="Tom Christie"> - -    <!-- Le styles --> -    <link href="http://www.django-rest-framework.org/css/prettify.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet"> -    <link href="http://www.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> -    <style> -span.fusion-wrap a { -  display: block; -  margin-top: 10px; -  color: black; -} - -a.fusion-poweredby { -  display: block; -  margin-top: 10px; -} -@media (max-width: 767px) { -  div.promo {display: none;} -} -</style> -  </head> -  <body onload="prettyPrint()" class="4-authentication-and-permissions-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/5-relationships-and-hyperlinked-apis">Next <i class="icon-arrow-right icon-white"></i></a> -            <a class="repo-link btn btn-inverse btn-small " href="../tutorial/3-class-based-views"><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://www.django-rest-framework.org">Django REST framework</a> -          <div class="nav-collapse collapse"> -            <ul class="nav"> -              <li><a href="http://www.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://www.django-rest-framework.org/tutorial/quickstart">Quickstart</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/api-guide/requests">Requests</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/responses">Responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/views">Views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/generic-views">Generic views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/viewsets">Viewsets</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/routers">Routers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/parsers">Parsers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/renderers">Renderers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/serializers">Serializers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/fields">Serializer fields</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/relations">Serializer relations</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/authentication">Authentication</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/permissions">Permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/throttling">Throttling</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/filtering">Filtering</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/pagination">Pagination</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/reverse">Returning URLs</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/exceptions">Exceptions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/status-codes">Status codes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/testing">Testing</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browsable-api">The Browsable API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/third-party-resources">Third Party Resources</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/contributing">Contributing to REST framework</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.4-announcement">2.4 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/kickstarter-announcement">Kickstarter Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/release-notes">Release Notes</a></li> -                  <li><a href="http://www.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-4-authentication-&-permissions">Tutorial 4: Authentication & Permissions</a></li> -<li><a href="#adding-information-to-our-model">Adding information to our model</a></li> -<li><a href="#adding-endpoints-for-our-user-models">Adding endpoints for our User models</a></li> -<li><a href="#associating-snippets-with-users">Associating Snippets with Users</a></li> -<li><a href="#updating-our-serializer">Updating our serializer</a></li> -<li><a href="#adding-required-permissions-to-views">Adding required permissions to views</a></li> -<li><a href="#adding-login-to-the-browsable-api">Adding login to the Browsable API</a></li> -<li><a href="#object-level-permissions">Object level permissions</a></li> -<li><a href="#authenticating-with-the-api">Authenticating with the API</a></li> -<li><a href="#summary">Summary</a></li> - -              <div class="promo"> -               -              </div> -</ul> - -            </div> -          </div> - -          <div id="main-content" class="span9"> -            <h1 id="tutorial-4-authentication-permissions">Tutorial 4: Authentication & Permissions</h1> -<p>Currently our API doesn't have any restrictions on who can edit or delete code snippets.  We'd like to have some more advanced behavior in order to make sure that:</p> -<ul> -<li>Code snippets are always associated with a creator.</li> -<li>Only authenticated users may create snippets.</li> -<li>Only the creator of a snippet may update or delete it.</li> -<li>Unauthenticated requests should have full read-only access.</li> -</ul> -<h2 id="adding-information-to-our-model">Adding information to our model</h2> -<p>We're going to make a couple of changes to our <code>Snippet</code> model class. -First, let's add a couple of fields.  One of those fields will be used to represent the user who created the code snippet.  The other field will be used to store the highlighted HTML representation of the code.</p> -<p>Add the following two fields to the <code>Snippet</code> model in <code>models.py</code>.</p> -<pre class="prettyprint lang-py"><code>owner = models.ForeignKey('auth.User', related_name='snippets') -highlighted = models.TextField() -</code></pre> -<p>We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the <code>pygments</code> code highlighting library.</p> -<p>We'll need some extra imports:</p> -<pre class="prettyprint lang-py"><code>from pygments.lexers import get_lexer_by_name -from pygments.formatters.html import HtmlFormatter -from pygments import highlight -</code></pre> -<p>And now we can add a <code>.save()</code> method to our model class:</p> -<pre class="prettyprint lang-py"><code>def save(self, *args, **kwargs): -    """ -    Use the `pygments` library to create a highlighted HTML -    representation of the code snippet. -    """ -    lexer = get_lexer_by_name(self.language) -    linenos = self.linenos and 'table' or False -    options = self.title and {'title': self.title} or {} -    formatter = HtmlFormatter(style=self.style, linenos=linenos, -                              full=True, **options) -    self.highlighted = highlight(self.code, lexer, formatter) -    super(Snippet, self).save(*args, **kwargs) -</code></pre> -<p>When that's all done we'll need to update our database tables. -Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.</p> -<pre class="prettyprint lang-py"><code>rm tmp.db -python manage.py syncdb -</code></pre> -<p>You might also want to create a few different users, to use for testing the API.  The quickest way to do this will be with the <code>createsuperuser</code> command.</p> -<pre class="prettyprint lang-py"><code>python manage.py createsuperuser -</code></pre> -<h2 id="adding-endpoints-for-our-user-models">Adding endpoints for our User models</h2> -<p>Now that we've got some users to work with, we'd better add representations of those users to our API.  Creating a new serializer is easy. In <code>serializers.py</code> add:</p> -<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User - -class UserSerializer(serializers.ModelSerializer): -    snippets = serializers.PrimaryKeyRelatedField(many=True) - -    class Meta: -        model = User -        fields = ('id', 'username', 'snippets') -</code></pre> -<p>Because <code>'snippets'</code> is a <em>reverse</em> relationship on the User model, it will not be included by default when using the <code>ModelSerializer</code> class, so we needed to add an explicit field for it.</p> -<p>We'll also add a couple of views to <code>views.py</code>.  We'd like to just use read-only views for the user representations, so we'll use the <code>ListAPIView</code> and <code>RetrieveAPIView</code> generic class based views.</p> -<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User - - -class UserList(generics.ListAPIView): -    queryset = User.objects.all() -    serializer_class = UserSerializer - - -class UserDetail(generics.RetrieveAPIView): -    queryset = User.objects.all() -    serializer_class = UserSerializer -</code></pre> -<p>Make sure to also import the <code>UserSerializer</code> class</p> -<pre class="prettyprint lang-py"><code>from snippets.serializers import UserSerializer -</code></pre> -<p>Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in <code>urls.py</code>.</p> -<pre class="prettyprint lang-py"><code>url(r'^users/$', views.UserList.as_view()), -url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()), -</code></pre> -<h2 id="associating-snippets-with-users">Associating Snippets with Users</h2> -<p>Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance.  The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.</p> -<p>The way we deal with that is by overriding a <code>.pre_save()</code> method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL.</p> -<p>On <strong>both</strong> the <code>SnippetList</code> and <code>SnippetDetail</code> view classes, add the following method:</p> -<pre class="prettyprint lang-py"><code>def pre_save(self, obj): -    obj.owner = self.request.user -</code></pre> -<h2 id="updating-our-serializer">Updating our serializer</h2> -<p>Now that snippets are associated with the user that created them, let's update our <code>SnippetSerializer</code> to reflect that.  Add the following field to the serializer definition in <code>serializers.py</code>:</p> -<pre class="prettyprint lang-py"><code>owner = serializers.Field(source='owner.username') -</code></pre> -<p><strong>Note</strong>: Make sure you also add <code>'owner',</code> to the list of fields in the inner <code>Meta</code> class.</p> -<p>This field is doing something quite interesting.  The <code>source</code> argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance.  It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.</p> -<p>The field we've added is the untyped <code>Field</code> class, in contrast to the other typed fields, such as <code>CharField</code>, <code>BooleanField</code> etc...  The untyped <code>Field</code> is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.</p> -<h2 id="adding-required-permissions-to-views">Adding required permissions to views</h2> -<p>Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.</p> -<p>REST framework includes a number of permission classes that we can use to restrict who can access a given view.  In this case the one we're looking for is <code>IsAuthenticatedOrReadOnly</code>, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.</p> -<p>First add the following import in the views module</p> -<pre class="prettyprint lang-py"><code>from rest_framework import permissions -</code></pre> -<p>Then, add the following property to <strong>both</strong> the <code>SnippetList</code> and <code>SnippetDetail</code> view classes.</p> -<pre class="prettyprint lang-py"><code>permission_classes = (permissions.IsAuthenticatedOrReadOnly,) -</code></pre> -<h2 id="adding-login-to-the-browsable-api">Adding login to the Browsable API</h2> -<p>If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets.  In order to do so we'd need to be able to login as a user.</p> -<p>We can add a login view for use with the browsable API, by editing the URLconf in our project-level <code>urls.py</code> file.</p> -<p>Add the following import at the top of the file:</p> -<pre class="prettyprint lang-py"><code>from django.conf.urls import include -</code></pre> -<p>And, at the end of the file, add a pattern to include the login and logout views for the browsable API.</p> -<pre class="prettyprint lang-py"><code>urlpatterns += [ -    url(r'^api-auth/', include('rest_framework.urls', -                               namespace='rest_framework')), -] -</code></pre> -<p>The <code>r'^api-auth/'</code> part of pattern can actually be whatever URL you want to use.  The only restriction is that the included urls must use the <code>'rest_framework'</code> namespace.</p> -<p>Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page.  If you log in as one of the users you created earlier, you'll be able to create code snippets again.</p> -<p>Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field.</p> -<h2 id="object-level-permissions">Object level permissions</h2> -<p>Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.</p> -<p>To do that we're going to need to create a custom permission.</p> -<p>In the snippets app, create a new file, <code>permissions.py</code></p> -<pre class="prettyprint lang-py"><code>from rest_framework import permissions - - -class IsOwnerOrReadOnly(permissions.BasePermission): -    """ -    Custom permission to only allow owners of an object to edit it. -    """ - -    def has_object_permission(self, request, view, obj): -        # Read permissions are allowed to any request, -        # so we'll always allow GET, HEAD or OPTIONS requests. -        if request.method in permissions.SAFE_METHODS: -            return True - -        # Write permissions are only allowed to the owner of the snippet. -        return obj.owner == request.user -</code></pre> -<p>Now we can add that custom permission to our snippet instance endpoint, by editing the <code>permission_classes</code> property on the <code>SnippetDetail</code> class:</p> -<pre class="prettyprint lang-py"><code>permission_classes = (permissions.IsAuthenticatedOrReadOnly, -                      IsOwnerOrReadOnly,) -</code></pre> -<p>Make sure to also import the <code>IsOwnerOrReadOnly</code> class.</p> -<pre class="prettyprint lang-py"><code>from snippets.permissions import IsOwnerOrReadOnly -</code></pre> -<p>Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.</p> -<h2 id="authenticating-with-the-api">Authenticating with the API</h2> -<p>Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets.  We haven't set up any <a href="../api-guide/authentication">authentication classes</a>, so the defaults are currently applied, which are <code>SessionAuthentication</code> and <code>BasicAuthentication</code>.</p> -<p>When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.</p> -<p>If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.</p> -<p>If we try to create a snippet without authenticating, we'll get an error:</p> -<pre class="prettyprint lang-py"><code>curl -i -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123" - -{"detail": "Authentication credentials were not provided."} -</code></pre> -<p>We can make a successful request by including the username and password of one of the users we created earlier.</p> -<pre class="prettyprint lang-py"><code>curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 789" -u tom:password - -{"id": 5, "owner": "tom", "title": "foo", "code": "print 789", "linenos": false, "language": "python", "style": "friendly"} -</code></pre> -<h2 id="summary">Summary</h2> -<p>We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.</p> -<p>In <a href="5-relationships-and-hyperlinked-apis">part 5</a> of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.</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://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script> -    <script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script> -    <script src="http://www.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> diff --git a/tutorial/4-authentication-and-permissions/index.html b/tutorial/4-authentication-and-permissions/index.html new file mode 100644 index 00000000..90e2d921 --- /dev/null +++ b/tutorial/4-authentication-and-permissions/index.html @@ -0,0 +1,607 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> +  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> +  <meta charset="utf-8"> +  <title>4 - Authentication and permissions - Django REST framework</title> +  <link href="../../img/favicon.ico" rel="icon" type="image/x-icon"> +  <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/" /> +  <meta name="viewport" content="width=device-width, initial-scale=1.0"> +  <meta name="description" content="Django, API, REST, 4 - Authentication and permissions"> +  <meta name="author" content="Tom Christie"> + +  <!-- Le styles --> +  <link href="../../css/prettify.css" rel="stylesheet"> +  <link href="../../css/bootstrap.css" rel="stylesheet"> +  <link href="../../css/bootstrap-responsive.css" rel="stylesheet"> +  <link href="../../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> + +  <style> +    span.fusion-wrap a { +      display: block; +      margin-top: 10px; +      color: black; +    } +    a.fusion-poweredby { +      display: block; +      margin-top: 10px; +    } +    @media (max-width: 767px) { +      div.promo { +        display: none; +      } +    } +  </style> +</head> +<body onload="prettyPrint()" class="-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 " rel="prev" href="../5-relationships-and-hyperlinked-apis"> +            Next <i class="icon-arrow-right icon-white"></i> +          </a> +          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../3-class-based-views"> +            <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://www.django-rest-framework.org">Django REST framework</a> +          <div class="nav-collapse collapse"> +             +            <!-- Main navigation --> +            <ul class="nav navbar-nav"> +              <li ><a href="/">Home</a></li> +                +              <li class="dropdown active"> +                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a> +                <ul class="dropdown-menu"> +                   +                  <li > +                    <a href="../quickstart">Quickstart</a> +                  </li> +                   +                  <li > +                    <a href="../1-serialization">1 - Serialization</a> +                  </li> +                   +                  <li > +                    <a href="../2-requests-and-responses">2 - Requests and responses</a> +                  </li> +                   +                  <li > +                    <a href="../3-class-based-views">3 - Class based views</a> +                  </li> +                   +                  <li class="active" > +                    <a href=".">4 - Authentication and permissions</a> +                  </li> +                   +                  <li > +                    <a href="../5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a> +                  </li> +                   +                  <li > +                    <a href="../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="../../api-guide/requests">Requests</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/responses">Responses</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/views">Views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/generic-views">Generic views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/viewsets">Viewsets</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/routers">Routers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/parsers">Parsers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/renderers">Renderers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/serializers">Serializers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/fields">Serializer fields</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/relations">Serializer relations</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/validators">Validators</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/authentication">Authentication</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/permissions">Permissions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/throttling">Throttling</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/filtering">Filtering</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/pagination">Pagination</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/content-negotiation">Content negotiation</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/format-suffixes">Format suffixes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/reverse">Returning URLs</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/exceptions">Exceptions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/status-codes">Status codes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/testing">Testing</a> +                  </li> +                   +                  <li > +                    <a href="../../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="../../topics/documenting-your-api">Documenting your API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/ajax-csrf-cors">AJAX, CSRF & CORS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browser-enhancements">Browser enhancements</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browsable-api">The Browsable API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/third-party-resources">Third Party Resources</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/contributing">Contributing to REST framework</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-framework-2-announcement">2.0 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.2-announcement">2.2 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.3-announcement">2.3 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.4-announcement">2.4 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/kickstarter-announcement">Kickstarter Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/release-notes">Release Notes</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/credits">Credits</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-4-authentication-permissions">Tutorial 4: Authentication & Permissions</a> +                  </li> + +                   +                    <li> +                      <a href="#adding-information-to-our-model">Adding information to our model</a> +                    </li> +                   +                    <li> +                      <a href="#adding-endpoints-for-our-user-models">Adding endpoints for our User models</a> +                    </li> +                   +                    <li> +                      <a href="#associating-snippets-with-users">Associating Snippets with Users</a> +                    </li> +                   +                    <li> +                      <a href="#updating-our-serializer">Updating our serializer</a> +                    </li> +                   +                    <li> +                      <a href="#adding-required-permissions-to-views">Adding required permissions to views</a> +                    </li> +                   +                    <li> +                      <a href="#adding-login-to-the-browsable-api">Adding login to the Browsable API</a> +                    </li> +                   +                    <li> +                      <a href="#object-level-permissions">Object level permissions</a> +                    </li> +                   +                    <li> +                      <a href="#authenticating-with-the-api">Authenticating with the API</a> +                    </li> +                   +                    <li> +                      <a href="#summary">Summary</a> +                    </li> +                   + +                 + +                 + +              </ul> + +            </div> +          </div> + +          <div id="main-content" class="span9"> +             + +            <h1 id="tutorial-4-authentication-permissions">Tutorial 4: Authentication & Permissions</h1> +<p>Currently our API doesn't have any restrictions on who can edit or delete code snippets.  We'd like to have some more advanced behavior in order to make sure that:</p> +<ul> +<li>Code snippets are always associated with a creator.</li> +<li>Only authenticated users may create snippets.</li> +<li>Only the creator of a snippet may update or delete it.</li> +<li>Unauthenticated requests should have full read-only access.</li> +</ul> +<h2 id="adding-information-to-our-model">Adding information to our model</h2> +<p>We're going to make a couple of changes to our <code>Snippet</code> model class. +First, let's add a couple of fields.  One of those fields will be used to represent the user who created the code snippet.  The other field will be used to store the highlighted HTML representation of the code.</p> +<p>Add the following two fields to the <code>Snippet</code> model in <code>models.py</code>.</p> +<pre><code>owner = models.ForeignKey('auth.User', related_name='snippets') +highlighted = models.TextField() +</code></pre> +<p>We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the <code>pygments</code> code highlighting library.</p> +<p>We'll need some extra imports:</p> +<pre><code>from pygments.lexers import get_lexer_by_name +from pygments.formatters.html import HtmlFormatter +from pygments import highlight +</code></pre> +<p>And now we can add a <code>.save()</code> method to our model class:</p> +<pre><code>def save(self, *args, **kwargs): +    """ +    Use the `pygments` library to create a highlighted HTML +    representation of the code snippet. +    """ +    lexer = get_lexer_by_name(self.language) +    linenos = self.linenos and 'table' or False +    options = self.title and {'title': self.title} or {} +    formatter = HtmlFormatter(style=self.style, linenos=linenos, +                              full=True, **options) +    self.highlighted = highlight(self.code, lexer, formatter) +    super(Snippet, self).save(*args, **kwargs) +</code></pre> +<p>When that's all done we'll need to update our database tables. +Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.</p> +<pre><code>rm tmp.db +rm -r snippets/migrations +python manage.py makemigrations snippets +python manage.py migrate +</code></pre> +<p>You might also want to create a few different users, to use for testing the API.  The quickest way to do this will be with the <code>createsuperuser</code> command.</p> +<pre><code>python manage.py createsuperuser +</code></pre> +<h2 id="adding-endpoints-for-our-user-models">Adding endpoints for our User models</h2> +<p>Now that we've got some users to work with, we'd better add representations of those users to our API.  Creating a new serializer is easy. In <code>serializers.py</code> add:</p> +<pre><code>from django.contrib.auth.models import User + +class UserSerializer(serializers.ModelSerializer): +    snippets = serializers.PrimaryKeyRelatedField(many=True) + +    class Meta: +        model = User +        fields = ('id', 'username', 'snippets') +</code></pre> +<p>Because <code>'snippets'</code> is a <em>reverse</em> relationship on the User model, it will not be included by default when using the <code>ModelSerializer</code> class, so we needed to add an explicit field for it.</p> +<p>We'll also add a couple of views to <code>views.py</code>.  We'd like to just use read-only views for the user representations, so we'll use the <code>ListAPIView</code> and <code>RetrieveAPIView</code> generic class based views.</p> +<pre><code>from django.contrib.auth.models import User + + +class UserList(generics.ListAPIView): +    queryset = User.objects.all() +    serializer_class = UserSerializer + + +class UserDetail(generics.RetrieveAPIView): +    queryset = User.objects.all() +    serializer_class = UserSerializer +</code></pre> +<p>Make sure to also import the <code>UserSerializer</code> class</p> +<pre><code>from snippets.serializers import UserSerializer +</code></pre> +<p>Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in <code>urls.py</code>.</p> +<pre><code>url(r'^users/$', views.UserList.as_view()), +url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()), +</code></pre> +<h2 id="associating-snippets-with-users">Associating Snippets with Users</h2> +<p>Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance.  The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.</p> +<p>The way we deal with that is by overriding a <code>.perform_create()</code> method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.</p> +<p>On the <code>SnippetList</code> view class, add the following method:</p> +<pre><code>def perform_create(self, serializer): +    serializer.save(owner=self.request.user) +</code></pre> +<p>The <code>create()</code> method of our serializer will now be passed an additional <code>'owner'</code> field, along with the validated data from the request.</p> +<h2 id="updating-our-serializer">Updating our serializer</h2> +<p>Now that snippets are associated with the user that created them, let's update our <code>SnippetSerializer</code> to reflect that.  Add the following field to the serializer definition in <code>serializers.py</code>:</p> +<pre><code>owner = serializers.ReadOnlyField(source='owner.username') +</code></pre> +<p><strong>Note</strong>: Make sure you also add <code>'owner',</code> to the list of fields in the inner <code>Meta</code> class.</p> +<p>This field is doing something quite interesting.  The <code>source</code> argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance.  It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.</p> +<p>The field we've added is the untyped <code>ReadOnlyField</code> class, in contrast to the other typed fields, such as <code>CharField</code>, <code>BooleanField</code> etc...  The untyped <code>ReadOnlyField</code> is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used <code>CharField(read_only=True)</code> here.</p> +<h2 id="adding-required-permissions-to-views">Adding required permissions to views</h2> +<p>Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.</p> +<p>REST framework includes a number of permission classes that we can use to restrict who can access a given view.  In this case the one we're looking for is <code>IsAuthenticatedOrReadOnly</code>, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.</p> +<p>First add the following import in the views module</p> +<pre><code>from rest_framework import permissions +</code></pre> +<p>Then, add the following property to <strong>both</strong> the <code>SnippetList</code> and <code>SnippetDetail</code> view classes.</p> +<pre><code>permission_classes = (permissions.IsAuthenticatedOrReadOnly,) +</code></pre> +<h2 id="adding-login-to-the-browsable-api">Adding login to the Browsable API</h2> +<p>If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets.  In order to do so we'd need to be able to login as a user.</p> +<p>We can add a login view for use with the browsable API, by editing the URLconf in our project-level <code>urls.py</code> file.</p> +<p>Add the following import at the top of the file:</p> +<pre><code>from django.conf.urls import include +</code></pre> +<p>And, at the end of the file, add a pattern to include the login and logout views for the browsable API.</p> +<pre><code>urlpatterns += [ +    url(r'^api-auth/', include('rest_framework.urls', +                               namespace='rest_framework')), +] +</code></pre> +<p>The <code>r'^api-auth/'</code> part of pattern can actually be whatever URL you want to use.  The only restriction is that the included urls must use the <code>'rest_framework'</code> namespace.</p> +<p>Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page.  If you log in as one of the users you created earlier, you'll be able to create code snippets again.</p> +<p>Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field.</p> +<h2 id="object-level-permissions">Object level permissions</h2> +<p>Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.</p> +<p>To do that we're going to need to create a custom permission.</p> +<p>In the snippets app, create a new file, <code>permissions.py</code></p> +<pre><code>from rest_framework import permissions + + +class IsOwnerOrReadOnly(permissions.BasePermission): +    """ +    Custom permission to only allow owners of an object to edit it. +    """ + +    def has_object_permission(self, request, view, obj): +        # Read permissions are allowed to any request, +        # so we'll always allow GET, HEAD or OPTIONS requests. +        if request.method in permissions.SAFE_METHODS: +            return True + +        # Write permissions are only allowed to the owner of the snippet. +        return obj.owner == request.user +</code></pre> +<p>Now we can add that custom permission to our snippet instance endpoint, by editing the <code>permission_classes</code> property on the <code>SnippetDetail</code> class:</p> +<pre><code>permission_classes = (permissions.IsAuthenticatedOrReadOnly, +                      IsOwnerOrReadOnly,) +</code></pre> +<p>Make sure to also import the <code>IsOwnerOrReadOnly</code> class.</p> +<pre><code>from snippets.permissions import IsOwnerOrReadOnly +</code></pre> +<p>Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.</p> +<h2 id="authenticating-with-the-api">Authenticating with the API</h2> +<p>Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets.  We haven't set up any <a href="../../api-guide/authentication">authentication classes</a>, so the defaults are currently applied, which are <code>SessionAuthentication</code> and <code>BasicAuthentication</code>.</p> +<p>When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.</p> +<p>If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.</p> +<p>If we try to create a snippet without authenticating, we'll get an error:</p> +<pre><code>curl -i -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123" + +{"detail": "Authentication credentials were not provided."} +</code></pre> +<p>We can make a successful request by including the username and password of one of the users we created earlier.</p> +<pre><code>curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 789" -u tom:password + +{"id": 5, "owner": "tom", "title": "foo", "code": "print 789", "linenos": false, "language": "python", "style": "friendly"} +</code></pre> +<h2 id="summary">Summary</h2> +<p>We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.</p> +<p>In <a href="../5-relationships-and-hyperlinked-apis">part 5</a> of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.</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="../../js/jquery-1.8.1-min.js"></script> +  <script src="../../js/prettify-1.0.js"></script> +  <script src="../../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>
\ No newline at end of file diff --git a/tutorial/5-relationships-and-hyperlinked-apis.html b/tutorial/5-relationships-and-hyperlinked-apis.html deleted file mode 100644 index 250a3d52..00000000 --- a/tutorial/5-relationships-and-hyperlinked-apis.html +++ /dev/null @@ -1,372 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -    <meta charset="utf-8"> -    <title>Tutorial 5: Relationships & Hyperlinked APIs - Django REST framework</title> -    <link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon"> -    <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis"/> -    <meta name="viewport" content="width=device-width, initial-scale=1.0"> -    <meta name="description" content="Django, API, REST, Tutorial 5: Relationships & Hyperlinked APIs"> -    <meta name="author" content="Tom Christie"> - -    <!-- Le styles --> -    <link href="http://www.django-rest-framework.org/css/prettify.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet"> -    <link href="http://www.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> -    <style> -span.fusion-wrap a { -  display: block; -  margin-top: 10px; -  color: black; -} - -a.fusion-poweredby { -  display: block; -  margin-top: 10px; -} -@media (max-width: 767px) { -  div.promo {display: none;} -} -</style> -  </head> -  <body onload="prettyPrint()" class="5-relationships-and-hyperlinked-apis-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/6-viewsets-and-routers">Next <i class="icon-arrow-right icon-white"></i></a> -            <a class="repo-link btn btn-inverse btn-small " href="../tutorial/4-authentication-and-permissions"><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://www.django-rest-framework.org">Django REST framework</a> -          <div class="nav-collapse collapse"> -            <ul class="nav"> -              <li><a href="http://www.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://www.django-rest-framework.org/tutorial/quickstart">Quickstart</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/api-guide/requests">Requests</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/responses">Responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/views">Views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/generic-views">Generic views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/viewsets">Viewsets</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/routers">Routers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/parsers">Parsers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/renderers">Renderers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/serializers">Serializers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/fields">Serializer fields</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/relations">Serializer relations</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/authentication">Authentication</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/permissions">Permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/throttling">Throttling</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/filtering">Filtering</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/pagination">Pagination</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/reverse">Returning URLs</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/exceptions">Exceptions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/status-codes">Status codes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/testing">Testing</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browsable-api">The Browsable API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/third-party-resources">Third Party Resources</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/contributing">Contributing to REST framework</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.4-announcement">2.4 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/kickstarter-announcement">Kickstarter Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/release-notes">Release Notes</a></li> -                  <li><a href="http://www.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-5-relationships-&-hyperlinked-apis">Tutorial 5: Relationships & Hyperlinked APIs</a></li> -<li><a href="#creating-an-endpoint-for-the-root-of-our-api">Creating an endpoint for the root of our API</a></li> -<li><a href="#creating-an-endpoint-for-the-highlighted-snippets">Creating an endpoint for the highlighted snippets</a></li> -<li><a href="#hyperlinking-our-api">Hyperlinking our API</a></li> -<li><a href="#making-sure-our-url-patterns-are-named">Making sure our URL patterns are named</a></li> -<li><a href="#adding-pagination">Adding pagination</a></li> -<li><a href="#browsing-the-api">Browsing the API</a></li> - -              <div class="promo"> -               -              </div> -</ul> - -            </div> -          </div> - -          <div id="main-content" class="span9"> -            <h1 id="tutorial-5-relationships-hyperlinked-apis">Tutorial 5: Relationships & Hyperlinked APIs</h1> -<p>At the moment relationships within our API are represented by using primary keys.  In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.</p> -<h2 id="creating-an-endpoint-for-the-root-of-our-api">Creating an endpoint for the root of our API</h2> -<p>Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API.  To create one, we'll use a regular function-based view and the <code>@api_view</code> decorator we introduced earlier. In your <code>snippets/views.py</code> add:</p> -<pre class="prettyprint lang-py"><code>from rest_framework import renderers -from rest_framework.decorators import api_view -from rest_framework.response import Response -from rest_framework.reverse import reverse - - -@api_view(('GET',)) -def api_root(request, format=None): -    return Response({ -        'users': reverse('user-list', request=request, format=format), -        'snippets': reverse('snippet-list', request=request, format=format) -    }) -</code></pre> -<p>Notice that we're using REST framework's <code>reverse</code> function in order to return fully-qualified URLs.</p> -<h2 id="creating-an-endpoint-for-the-highlighted-snippets">Creating an endpoint for the highlighted snippets</h2> -<p>The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.</p> -<p>Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation.  There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML.  The second renderer is the one we'd like to use for this endpoint.</p> -<p>The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use.  We're not returning an object instance, but instead a property of an object instance.</p> -<p>Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own <code>.get()</code> method.  In your <code>snippets/views.py</code> add:</p> -<pre class="prettyprint lang-py"><code>from rest_framework import renderers -from rest_framework.response import Response - -class SnippetHighlight(generics.GenericAPIView): -    queryset = Snippet.objects.all() -    renderer_classes = (renderers.StaticHTMLRenderer,) - -    def get(self, request, *args, **kwargs): -        snippet = self.get_object() -        return Response(snippet.highlighted) -</code></pre> -<p>As usual we need to add the new views that we've created in to our URLconf. -We'll add a url pattern for our new API root in <code>snippets/urls.py</code>:</p> -<pre class="prettyprint lang-py"><code>url(r'^$', 'api_root'), -</code></pre> -<p>And then add a url pattern for the snippet highlights:</p> -<pre class="prettyprint lang-py"><code>url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', views.SnippetHighlight.as_view()), -</code></pre> -<h2 id="hyperlinking-our-api">Hyperlinking our API</h2> -<p>Dealing with relationships between entities is one of the more challenging aspects of Web API design.  There are a number of different ways that we might choose to represent a relationship:</p> -<ul> -<li>Using primary keys.</li> -<li>Using hyperlinking between entities.</li> -<li>Using a unique identifying slug field on the related entity.</li> -<li>Using the default string representation of the related entity.</li> -<li>Nesting the related entity inside the parent representation.</li> -<li>Some other custom representation.</li> -</ul> -<p>REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.</p> -<p>In this case we'd like to use a hyperlinked style between entities.  In order to do so, we'll modify our serializers to extend <code>HyperlinkedModelSerializer</code> instead of the existing <code>ModelSerializer</code>.</p> -<p>The <code>HyperlinkedModelSerializer</code> has the following differences from <code>ModelSerializer</code>:</p> -<ul> -<li>It does not include the <code>pk</code> field by default.</li> -<li>It includes a <code>url</code> field, using <code>HyperlinkedIdentityField</code>.</li> -<li>Relationships use <code>HyperlinkedRelatedField</code>, -  instead of <code>PrimaryKeyRelatedField</code>.</li> -</ul> -<p>We can easily re-write our existing serializers to use hyperlinking. In your <code>snippets/serializers.py</code> add:</p> -<pre class="prettyprint lang-py"><code>class SnippetSerializer(serializers.HyperlinkedModelSerializer): -    owner = serializers.Field(source='owner.username') -    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') - -    class Meta: -        model = Snippet -        fields = ('url', 'highlight', 'owner', -                  'title', 'code', 'linenos', 'language', 'style') - - -class UserSerializer(serializers.HyperlinkedModelSerializer): -    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail') - -    class Meta: -        model = User -        fields = ('url', 'username', 'snippets') -</code></pre> -<p>Notice that we've also added a new <code>'highlight'</code> field.  This field is of the same type as the <code>url</code> field, except that it points to the <code>'snippet-highlight'</code> url pattern, instead of the <code>'snippet-detail'</code> url pattern.</p> -<p>Because we've included format suffixed URLs such as <code>'.json'</code>, we also need to indicate on the <code>highlight</code> field that any format suffixed hyperlinks it returns should use the <code>'.html'</code> suffix.</p> -<h2 id="making-sure-our-url-patterns-are-named">Making sure our URL patterns are named</h2> -<p>If we're going to have a hyperlinked API, we need to make sure we name our URL patterns.  Let's take a look at which URL patterns we need to name.</p> -<ul> -<li>The root of our API refers to <code>'user-list'</code> and <code>'snippet-list'</code>.</li> -<li>Our snippet serializer includes a field that refers to <code>'snippet-highlight'</code>.</li> -<li>Our user serializer includes a field that refers to <code>'snippet-detail'</code>.</li> -<li>Our snippet and user serializers include <code>'url'</code> fields that by default will refer to <code>'{model_name}-detail'</code>, which in this case will be <code>'snippet-detail'</code> and <code>'user-detail'</code>.</li> -</ul> -<p>After adding all those names into our URLconf, our final <code>snippets/urls.py</code> file should look something like this:</p> -<pre class="prettyprint lang-py"><code># API endpoints -urlpatterns = format_suffix_patterns([ -    url(r'^$', views.api_root), -    url(r'^snippets/$', -        views.SnippetList.as_view(), -        name='snippet-list'), -    url(r'^snippets/(?P<pk>[0-9]+)/$', -        views.SnippetDetail.as_view(), -        name='snippet-detail'), -    url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', -        views.SnippetHighlight.as_view(), -        name='snippet-highlight'), -    url(r'^users/$', -        views.UserList.as_view(), -        name='user-list'), -    url(r'^users/(?P<pk>[0-9]+)/$', -        views.UserDetail.as_view(), -        name='user-detail') -]) - -# Login and logout views for the browsable API -urlpatterns += [ -    url(r'^api-auth/', include('rest_framework.urls', -                               namespace='rest_framework')), -] -</code></pre> -<h2 id="adding-pagination">Adding pagination</h2> -<p>The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.</p> -<p>We can change the default list style to use pagination, by modifying our <code>settings.py</code> file slightly.  Add the following setting:</p> -<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = { -    'PAGINATE_BY': 10 -} -</code></pre> -<p>Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.</p> -<p>We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.</p> -<h2 id="browsing-the-api">Browsing the API</h2> -<p>If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.</p> -<p>You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.</p> -<p>In <a href="6-viewsets-and-routers">part 6</a> of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.</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://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script> -    <script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script> -    <script src="http://www.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> diff --git a/tutorial/5-relationships-and-hyperlinked-apis/index.html b/tutorial/5-relationships-and-hyperlinked-apis/index.html new file mode 100644 index 00000000..dd39c431 --- /dev/null +++ b/tutorial/5-relationships-and-hyperlinked-apis/index.html @@ -0,0 +1,560 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> +  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> +  <meta charset="utf-8"> +  <title>5 - Relationships and hyperlinked APIs - Django REST framework</title> +  <link href="../../img/favicon.ico" rel="icon" type="image/x-icon"> +  <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/" /> +  <meta name="viewport" content="width=device-width, initial-scale=1.0"> +  <meta name="description" content="Django, API, REST, 5 - Relationships and hyperlinked APIs"> +  <meta name="author" content="Tom Christie"> + +  <!-- Le styles --> +  <link href="../../css/prettify.css" rel="stylesheet"> +  <link href="../../css/bootstrap.css" rel="stylesheet"> +  <link href="../../css/bootstrap-responsive.css" rel="stylesheet"> +  <link href="../../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> + +  <style> +    span.fusion-wrap a { +      display: block; +      margin-top: 10px; +      color: black; +    } +    a.fusion-poweredby { +      display: block; +      margin-top: 10px; +    } +    @media (max-width: 767px) { +      div.promo { +        display: none; +      } +    } +  </style> +</head> +<body onload="prettyPrint()" class="-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 " rel="prev" href="../6-viewsets-and-routers"> +            Next <i class="icon-arrow-right icon-white"></i> +          </a> +          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../4-authentication-and-permissions"> +            <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://www.django-rest-framework.org">Django REST framework</a> +          <div class="nav-collapse collapse"> +             +            <!-- Main navigation --> +            <ul class="nav navbar-nav"> +              <li ><a href="/">Home</a></li> +                +              <li class="dropdown active"> +                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a> +                <ul class="dropdown-menu"> +                   +                  <li > +                    <a href="../quickstart">Quickstart</a> +                  </li> +                   +                  <li > +                    <a href="../1-serialization">1 - Serialization</a> +                  </li> +                   +                  <li > +                    <a href="../2-requests-and-responses">2 - Requests and responses</a> +                  </li> +                   +                  <li > +                    <a href="../3-class-based-views">3 - Class based views</a> +                  </li> +                   +                  <li > +                    <a href="../4-authentication-and-permissions">4 - Authentication and permissions</a> +                  </li> +                   +                  <li class="active" > +                    <a href=".">5 - Relationships and hyperlinked APIs</a> +                  </li> +                   +                  <li > +                    <a href="../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="../../api-guide/requests">Requests</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/responses">Responses</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/views">Views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/generic-views">Generic views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/viewsets">Viewsets</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/routers">Routers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/parsers">Parsers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/renderers">Renderers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/serializers">Serializers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/fields">Serializer fields</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/relations">Serializer relations</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/validators">Validators</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/authentication">Authentication</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/permissions">Permissions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/throttling">Throttling</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/filtering">Filtering</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/pagination">Pagination</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/content-negotiation">Content negotiation</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/format-suffixes">Format suffixes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/reverse">Returning URLs</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/exceptions">Exceptions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/status-codes">Status codes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/testing">Testing</a> +                  </li> +                   +                  <li > +                    <a href="../../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="../../topics/documenting-your-api">Documenting your API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/ajax-csrf-cors">AJAX, CSRF & CORS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browser-enhancements">Browser enhancements</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browsable-api">The Browsable API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/third-party-resources">Third Party Resources</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/contributing">Contributing to REST framework</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-framework-2-announcement">2.0 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.2-announcement">2.2 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.3-announcement">2.3 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.4-announcement">2.4 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/kickstarter-announcement">Kickstarter Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/release-notes">Release Notes</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/credits">Credits</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-5-relationships-hyperlinked-apis">Tutorial 5: Relationships & Hyperlinked APIs</a> +                  </li> + +                   +                    <li> +                      <a href="#creating-an-endpoint-for-the-root-of-our-api">Creating an endpoint for the root of our API</a> +                    </li> +                   +                    <li> +                      <a href="#creating-an-endpoint-for-the-highlighted-snippets">Creating an endpoint for the highlighted snippets</a> +                    </li> +                   +                    <li> +                      <a href="#hyperlinking-our-api">Hyperlinking our API</a> +                    </li> +                   +                    <li> +                      <a href="#making-sure-our-url-patterns-are-named">Making sure our URL patterns are named</a> +                    </li> +                   +                    <li> +                      <a href="#adding-pagination">Adding pagination</a> +                    </li> +                   +                    <li> +                      <a href="#browsing-the-api">Browsing the API</a> +                    </li> +                   + +                 + +                 + +              </ul> + +            </div> +          </div> + +          <div id="main-content" class="span9"> +             + +            <h1 id="tutorial-5-relationships-hyperlinked-apis">Tutorial 5: Relationships & Hyperlinked APIs</h1> +<p>At the moment relationships within our API are represented by using primary keys.  In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.</p> +<h2 id="creating-an-endpoint-for-the-root-of-our-api">Creating an endpoint for the root of our API</h2> +<p>Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API.  To create one, we'll use a regular function-based view and the <code>@api_view</code> decorator we introduced earlier. In your <code>snippets/views.py</code> add:</p> +<pre><code>from rest_framework.decorators import api_view +from rest_framework.response import Response +from rest_framework.reverse import reverse + + +@api_view(('GET',)) +def api_root(request, format=None): +    return Response({ +        'users': reverse('user-list', request=request, format=format), +        'snippets': reverse('snippet-list', request=request, format=format) +    }) +</code></pre> +<p>Notice that we're using REST framework's <code>reverse</code> function in order to return fully-qualified URLs.</p> +<h2 id="creating-an-endpoint-for-the-highlighted-snippets">Creating an endpoint for the highlighted snippets</h2> +<p>The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.</p> +<p>Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation.  There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML.  The second renderer is the one we'd like to use for this endpoint.</p> +<p>The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use.  We're not returning an object instance, but instead a property of an object instance.</p> +<p>Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own <code>.get()</code> method.  In your <code>snippets/views.py</code> add:</p> +<pre><code>from rest_framework import renderers +from rest_framework.response import Response + +class SnippetHighlight(generics.GenericAPIView): +    queryset = Snippet.objects.all() +    renderer_classes = (renderers.StaticHTMLRenderer,) + +    def get(self, request, *args, **kwargs): +        snippet = self.get_object() +        return Response(snippet.highlighted) +</code></pre> +<p>As usual we need to add the new views that we've created in to our URLconf. +We'll add a url pattern for our new API root in <code>snippets/urls.py</code>:</p> +<pre><code>url(r'^$', 'api_root'), +</code></pre> +<p>And then add a url pattern for the snippet highlights:</p> +<pre><code>url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', views.SnippetHighlight.as_view()), +</code></pre> +<h2 id="hyperlinking-our-api">Hyperlinking our API</h2> +<p>Dealing with relationships between entities is one of the more challenging aspects of Web API design.  There are a number of different ways that we might choose to represent a relationship:</p> +<ul> +<li>Using primary keys.</li> +<li>Using hyperlinking between entities.</li> +<li>Using a unique identifying slug field on the related entity.</li> +<li>Using the default string representation of the related entity.</li> +<li>Nesting the related entity inside the parent representation.</li> +<li>Some other custom representation.</li> +</ul> +<p>REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.</p> +<p>In this case we'd like to use a hyperlinked style between entities.  In order to do so, we'll modify our serializers to extend <code>HyperlinkedModelSerializer</code> instead of the existing <code>ModelSerializer</code>.</p> +<p>The <code>HyperlinkedModelSerializer</code> has the following differences from <code>ModelSerializer</code>:</p> +<ul> +<li>It does not include the <code>pk</code> field by default.</li> +<li>It includes a <code>url</code> field, using <code>HyperlinkedIdentityField</code>.</li> +<li>Relationships use <code>HyperlinkedRelatedField</code>, +  instead of <code>PrimaryKeyRelatedField</code>.</li> +</ul> +<p>We can easily re-write our existing serializers to use hyperlinking. In your <code>snippets/serializers.py</code> add:</p> +<pre><code>class SnippetSerializer(serializers.HyperlinkedModelSerializer): +    owner = serializers.Field(source='owner.username') +    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') + +    class Meta: +        model = Snippet +        fields = ('url', 'highlight', 'owner', +                  'title', 'code', 'linenos', 'language', 'style') + + +class UserSerializer(serializers.HyperlinkedModelSerializer): +    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail') + +    class Meta: +        model = User +        fields = ('url', 'username', 'snippets') +</code></pre> +<p>Notice that we've also added a new <code>'highlight'</code> field.  This field is of the same type as the <code>url</code> field, except that it points to the <code>'snippet-highlight'</code> url pattern, instead of the <code>'snippet-detail'</code> url pattern.</p> +<p>Because we've included format suffixed URLs such as <code>'.json'</code>, we also need to indicate on the <code>highlight</code> field that any format suffixed hyperlinks it returns should use the <code>'.html'</code> suffix.</p> +<h2 id="making-sure-our-url-patterns-are-named">Making sure our URL patterns are named</h2> +<p>If we're going to have a hyperlinked API, we need to make sure we name our URL patterns.  Let's take a look at which URL patterns we need to name.</p> +<ul> +<li>The root of our API refers to <code>'user-list'</code> and <code>'snippet-list'</code>.</li> +<li>Our snippet serializer includes a field that refers to <code>'snippet-highlight'</code>.</li> +<li>Our user serializer includes a field that refers to <code>'snippet-detail'</code>.</li> +<li>Our snippet and user serializers include <code>'url'</code> fields that by default will refer to <code>'{model_name}-detail'</code>, which in this case will be <code>'snippet-detail'</code> and <code>'user-detail'</code>.</li> +</ul> +<p>After adding all those names into our URLconf, our final <code>snippets/urls.py</code> file should look something like this:</p> +<pre><code># API endpoints +urlpatterns = format_suffix_patterns([ +    url(r'^$', views.api_root), +    url(r'^snippets/$', +        views.SnippetList.as_view(), +        name='snippet-list'), +    url(r'^snippets/(?P<pk>[0-9]+)/$', +        views.SnippetDetail.as_view(), +        name='snippet-detail'), +    url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', +        views.SnippetHighlight.as_view(), +        name='snippet-highlight'), +    url(r'^users/$', +        views.UserList.as_view(), +        name='user-list'), +    url(r'^users/(?P<pk>[0-9]+)/$', +        views.UserDetail.as_view(), +        name='user-detail') +]) + +# Login and logout views for the browsable API +urlpatterns += [ +    url(r'^api-auth/', include('rest_framework.urls', +                               namespace='rest_framework')), +] +</code></pre> +<h2 id="adding-pagination">Adding pagination</h2> +<p>The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.</p> +<p>We can change the default list style to use pagination, by modifying our <code>settings.py</code> file slightly.  Add the following setting:</p> +<pre><code>REST_FRAMEWORK = { +    'PAGINATE_BY': 10 +} +</code></pre> +<p>Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.</p> +<p>We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.</p> +<h2 id="browsing-the-api">Browsing the API</h2> +<p>If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.</p> +<p>You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.</p> +<p>In <a href="../6-viewsets-and-routers">part 6</a> of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.</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="../../js/jquery-1.8.1-min.js"></script> +  <script src="../../js/prettify-1.0.js"></script> +  <script src="../../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>
\ No newline at end of file diff --git a/tutorial/6-viewsets-and-routers.html b/tutorial/6-viewsets-and-routers.html deleted file mode 100644 index da4c6383..00000000 --- a/tutorial/6-viewsets-and-routers.html +++ /dev/null @@ -1,361 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -    <meta charset="utf-8"> -    <title>Tutorial 6: ViewSets & Routers - Django REST framework</title> -    <link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon"> -    <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers"/> -    <meta name="viewport" content="width=device-width, initial-scale=1.0"> -    <meta name="description" content="Django, API, REST, Tutorial 6: ViewSets & Routers"> -    <meta name="author" content="Tom Christie"> - -    <!-- Le styles --> -    <link href="http://www.django-rest-framework.org/css/prettify.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet"> -    <link href="http://www.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> -    <style> -span.fusion-wrap a { -  display: block; -  margin-top: 10px; -  color: black; -} - -a.fusion-poweredby { -  display: block; -  margin-top: 10px; -} -@media (max-width: 767px) { -  div.promo {display: none;} -} -</style> -  </head> -  <body onload="prettyPrint()" class="6-viewsets-and-routers-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="../api-guide/requests">Next <i class="icon-arrow-right icon-white"></i></a> -            <a class="repo-link btn btn-inverse btn-small " href="../tutorial/5-relationships-and-hyperlinked-apis"><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://www.django-rest-framework.org">Django REST framework</a> -          <div class="nav-collapse collapse"> -            <ul class="nav"> -              <li><a href="http://www.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://www.django-rest-framework.org/tutorial/quickstart">Quickstart</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/api-guide/requests">Requests</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/responses">Responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/views">Views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/generic-views">Generic views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/viewsets">Viewsets</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/routers">Routers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/parsers">Parsers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/renderers">Renderers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/serializers">Serializers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/fields">Serializer fields</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/relations">Serializer relations</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/authentication">Authentication</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/permissions">Permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/throttling">Throttling</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/filtering">Filtering</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/pagination">Pagination</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/reverse">Returning URLs</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/exceptions">Exceptions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/status-codes">Status codes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/testing">Testing</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browsable-api">The Browsable API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/third-party-resources">Third Party Resources</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/contributing">Contributing to REST framework</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.4-announcement">2.4 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/kickstarter-announcement">Kickstarter Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/release-notes">Release Notes</a></li> -                  <li><a href="http://www.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-6-viewsets-&-routers">Tutorial 6: ViewSets & Routers</a></li> -<li><a href="#refactoring-to-use-viewsets">Refactoring to use ViewSets</a></li> -<li><a href="#binding-viewsets-to-urls-explicitly">Binding ViewSets to URLs explicitly</a></li> -<li><a href="#using-routers">Using Routers</a></li> -<li><a href="#trade-offs-between-views-vs-viewsets">Trade-offs between views vs viewsets</a></li> -<li><a href="#reviewing-our-work">Reviewing our work</a></li> -<li><a href="#onwards-and-upwards">Onwards and upwards</a></li> - -              <div class="promo"> -               -              </div> -</ul> - -            </div> -          </div> - -          <div id="main-content" class="span9"> -            <h1 id="tutorial-6-viewsets-routers">Tutorial 6: ViewSets & Routers</h1> -<p>REST framework includes an abstraction for dealing with <code>ViewSets</code>, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.</p> -<p><code>ViewSet</code> classes are almost the same thing as <code>View</code> classes, except that they provide operations such as <code>read</code>, or <code>update</code>, and not method handlers such as <code>get</code> or <code>put</code>.</p> -<p>A <code>ViewSet</code> class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a <code>Router</code> class which handles the complexities of defining the URL conf for you.</p> -<h2 id="refactoring-to-use-viewsets">Refactoring to use ViewSets</h2> -<p>Let's take our current set of views, and refactor them into view sets.</p> -<p>First of all let's refactor our <code>UserList</code> and <code>UserDetail</code> views into a single <code>UserViewSet</code>.  We can remove the two views, and replace them with a single class:</p> -<pre class="prettyprint lang-py"><code>from rest_framework import viewsets - -class UserViewSet(viewsets.ReadOnlyModelViewSet): -    """ -    This viewset automatically provides `list` and `detail` actions. -    """ -    queryset = User.objects.all() -    serializer_class = UserSerializer -</code></pre> -<p>Here we've used the <code>ReadOnlyModelViewSet</code> class to automatically provide the default 'read-only' operations.  We're still setting the <code>queryset</code> and <code>serializer_class</code> attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.</p> -<p>Next we're going to replace the <code>SnippetList</code>, <code>SnippetDetail</code> and <code>SnippetHighlight</code> view classes.  We can remove the three views, and again replace them with a single class.</p> -<pre class="prettyprint lang-py"><code>from rest_framework.decorators import detail_route - -class SnippetViewSet(viewsets.ModelViewSet): -    """ -    This viewset automatically provides `list`, `create`, `retrieve`, -    `update` and `destroy` actions. - -    Additionally we also provide an extra `highlight` action. -    """ -    queryset = Snippet.objects.all() -    serializer_class = SnippetSerializer -    permission_classes = (permissions.IsAuthenticatedOrReadOnly, -                          IsOwnerOrReadOnly,) - -    @detail_route(renderer_classes=[renderers.StaticHTMLRenderer]) -    def highlight(self, request, *args, **kwargs): -        snippet = self.get_object() -        return Response(snippet.highlighted) - -    def pre_save(self, obj): -        obj.owner = self.request.user -</code></pre> -<p>This time we've used the <code>ModelViewSet</code> class in order to get the complete set of default read and write operations.</p> -<p>Notice that we've also used the <code>@detail_route</code> decorator to create a custom action, named <code>highlight</code>.  This decorator can be used to add any custom endpoints that don't fit into the standard <code>create</code>/<code>update</code>/<code>delete</code> style.</p> -<p>Custom actions which use the <code>@detail_route</code> decorator will respond to <code>GET</code> requests.  We can use the <code>methods</code> argument if we wanted an action that responded to <code>POST</code> requests.</p> -<h2 id="binding-viewsets-to-urls-explicitly">Binding ViewSets to URLs explicitly</h2> -<p>The handler methods only get bound to the actions when we define the URLConf. -To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.</p> -<p>In the <code>urls.py</code> file we bind our <code>ViewSet</code> classes into a set of concrete views.</p> -<pre class="prettyprint lang-py"><code>from snippets.views import SnippetViewSet, UserViewSet -from rest_framework import renderers - -snippet_list = SnippetViewSet.as_view({ -    'get': 'list', -    'post': 'create' -}) -snippet_detail = SnippetViewSet.as_view({ -    'get': 'retrieve', -    'put': 'update', -    'patch': 'partial_update', -    'delete': 'destroy' -}) -snippet_highlight = SnippetViewSet.as_view({ -    'get': 'highlight' -}, renderer_classes=[renderers.StaticHTMLRenderer]) -user_list = UserViewSet.as_view({ -    'get': 'list' -}) -user_detail = UserViewSet.as_view({ -    'get': 'retrieve' -}) -</code></pre> -<p>Notice how we're creating multiple views from each <code>ViewSet</code> class, by binding the http methods to the required action for each view.</p> -<p>Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.</p> -<pre class="prettyprint lang-py"><code>urlpatterns = format_suffix_patterns([ -    url(r'^$', api_root), -    url(r'^snippets/$', snippet_list, name='snippet-list'), -    url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'), -    url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'), -    url(r'^users/$', user_list, name='user-list'), -    url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail') -]) -</code></pre> -<h2 id="using-routers">Using Routers</h2> -<p>Because we're using <code>ViewSet</code> classes rather than <code>View</code> classes, we actually don't need to design the URL conf ourselves.  The conventions for wiring up resources into views and urls can be handled automatically, using a <code>Router</code> class.  All we need to do is register the appropriate view sets with a router, and let it do the rest.</p> -<p>Here's our re-wired <code>urls.py</code> file.</p> -<pre class="prettyprint lang-py"><code>from django.conf.urls import url, include -from snippets import views -from rest_framework.routers import DefaultRouter - -# Create a router and register our viewsets with it. -router = DefaultRouter() -router.register(r'snippets', views.SnippetViewSet) -router.register(r'users', views.UserViewSet) - -# The API URLs are now determined automatically by the router. -# Additionally, we include the login URLs for the browseable API. -urlpatterns = [ -    url(r'^', include(router.urls)), -    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) -] -</code></pre> -<p>Registering the viewsets with the router is similar to providing a urlpattern.  We include two arguments - the URL prefix for the views, and the viewset itself.</p> -<p>The <code>DefaultRouter</code> class we're using also automatically creates the API root view for us, so we can now delete the <code>api_root</code> method from our <code>views</code> module.</p> -<h2 id="trade-offs-between-views-vs-viewsets">Trade-offs between views vs viewsets</h2> -<p>Using viewsets can be a really useful abstraction.  It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.</p> -<p>That doesn't mean it's always the right approach to take.  There's a similar set of trade-offs to consider as when using class-based views instead of function based views.  Using viewsets is less explicit than building your views individually.</p> -<h2 id="reviewing-our-work">Reviewing our work</h2> -<p>With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.</p> -<p>We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.</p> -<p>You can review the final <a href="https://github.com/tomchristie/rest-framework-tutorial">tutorial code</a> on GitHub, or try out a live example in <a href="http://restframework.herokuapp.com/">the sandbox</a>.</p> -<h2 id="onwards-and-upwards">Onwards and upwards</h2> -<p>We've reached the end of our tutorial.  If you want to get more involved in the REST framework project, here are a few places you can start:</p> -<ul> -<li>Contribute on <a href="https://github.com/tomchristie/django-rest-framework">GitHub</a> by reviewing and submitting issues, and making pull requests.</li> -<li>Join the <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">REST framework discussion group</a>, and help build the community.</li> -<li>Follow <a href="https://twitter.com/_tomchristie">the author</a> on Twitter and say hi.</li> -</ul> -<p><strong>Now go build awesome things.</strong></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://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script> -    <script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script> -    <script src="http://www.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> diff --git a/tutorial/6-viewsets-and-routers/index.html b/tutorial/6-viewsets-and-routers/index.html new file mode 100644 index 00000000..d299743f --- /dev/null +++ b/tutorial/6-viewsets-and-routers/index.html @@ -0,0 +1,550 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> +  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> +  <meta charset="utf-8"> +  <title>6- Viewsets and routers - Django REST framework</title> +  <link href="../../img/favicon.ico" rel="icon" type="image/x-icon"> +  <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/" /> +  <meta name="viewport" content="width=device-width, initial-scale=1.0"> +  <meta name="description" content="Django, API, REST, 6- Viewsets and routers"> +  <meta name="author" content="Tom Christie"> + +  <!-- Le styles --> +  <link href="../../css/prettify.css" rel="stylesheet"> +  <link href="../../css/bootstrap.css" rel="stylesheet"> +  <link href="../../css/bootstrap-responsive.css" rel="stylesheet"> +  <link href="../../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> + +  <style> +    span.fusion-wrap a { +      display: block; +      margin-top: 10px; +      color: black; +    } +    a.fusion-poweredby { +      display: block; +      margin-top: 10px; +    } +    @media (max-width: 767px) { +      div.promo { +        display: none; +      } +    } +  </style> +</head> +<body onload="prettyPrint()" class="-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 " rel="prev" href="../../api-guide/requests"> +            Next <i class="icon-arrow-right icon-white"></i> +          </a> +          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../5-relationships-and-hyperlinked-apis"> +            <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://www.django-rest-framework.org">Django REST framework</a> +          <div class="nav-collapse collapse"> +             +            <!-- Main navigation --> +            <ul class="nav navbar-nav"> +              <li ><a href="/">Home</a></li> +                +              <li class="dropdown active"> +                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a> +                <ul class="dropdown-menu"> +                   +                  <li > +                    <a href="../quickstart">Quickstart</a> +                  </li> +                   +                  <li > +                    <a href="../1-serialization">1 - Serialization</a> +                  </li> +                   +                  <li > +                    <a href="../2-requests-and-responses">2 - Requests and responses</a> +                  </li> +                   +                  <li > +                    <a href="../3-class-based-views">3 - Class based views</a> +                  </li> +                   +                  <li > +                    <a href="../4-authentication-and-permissions">4 - Authentication and permissions</a> +                  </li> +                   +                  <li > +                    <a href="../5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a> +                  </li> +                   +                  <li class="active" > +                    <a href=".">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="../../api-guide/requests">Requests</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/responses">Responses</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/views">Views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/generic-views">Generic views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/viewsets">Viewsets</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/routers">Routers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/parsers">Parsers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/renderers">Renderers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/serializers">Serializers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/fields">Serializer fields</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/relations">Serializer relations</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/validators">Validators</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/authentication">Authentication</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/permissions">Permissions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/throttling">Throttling</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/filtering">Filtering</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/pagination">Pagination</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/content-negotiation">Content negotiation</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/format-suffixes">Format suffixes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/reverse">Returning URLs</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/exceptions">Exceptions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/status-codes">Status codes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/testing">Testing</a> +                  </li> +                   +                  <li > +                    <a href="../../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="../../topics/documenting-your-api">Documenting your API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/ajax-csrf-cors">AJAX, CSRF & CORS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browser-enhancements">Browser enhancements</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browsable-api">The Browsable API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/third-party-resources">Third Party Resources</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/contributing">Contributing to REST framework</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-framework-2-announcement">2.0 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.2-announcement">2.2 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.3-announcement">2.3 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.4-announcement">2.4 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/kickstarter-announcement">Kickstarter Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/release-notes">Release Notes</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/credits">Credits</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-6-viewsets-routers">Tutorial 6: ViewSets & Routers</a> +                  </li> + +                   +                    <li> +                      <a href="#refactoring-to-use-viewsets">Refactoring to use ViewSets</a> +                    </li> +                   +                    <li> +                      <a href="#binding-viewsets-to-urls-explicitly">Binding ViewSets to URLs explicitly</a> +                    </li> +                   +                    <li> +                      <a href="#using-routers">Using Routers</a> +                    </li> +                   +                    <li> +                      <a href="#trade-offs-between-views-vs-viewsets">Trade-offs between views vs viewsets</a> +                    </li> +                   +                    <li> +                      <a href="#reviewing-our-work">Reviewing our work</a> +                    </li> +                   +                    <li> +                      <a href="#onwards-and-upwards">Onwards and upwards</a> +                    </li> +                   + +                 + +                 + +              </ul> + +            </div> +          </div> + +          <div id="main-content" class="span9"> +             + +            <h1 id="tutorial-6-viewsets-routers">Tutorial 6: ViewSets & Routers</h1> +<p>REST framework includes an abstraction for dealing with <code>ViewSets</code>, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.</p> +<p><code>ViewSet</code> classes are almost the same thing as <code>View</code> classes, except that they provide operations such as <code>read</code>, or <code>update</code>, and not method handlers such as <code>get</code> or <code>put</code>.</p> +<p>A <code>ViewSet</code> class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a <code>Router</code> class which handles the complexities of defining the URL conf for you.</p> +<h2 id="refactoring-to-use-viewsets">Refactoring to use ViewSets</h2> +<p>Let's take our current set of views, and refactor them into view sets.</p> +<p>First of all let's refactor our <code>UserList</code> and <code>UserDetail</code> views into a single <code>UserViewSet</code>.  We can remove the two views, and replace them with a single class:</p> +<pre><code>from rest_framework import viewsets + +class UserViewSet(viewsets.ReadOnlyModelViewSet): +    """ +    This viewset automatically provides `list` and `detail` actions. +    """ +    queryset = User.objects.all() +    serializer_class = UserSerializer +</code></pre> +<p>Here we've used the <code>ReadOnlyModelViewSet</code> class to automatically provide the default 'read-only' operations.  We're still setting the <code>queryset</code> and <code>serializer_class</code> attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.</p> +<p>Next we're going to replace the <code>SnippetList</code>, <code>SnippetDetail</code> and <code>SnippetHighlight</code> view classes.  We can remove the three views, and again replace them with a single class.</p> +<pre><code>from rest_framework.decorators import detail_route + +class SnippetViewSet(viewsets.ModelViewSet): +    """ +    This viewset automatically provides `list`, `create`, `retrieve`, +    `update` and `destroy` actions. + +    Additionally we also provide an extra `highlight` action. +    """ +    queryset = Snippet.objects.all() +    serializer_class = SnippetSerializer +    permission_classes = (permissions.IsAuthenticatedOrReadOnly, +                          IsOwnerOrReadOnly,) + +    @detail_route(renderer_classes=[renderers.StaticHTMLRenderer]) +    def highlight(self, request, *args, **kwargs): +        snippet = self.get_object() +        return Response(snippet.highlighted) + +    def pre_save(self, obj): +        obj.owner = self.request.user +</code></pre> +<p>This time we've used the <code>ModelViewSet</code> class in order to get the complete set of default read and write operations.</p> +<p>Notice that we've also used the <code>@detail_route</code> decorator to create a custom action, named <code>highlight</code>.  This decorator can be used to add any custom endpoints that don't fit into the standard <code>create</code>/<code>update</code>/<code>delete</code> style.</p> +<p>Custom actions which use the <code>@detail_route</code> decorator will respond to <code>GET</code> requests.  We can use the <code>methods</code> argument if we wanted an action that responded to <code>POST</code> requests.</p> +<h2 id="binding-viewsets-to-urls-explicitly">Binding ViewSets to URLs explicitly</h2> +<p>The handler methods only get bound to the actions when we define the URLConf. +To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.</p> +<p>In the <code>urls.py</code> file we bind our <code>ViewSet</code> classes into a set of concrete views.</p> +<pre><code>from snippets.views import SnippetViewSet, UserViewSet, api_root +from rest_framework import renderers + +snippet_list = SnippetViewSet.as_view({ +    'get': 'list', +    'post': 'create' +}) +snippet_detail = SnippetViewSet.as_view({ +    'get': 'retrieve', +    'put': 'update', +    'patch': 'partial_update', +    'delete': 'destroy' +}) +snippet_highlight = SnippetViewSet.as_view({ +    'get': 'highlight' +}, renderer_classes=[renderers.StaticHTMLRenderer]) +user_list = UserViewSet.as_view({ +    'get': 'list' +}) +user_detail = UserViewSet.as_view({ +    'get': 'retrieve' +}) +</code></pre> +<p>Notice how we're creating multiple views from each <code>ViewSet</code> class, by binding the http methods to the required action for each view.</p> +<p>Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.</p> +<pre><code>urlpatterns = format_suffix_patterns([ +    url(r'^$', api_root), +    url(r'^snippets/$', snippet_list, name='snippet-list'), +    url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'), +    url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'), +    url(r'^users/$', user_list, name='user-list'), +    url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail') +]) +</code></pre> +<h2 id="using-routers">Using Routers</h2> +<p>Because we're using <code>ViewSet</code> classes rather than <code>View</code> classes, we actually don't need to design the URL conf ourselves.  The conventions for wiring up resources into views and urls can be handled automatically, using a <code>Router</code> class.  All we need to do is register the appropriate view sets with a router, and let it do the rest.</p> +<p>Here's our re-wired <code>urls.py</code> file.</p> +<pre><code>from django.conf.urls import url, include +from snippets import views +from rest_framework.routers import DefaultRouter + +# Create a router and register our viewsets with it. +router = DefaultRouter() +router.register(r'snippets', views.SnippetViewSet) +router.register(r'users', views.UserViewSet) + +# The API URLs are now determined automatically by the router. +# Additionally, we include the login URLs for the browseable API. +urlpatterns = [ +    url(r'^', include(router.urls)), +    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) +] +</code></pre> +<p>Registering the viewsets with the router is similar to providing a urlpattern.  We include two arguments - the URL prefix for the views, and the viewset itself.</p> +<p>The <code>DefaultRouter</code> class we're using also automatically creates the API root view for us, so we can now delete the <code>api_root</code> method from our <code>views</code> module.</p> +<h2 id="trade-offs-between-views-vs-viewsets">Trade-offs between views vs viewsets</h2> +<p>Using viewsets can be a really useful abstraction.  It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.</p> +<p>That doesn't mean it's always the right approach to take.  There's a similar set of trade-offs to consider as when using class-based views instead of function based views.  Using viewsets is less explicit than building your views individually.</p> +<h2 id="reviewing-our-work">Reviewing our work</h2> +<p>With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.</p> +<p>We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.</p> +<p>You can review the final <a href="https://github.com/tomchristie/rest-framework-tutorial">tutorial code</a> on GitHub, or try out a live example in <a href="http://restframework.herokuapp.com/">the sandbox</a>.</p> +<h2 id="onwards-and-upwards">Onwards and upwards</h2> +<p>We've reached the end of our tutorial.  If you want to get more involved in the REST framework project, here are a few places you can start:</p> +<ul> +<li>Contribute on <a href="https://github.com/tomchristie/django-rest-framework">GitHub</a> by reviewing and submitting issues, and making pull requests.</li> +<li>Join the <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">REST framework discussion group</a>, and help build the community.</li> +<li>Follow <a href="https://twitter.com/_tomchristie">the author</a> on Twitter and say hi.</li> +</ul> +<p><strong>Now go build awesome things.</strong></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="../../js/jquery-1.8.1-min.js"></script> +  <script src="../../js/prettify-1.0.js"></script> +  <script src="../../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>
\ No newline at end of file diff --git a/tutorial/quickstart.html b/tutorial/quickstart.html deleted file mode 100644 index 07d38da8..00000000 --- a/tutorial/quickstart.html +++ /dev/null @@ -1,380 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -    <meta charset="utf-8"> -    <title>Quickstart - Django REST framework</title> -    <link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon"> -    <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/quickstart"/> -    <meta name="viewport" content="width=device-width, initial-scale=1.0"> -    <meta name="description" content="Django, API, REST, Quickstart"> -    <meta name="author" content="Tom Christie"> - -    <!-- Le styles --> -    <link href="http://www.django-rest-framework.org/css/prettify.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet"> -    <link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet"> -    <link href="http://www.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> -    <style> -span.fusion-wrap a { -  display: block; -  margin-top: 10px; -  color: black; -} - -a.fusion-poweredby { -  display: block; -  margin-top: 10px; -} -@media (max-width: 767px) { -  div.promo {display: none;} -} -</style> -  </head> -  <body onload="prettyPrint()" class="quickstart-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/1-serialization">Next <i class="icon-arrow-right icon-white"></i></a> -            <a class="repo-link btn btn-inverse btn-small " href="/"><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://www.django-rest-framework.org">Django REST framework</a> -          <div class="nav-collapse collapse"> -            <ul class="nav"> -              <li><a href="http://www.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://www.django-rest-framework.org/tutorial/quickstart">Quickstart</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/api-guide/requests">Requests</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/responses">Responses</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/views">Views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/generic-views">Generic views</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/viewsets">Viewsets</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/routers">Routers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/parsers">Parsers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/renderers">Renderers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/serializers">Serializers</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/fields">Serializer fields</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/relations">Serializer relations</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/authentication">Authentication</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/permissions">Permissions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/throttling">Throttling</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/filtering">Filtering</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/pagination">Pagination</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/reverse">Returning URLs</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/exceptions">Exceptions</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/status-codes">Status codes</a></li> -                  <li><a href="http://www.django-rest-framework.org/api-guide/testing">Testing</a></li> -                  <li><a href="http://www.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://www.django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/browsable-api">The Browsable API</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/third-party-resources">Third Party Resources</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/contributing">Contributing to REST framework</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/2.4-announcement">2.4 Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/kickstarter-announcement">Kickstarter Announcement</a></li> -                  <li><a href="http://www.django-rest-framework.org/topics/release-notes">Release Notes</a></li> -                  <li><a href="http://www.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="#quickstart">Quickstart</a></li> -<li><a href="#project-setup">Project setup</a></li> -<li><a href="#serializers">Serializers</a></li> -<li><a href="#views">Views</a></li> -<li><a href="#urls">URLs</a></li> -<li><a href="#settings">Settings</a></li> -<li><a href="#testing-our-api">Testing our API</a></li> - -              <div class="promo"> -               -              </div> -</ul> - -            </div> -          </div> - -          <div id="main-content" class="span9"> -            <h1 id="quickstart">Quickstart</h1> -<p>We're going to create a simple API to allow admin users to view and edit the users and groups in the system.</p> -<h2 id="project-setup">Project setup</h2> -<p>Create a new Django project named <code>tutorial</code>, then start a new app called <code>quickstart</code>.</p> -<pre class="prettyprint lang-py"><code># Create the project directory -mkdir tutorial -cd tutorial - -# Create a virtualenv to isolate our package dependencies locally -virtualenv env -source env/bin/activate  # On Windows use `env\Scripts\activate` - -# Install Django and Django REST framework into the virtualenv -pip install django -pip install djangorestframework - -# Set up a new project with a single application -django-admin.py startproject tutorial . -cd tutorial -django-admin.py startapp quickstart -cd .. -</code></pre> -<p>Now sync your database for the first time:</p> -<pre class="prettyprint lang-py"><code>python manage.py syncdb -</code></pre> -<p>Make sure to create an initial user named <code>admin</code> with a password of <code>password</code>. We'll authenticate as that user later in our example.</p> -<p>Once you've set up a database and got everything synced and ready to go, open up the app's directory and we'll get coding...</p> -<h2 id="serializers">Serializers</h2> -<p>First up we're going to define some serializers. Let's create a new module named <code>tutorial/quickstart/serializers.py</code> that we'll use for our data representations.</p> -<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User, Group -from rest_framework import serializers - - -class UserSerializer(serializers.HyperlinkedModelSerializer): -    class Meta: -        model = User -        fields = ('url', 'username', 'email', 'groups') - - -class GroupSerializer(serializers.HyperlinkedModelSerializer): -    class Meta: -        model = Group -        fields = ('url', 'name') -</code></pre> -<p>Notice that we're using hyperlinked relations in this case, with <code>HyperlinkedModelSerializer</code>.  You can also use primary key and various other relationships, but hyperlinking is good RESTful design.</p> -<h2 id="views">Views</h2> -<p>Right, we'd better write some views then.  Open <code>tutorial/quickstart/views.py</code> and get typing.</p> -<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User, Group -from rest_framework import viewsets -from tutorial.quickstart.serializers import UserSerializer, GroupSerializer - - -class UserViewSet(viewsets.ModelViewSet): -    """ -    API endpoint that allows users to be viewed or edited. -    """ -    queryset = User.objects.all() -    serializer_class = UserSerializer - - -class GroupViewSet(viewsets.ModelViewSet): -    """ -    API endpoint that allows groups to be viewed or edited. -    """ -    queryset = Group.objects.all() -    serializer_class = GroupSerializer -</code></pre> -<p>Rather than write multiple views we're grouping together all the common behavior into classes called <code>ViewSets</code>.</p> -<p>We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.</p> -<p>Notice that our viewset classes here are a little different from those in the <a href="../#example">frontpage example</a>, as they include <code>queryset</code> and <code>serializer_class</code> attributes, instead of a <code>model</code> attribute.</p> -<p>For trivial cases you can simply set a <code>model</code> attribute on the <code>ViewSet</code> class and the serializer and queryset will be automatically generated for you.  Setting the <code>queryset</code> and/or <code>serializer_class</code> attributes gives you more explicit control of the API behaviour, and is the recommended style for most applications.</p> -<h2 id="urls">URLs</h2> -<p>Okay, now let's wire up the API URLs.  On to <code>tutorial/urls.py</code>...</p> -<pre class="prettyprint lang-py"><code>from django.conf.urls import url, include -from rest_framework import routers -from tutorial.quickstart import views - -router = routers.DefaultRouter() -router.register(r'users', views.UserViewSet) -router.register(r'groups', views.GroupViewSet) - -# Wire up our API using automatic URL routing. -# Additionally, we include login URLs for the browseable API. -urlpatterns = [ -    url(r'^', include(router.urls)), -    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) -] -</code></pre> -<p>Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.</p> -<p>Again, if we need more control over the API URLs we can simply drop down to using regular class based views, and writing the URL conf explicitly.</p> -<p>Finally, we're including default login and logout views for use with the browsable API.  That's optional, but useful if your API requires authentication and you want to use the browsable API.</p> -<h2 id="settings">Settings</h2> -<p>We'd also like to set a few global settings.  We'd like to turn on pagination, and we want our API to only be accessible to admin users.  The settings module will be in <code>tutorial/settings.py</code></p> -<pre class="prettyprint lang-py"><code>INSTALLED_APPS = ( -    ... -    'rest_framework', -) - -REST_FRAMEWORK = { -    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',), -    'PAGINATE_BY': 10 -} -</code></pre> -<p>Okay, we're done.</p> -<hr /> -<h2 id="testing-our-api">Testing our API</h2> -<p>We're now ready to test the API we've built.  Let's fire up the server from the command line.</p> -<pre class="prettyprint lang-py"><code>python ./manage.py runserver -</code></pre> -<p>We can now access our API, both from the command-line, using tools like <code>curl</code>...</p> -<pre class="prettyprint lang-py"><code>bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ -{ -    "count": 2, -    "next": null, -    "previous": null, -    "results": [ -        { -            "email": "admin@example.com", -            "groups": [], -            "url": "http://127.0.0.1:8000/users/1/", -            "username": "admin" -        }, -        { -            "email": "tom@example.com", -            "groups": [                ], -            "url": "http://127.0.0.1:8000/users/2/", -            "username": "tom" -        } -    ] -} -</code></pre> -<p>Or directly through the browser...</p> -<p><img alt="Quick start image" src="../img/quickstart.png" /></p> -<p>If you're working through the browser, make sure to login using the control in the top right corner.</p> -<p>Great, that was easy!</p> -<p>If you want to get a more in depth understanding of how REST framework fits together head on over to <a href="1-serialization">the tutorial</a>, or start browsing the <a href="../#api-guide">API guide</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://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script> -    <script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script> -    <script src="http://www.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> diff --git a/tutorial/quickstart/index.html b/tutorial/quickstart/index.html new file mode 100644 index 00000000..0aad281b --- /dev/null +++ b/tutorial/quickstart/index.html @@ -0,0 +1,571 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> +  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> +  <meta charset="utf-8"> +  <title>Quickstart - Django REST framework</title> +  <link href="../../img/favicon.ico" rel="icon" type="image/x-icon"> +  <link rel="canonical" href="http://www.django-rest-framework.org/tutorial/quickstart/" /> +  <meta name="viewport" content="width=device-width, initial-scale=1.0"> +  <meta name="description" content="Django, API, REST, Quickstart"> +  <meta name="author" content="Tom Christie"> + +  <!-- Le styles --> +  <link href="../../css/prettify.css" rel="stylesheet"> +  <link href="../../css/bootstrap.css" rel="stylesheet"> +  <link href="../../css/bootstrap-responsive.css" rel="stylesheet"> +  <link href="../../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> + +  <style> +    span.fusion-wrap a { +      display: block; +      margin-top: 10px; +      color: black; +    } +    a.fusion-poweredby { +      display: block; +      margin-top: 10px; +    } +    @media (max-width: 767px) { +      div.promo { +        display: none; +      } +    } +  </style> +</head> +<body onload="prettyPrint()" class="-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 " rel="prev" href="../1-serialization"> +            Next <i class="icon-arrow-right icon-white"></i> +          </a> +          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../.."> +            <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://www.django-rest-framework.org">Django REST framework</a> +          <div class="nav-collapse collapse"> +             +            <!-- Main navigation --> +            <ul class="nav navbar-nav"> +              <li ><a href="/">Home</a></li> +                +              <li class="dropdown active"> +                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a> +                <ul class="dropdown-menu"> +                   +                  <li class="active" > +                    <a href=".">Quickstart</a> +                  </li> +                   +                  <li > +                    <a href="../1-serialization">1 - Serialization</a> +                  </li> +                   +                  <li > +                    <a href="../2-requests-and-responses">2 - Requests and responses</a> +                  </li> +                   +                  <li > +                    <a href="../3-class-based-views">3 - Class based views</a> +                  </li> +                   +                  <li > +                    <a href="../4-authentication-and-permissions">4 - Authentication and permissions</a> +                  </li> +                   +                  <li > +                    <a href="../5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a> +                  </li> +                   +                  <li > +                    <a href="../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="../../api-guide/requests">Requests</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/responses">Responses</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/views">Views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/generic-views">Generic views</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/viewsets">Viewsets</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/routers">Routers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/parsers">Parsers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/renderers">Renderers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/serializers">Serializers</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/fields">Serializer fields</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/relations">Serializer relations</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/validators">Validators</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/authentication">Authentication</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/permissions">Permissions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/throttling">Throttling</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/filtering">Filtering</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/pagination">Pagination</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/content-negotiation">Content negotiation</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/format-suffixes">Format suffixes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/reverse">Returning URLs</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/exceptions">Exceptions</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/status-codes">Status codes</a> +                  </li> +                   +                  <li > +                    <a href="../../api-guide/testing">Testing</a> +                  </li> +                   +                  <li > +                    <a href="../../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="../../topics/documenting-your-api">Documenting your API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/ajax-csrf-cors">AJAX, CSRF & CORS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browser-enhancements">Browser enhancements</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/browsable-api">The Browsable API</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/third-party-resources">Third Party Resources</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/contributing">Contributing to REST framework</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/rest-framework-2-announcement">2.0 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.2-announcement">2.2 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.3-announcement">2.3 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/2.4-announcement">2.4 Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/kickstarter-announcement">Kickstarter Announcement</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/release-notes">Release Notes</a> +                  </li> +                   +                  <li > +                    <a href="../../topics/credits">Credits</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="#quickstart">Quickstart</a> +                  </li> + +                   +                    <li> +                      <a href="#project-setup">Project setup</a> +                    </li> +                   +                    <li> +                      <a href="#serializers">Serializers</a> +                    </li> +                   +                    <li> +                      <a href="#views">Views</a> +                    </li> +                   +                    <li> +                      <a href="#urls">URLs</a> +                    </li> +                   +                    <li> +                      <a href="#settings">Settings</a> +                    </li> +                   +                    <li> +                      <a href="#testing-our-api">Testing our API</a> +                    </li> +                   + +                 + +                 + +              </ul> + +            </div> +          </div> + +          <div id="main-content" class="span9"> +             + +            <h1 id="quickstart">Quickstart</h1> +<p>We're going to create a simple API to allow admin users to view and edit the users and groups in the system.</p> +<h2 id="project-setup">Project setup</h2> +<p>Create a new Django project named <code>tutorial</code>, then start a new app called <code>quickstart</code>.</p> +<pre><code># Create the project directory +mkdir tutorial +cd tutorial + +# Create a virtualenv to isolate our package dependencies locally +virtualenv env +source env/bin/activate  # On Windows use `env\Scripts\activate` + +# Install Django and Django REST framework into the virtualenv +pip install django +pip install djangorestframework + +# Set up a new project with a single application +django-admin.py startproject tutorial +cd tutorial +django-admin.py startapp quickstart +cd .. +</code></pre> +<p>Now sync your database for the first time:</p> +<pre><code>python manage.py migrate +</code></pre> +<p>We'll also create an initial user named <code>admin</code> with a password of <code>password</code>. We'll authenticate as that user later in our example.</p> +<pre><code>python manage.py createsuperuser +</code></pre> +<p>Once you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...</p> +<h2 id="serializers">Serializers</h2> +<p>First up we're going to define some serializers. Let's create a new module named <code>tutorial/quickstart/serializers.py</code> that we'll use for our data representations.</p> +<pre><code>from django.contrib.auth.models import User, Group +from rest_framework import serializers + + +class UserSerializer(serializers.HyperlinkedModelSerializer): +    class Meta: +        model = User +        fields = ('url', 'username', 'email', 'groups') + + +class GroupSerializer(serializers.HyperlinkedModelSerializer): +    class Meta: +        model = Group +        fields = ('url', 'name') +</code></pre> +<p>Notice that we're using hyperlinked relations in this case, with <code>HyperlinkedModelSerializer</code>.  You can also use primary key and various other relationships, but hyperlinking is good RESTful design.</p> +<h2 id="views">Views</h2> +<p>Right, we'd better write some views then.  Open <code>tutorial/quickstart/views.py</code> and get typing.</p> +<pre><code>from django.contrib.auth.models import User, Group +from rest_framework import viewsets +from tutorial.quickstart.serializers import UserSerializer, GroupSerializer + + +class UserViewSet(viewsets.ModelViewSet): +    """ +    API endpoint that allows users to be viewed or edited. +    """ +    queryset = User.objects.all() +    serializer_class = UserSerializer + + +class GroupViewSet(viewsets.ModelViewSet): +    """ +    API endpoint that allows groups to be viewed or edited. +    """ +    queryset = Group.objects.all() +    serializer_class = GroupSerializer +</code></pre> +<p>Rather than write multiple views we're grouping together all the common behavior into classes called <code>ViewSets</code>.</p> +<p>We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.</p> +<p>Notice that our viewset classes here are a little different from those in the <a href="../../../#example">frontpage example</a>, as they include <code>queryset</code> and <code>serializer_class</code> attributes, instead of a <code>model</code> attribute.</p> +<p>For trivial cases you can simply set a <code>model</code> attribute on the <code>ViewSet</code> class and the serializer and queryset will be automatically generated for you.  Setting the <code>queryset</code> and/or <code>serializer_class</code> attributes gives you more explicit control of the API behaviour, and is the recommended style for most applications.</p> +<h2 id="urls">URLs</h2> +<p>Okay, now let's wire up the API URLs.  On to <code>tutorial/urls.py</code>...</p> +<pre><code>from django.conf.urls import url, include +from rest_framework import routers +from tutorial.quickstart import views + +router = routers.DefaultRouter() +router.register(r'users', views.UserViewSet) +router.register(r'groups', views.GroupViewSet) + +# Wire up our API using automatic URL routing. +# Additionally, we include login URLs for the browseable API. +urlpatterns = [ +    url(r'^', include(router.urls)), +    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) +] +</code></pre> +<p>Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.</p> +<p>Again, if we need more control over the API URLs we can simply drop down to using regular class based views, and writing the URL conf explicitly.</p> +<p>Finally, we're including default login and logout views for use with the browsable API.  That's optional, but useful if your API requires authentication and you want to use the browsable API.</p> +<h2 id="settings">Settings</h2> +<p>We'd also like to set a few global settings.  We'd like to turn on pagination, and we want our API to only be accessible to admin users.  The settings module will be in <code>tutorial/settings.py</code></p> +<pre><code>INSTALLED_APPS = ( +    ... +    'rest_framework', +) + +REST_FRAMEWORK = { +    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',), +    'PAGINATE_BY': 10 +} +</code></pre> +<p>Okay, we're done.</p> +<hr /> +<h2 id="testing-our-api">Testing our API</h2> +<p>We're now ready to test the API we've built.  Let's fire up the server from the command line.</p> +<pre><code>python ./manage.py runserver +</code></pre> +<p>We can now access our API, both from the command-line, using tools like <code>curl</code>...</p> +<pre><code>bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ +{ +    "count": 2, +    "next": null, +    "previous": null, +    "results": [ +        { +            "email": "admin@example.com", +            "groups": [], +            "url": "http://127.0.0.1:8000/users/1/", +            "username": "admin" +        }, +        { +            "email": "tom@example.com", +            "groups": [                ], +            "url": "http://127.0.0.1:8000/users/2/", +            "username": "tom" +        } +    ] +} +</code></pre> +<p>Or directly through the browser...</p> +<p><img alt="Quick start image" src="../../../img/quickstart.png" /></p> +<p>If you're working through the browser, make sure to login using the control in the top right corner.</p> +<p>Great, that was easy!</p> +<p>If you want to get a more in depth understanding of how REST framework fits together head on over to <a href="../1-serialization">the tutorial</a>, or start browsing the <a href="../../../#api-guide">API guide</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="../../js/jquery-1.8.1-min.js"></script> +  <script src="../../js/prettify-1.0.js"></script> +  <script src="../../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>
\ No newline at end of file | 
