<!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/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/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 = patterns('', 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>