diff options
Diffstat (limited to 'docs/topics')
| -rw-r--r-- | docs/topics/browsable-api.md | 102 | ||||
| -rw-r--r-- | docs/topics/browser-enhancements.md | 64 | ||||
| -rw-r--r-- | docs/topics/contributing.md | 15 | ||||
| -rw-r--r-- | docs/topics/credits.md | 139 | ||||
| -rw-r--r-- | docs/topics/csrf.md | 12 | ||||
| -rw-r--r-- | docs/topics/migration.md | 89 | ||||
| -rw-r--r-- | docs/topics/release-notes.md | 116 | ||||
| -rw-r--r-- | docs/topics/rest-framework-2-announcement.md | 100 | ||||
| -rw-r--r-- | docs/topics/rest-hypermedia-hateoas.md | 53 |
9 files changed, 690 insertions, 0 deletions
diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md new file mode 100644 index 00000000..9fe82e69 --- /dev/null +++ b/docs/topics/browsable-api.md @@ -0,0 +1,102 @@ +# The Browsable API + +> It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them. +> +> — [Alfred North Whitehead][cite], An Introduction to Mathematics (1911) + + +API may stand for Application *Programming* Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the `HTML` format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using `POST`, `PUT`, and `DELETE`. + +## URLs + +If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `rest_framework` package includes a [`reverse`][drfreverse] helper for this purpose. + + +## Formats + +By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview]. + + +## Customizing + +To customize the look-and-feel, create a template called `api.html` and add it to your project, eg: `templates/rest_framework/api.html`, that extends the `rest_framework/base.html` template. + +The included browsable API template is built with [Bootstrap (2.1.1)][bootstrap], making it easy to customize the look-and-feel. + +### Theme + +To replace the theme wholesale, add a `bootstrap_theme` block to your `api.html` and insert a `link` to the desired Bootstrap theme css file. This will completely replace the included theme. + + {% block bootstrap_theme %} + <link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css"> + {% endblock %} + +A suitable replacement theme can be generated using Bootstrap's [Customize Tool][bcustomize]. Also, there are pre-made themes available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. + +You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style. + +For more specific CSS tweaks, use the `extra_style` block instead. + + +### Blocks + +All of the blocks available in the browsable API base template that can be used in your `api.html`. + +* `blockbots` - `<meta>` tag that blocks crawlers +* `bodyclass` - (empty) class attribute for the `<body>` +* `bootstrap_theme` - CSS for the Bootstrap theme +* `bootstrap_navbar_variant` - CSS class for the navbar +* `branding` - section of the navbar, see [Bootstrap components][bcomponentsnav] +* `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block. +* `extrastyle` - (empty) extra CSS for the page +* `extrahead` - (empty) extra markup for the page `<head>` +* `footer` - Any copyright notices or similar footer materials can go here (by default right-aligned) +* `global_heading` - (empty) Use to insert content below the header but before the breadcrumbs. +* `title` - title of the page +* `userlinks` - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links. + +#### Components + +All of the [Bootstrap components][bcomponents] are available. + +##### Tooltips + +The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content displayed in a tooltip on hover after a 1000ms delay. + + +### Advanced Customization + +#### Context + +The context that's available to the template: + +* `allowed_methods` : A list of methods allowed by the resource +* `api_settings` : The API settings +* `available_formats` : A list of formats allowed by the resource +* `breadcrumblist` : The list of links following the chain of nested resources +* `content` : The content of the API response +* `description` : The description of the resource, generated from its docstring +* `name` : The name of the resource +* `post_form` : A form instance for use by the POST form (if allowed) +* `put_form` : A form instance for use by the PUT form (if allowed) +* `request` : The request object +* `response` : The response object +* `version` : The version of Django REST Framework +* `view` : The view handling the request +* `FORMAT_PARAM` : The view can accept a format override +* `METHOD_PARAM` : The view can accept a method override + +#### Not using base.html + +For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you. + +[cite]: http://en.wikiquote.org/wiki/Alfred_North_Whitehead +[drfreverse]: ../api-guide/reverse.md +[ffjsonview]: https://addons.mozilla.org/en-US/firefox/addon/jsonview/ +[chromejsonview]: https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc +[bootstrap]: http://getbootstrap.com +[bcustomize]: http://twitter.github.com/bootstrap/customize.html#variables +[bswatch]: http://bootswatch.com/ +[bcomponents]: http://twitter.github.com/bootstrap/components.html +[bcomponentsnav]: http://twitter.github.com/bootstrap/components.html#navbar + diff --git a/docs/topics/browser-enhancements.md b/docs/topics/browser-enhancements.md new file mode 100644 index 00000000..6a11f0fa --- /dev/null +++ b/docs/topics/browser-enhancements.md @@ -0,0 +1,64 @@ +# Browser enhancements + +> "There are two noncontroversial uses for overloaded POST. The first is to *simulate* HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE" +> +> — [RESTful Web Services][cite], Leonard Richardson & Sam Ruby. + +## Browser based PUT, DELETE, etc... + +REST framework supports browser-based `PUT`, `DELETE` and other methods, by +overloading `POST` requests using a hidden form field. + +Note that this is the same strategy as is used in [Ruby on Rails][rails]. + +For example, given the following form: + + <form action="/news-items/5" method="POST"> + <input type="hidden" name="_method" value="DELETE"> + </form> + +`request.method` would return `"DELETE"`. + +## Browser based submission of non-form content + +Browser-based submission of content types other than form are supported by +using form fields named `_content` and `_content_type`: + +For example, given the following form: + + <form action="/news-items/5" method="PUT"> + <input type="hidden" name="_content_type" value="application/json"> + <input name="_content" value="{'count': 1}"> + </form> + +`request.content_type` would return `"application/json"`, and +`request.stream` would return `"{'count': 1}"` + +## URL based accept headers + +REST framework can take `?accept=application/json` style URL parameters, +which allow the `Accept` header to be overridden. + +This can be useful for testing the API from a web browser, where you don't +have any control over what is sent in the `Accept` header. + +## URL based format suffixes + +REST framework can take `?format=json` style URL parameters, which can be a +useful shortcut for determing which content type should be returned from +the view. + +This is a more concise than using the `accept` override, but it also gives +you less control. (For example you can't specify any media type parameters) + +## Doesn't HTML5 support PUT and DELETE forms? + +Nope. It was at one point intended to support `PUT` and `DELETE` forms, but +was later [dropped from the spec][html5]. There remains +[ongoing discussion][put_delete] about adding support for `PUT` and `DELETE`, +as well as how to support content types other than form-encoded data. + +[cite]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260 +[rails]: http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work +[html5]: http://www.w3.org/TR/html5-diff/#changes-2010-06-24 +[put_delete]: http://amundsen.com/examples/put-delete-forms/ diff --git a/docs/topics/contributing.md b/docs/topics/contributing.md new file mode 100644 index 00000000..7fd61c10 --- /dev/null +++ b/docs/topics/contributing.md @@ -0,0 +1,15 @@ +# Contributing to REST framework + +> The world can only really be changed one piece at a time. The art is picking that piece. +> +> — [Tim Berners-Lee][cite] + +## Running the tests + +## Building the docs + +## Managing compatibility issues + +**Describe compat module** + +[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html
\ No newline at end of file diff --git a/docs/topics/credits.md b/docs/topics/credits.md new file mode 100644 index 00000000..69d57802 --- /dev/null +++ b/docs/topics/credits.md @@ -0,0 +1,139 @@ +# Credits + +The following people have helped make REST framework great. + +* Tom Christie - [tomchristie] +* Marko Tibold - [markotibold] +* Paul Bagwell - [pbgwl] +* Sébastien Piquemal - [sebpiq] +* Carmen Wick - [cwick] +* Alex Ehlke - [aehlke] +* Alen Mujezinovic - [flashingpumpkin] +* Carles Barrobés - [txels] +* Michael Fötsch - [mfoetsch] +* David Larlet - [david] +* Andrew Straw - [astraw] +* Zeth - [zeth] +* Fernando Zunino - [fzunino] +* Jens Alm - [ulmus] +* Craig Blaszczyk - [jakul] +* Garcia Solero - [garciasolero] +* Tom Drummond - [devioustree] +* Danilo Bargen - [gwrtheyrn] +* Andrew McCloud - [amccloud] +* Thomas Steinacher - [thomasst] +* Meurig Freeman - [meurig] +* Anthony Nemitz - [anemitz] +* Ewoud Kohl van Wijngaarden - [ekohl] +* Michael Ding - [yandy] +* Mjumbe Poe - [mjumbewu] +* Natim - [natim] +* Sebastian Żurek - [sebzur] +* Benoit C - [dzen] +* Chris Pickett - [bunchesofdonald] +* Ben Timby - [btimby] +* Michele Lazzeri - [michelelazzeri-nextage] +* Camille Harang - [mammique] +* Paul Oswald - [poswald] +* Sean C. Farley - [scfarley] +* Daniel Izquierdo - [izquierdo] +* Can Yavuz - [tschan] +* Shawn Lewis - [shawnlewis] +* Alec Perkins - [alecperkins] +* Michael Barrett - [phobologic] +* Mathieu Dhondt - [laundromat] +* Johan Charpentier - [cyberj] +* Jamie Matthews - [j4mie] +* Mattbo - [mattbo] +* Max Hurl - [maximilianhurl] +* Tomi Pajunen - [eofs] +* Rob Dobson - [rdobson] +* Daniel Vaca Araujo - [diviei] +* Madis Väin - [madisvain] +* Stephan Groß - [minddust] + +Many thanks to everyone who's contributed to the project. + +## Additional thanks + +The documentation is built with [Bootstrap] and [Markdown]. + +Project hosting is with [GitHub]. + +Continuous integration testing is managed with [Travis CI][travis-ci]. + +The [live sandbox][sandbox] is hosted on [Heroku]. + +Various inspiration taken from the [Piston], [Tastypie] and [Dagny] projects. + +Development of REST framework 2.0 was sponsored by [DabApps]. + +## Contact + +To contact the author directly: + +* twitter: [@_tomchristie][twitter] +* email: [tom@tomchristie.com][email] + +[email]: mailto:tom@tomchristie.com +[twitter]: http://twitter.com/_tomchristie +[bootstrap]: http://twitter.github.com/bootstrap/ +[markdown]: http://daringfireball.net/projects/markdown/ +[github]: github.com/tomchristie/django-rest-framework +[travis-ci]: https://secure.travis-ci.org/tomchristie/django-rest-framework +[piston]: https://bitbucket.org/jespern/django-piston +[tastypie]: https://github.com/toastdriven/django-tastypie +[dagny]: https://github.com/zacharyvoase/dagny +[dabapps]: http://lab.dabapps.com +[sandbox]: http://restframework.herokuapp.com/ +[heroku]: http://www.heroku.com/ + +[tomchristie]: https://github.com/tomchristie +[markotibold]: https://github.com/markotibold +[pbgwl]: https://github.com/pbgwl +[sebpiq]: https://github.com/sebpiq +[cwick]: https://github.com/cwick +[aehlke]: https://github.com/aehlke +[flashingpumpkin]: https://github.com/flashingpumpkin +[txels]: https://github.com/txels +[mfoetsch]: https://github.com/mfoetsch +[david]: https://github.com/david +[astraw]: https://github.com/astraw +[zeth]: https://github.com/zeth +[fzunino]: https://github.com/fzunino +[ulmus]: https://github.com/ulmus +[jakul]: https://github.com/jakul +[garciasolero]: https://github.com/garciasolero +[devioustree]: https://github.com/devioustree +[gwrtheyrn]: https://github.com/gwrtheyrn +[amccloud]: https://github.com/amccloud +[thomasst]: https://github.com/thomasst +[meurig]: https://github.com/meurig +[anemitz]: https://github.com/anemitz +[ekohl]: https://github.com/ekohl +[yandy]: https://github.com/yandy +[mjumbewu]: https://github.com/mjumbewu +[natim]: https://github.com/natim +[sebzur]: https://github.com/sebzur +[dzen]: https://github.com/dzen +[bunchesofdonald]: https://github.com/bunchesofdonald +[btimby]: https://github.com/btimby +[michelelazzeri-nextage]: https://github.com/michelelazzeri-nextage +[mammique]: https://github.com/mammique +[poswald]: https://github.com/poswald +[scfarley]: https://github.com/scfarley +[izquierdo]: https://github.com/izquierdo +[tschan]: https://github.com/tschan +[shawnlewis]: https://github.com/shawnlewis +[alecperkins]: https://github.com/alecperkins +[phobologic]: https://github.com/phobologic +[laundromat]: https://github.com/laundromat +[cyberj]: https://github.com/cyberj +[j4mie]: https://github.com/j4mie +[mattbo]: https://github.com/mattbo +[maximilianhurl]: https://github.com/maximilianhurl +[eofs]: https://github.com/eofs +[rdobson]: https://github.com/rdobson +[diviei]: https://github.com/diviei +[madisvain]: https://github.com/madisvain +[minddust]: https://github.com/minddust
\ No newline at end of file diff --git a/docs/topics/csrf.md b/docs/topics/csrf.md new file mode 100644 index 00000000..043144c1 --- /dev/null +++ b/docs/topics/csrf.md @@ -0,0 +1,12 @@ +# Working with AJAX and CSRF + +> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability -- very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one." +> +> — [Jeff Atwood][cite] + +* Explain need to add CSRF token to AJAX requests. +* Explain deferred CSRF style used by REST framework +* Why you should use Django's standard login/logout views, and not REST framework view + + +[cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html diff --git a/docs/topics/migration.md b/docs/topics/migration.md new file mode 100644 index 00000000..25fc9074 --- /dev/null +++ b/docs/topics/migration.md @@ -0,0 +1,89 @@ +# 2.0 Migration Guide + +> Move fast and break things +> +> — Mark Zuckerberg, [the Hacker Way][cite]. + +REST framework 2.0 introduces a radical redesign of the core components, and a large number of backwards breaking changes. + +### Serialization redesign. + +REST framework's serialization and deserialization previously used a slightly odd combination of serializers for output, and Django Forms and Model Forms for input. The serialization core has been completely redesigned based on work that was originally intended for Django core. + +2.0's form-like serializers comprehensively address those issues, and are a much more flexible and clean solution to the problems around accepting both form-based and non-form based inputs. + +### Generic views improved. + +When REST framework 0.1 was released the current Django version was 1.2. REST framework included a backport of the Django 1.3's upcoming `View` class, but it didn't take full advantage of the generic view implementations. + +As of 2.0 the generic views in REST framework tie in much more cleanly and obviously with Django's existing codebase, and the mixin architecture is radically simplified. + +### Cleaner request-response cycle. + +REST framework 2.0's request-response cycle is now much less complex. + +* Responses inherit from `SimpleTemplateResponse`, allowing rendering to be delegated to the response, not handled by the view. +* Requests extend the regular `HttpRequest`, allowing authentication and parsing to be delegated to the request, not handled by the view. + +### Renamed attributes & classes. + +Various attributes and classes have been renamed in order to fit in better with Django's conventions. + +## Example: Blog Posts API + +Let's take a look at an example from the REST framework 0.4 documentation... + + from djangorestframework.resources import ModelResource + from djangorestframework.reverse import reverse + from blogpost.models import BlogPost, Comment + + + class BlogPostResource(ModelResource): + """ + A Blog Post has a *title* and *content*, and can be associated + with zero or more comments. + """ + model = BlogPost + fields = ('created', 'title', 'slug', 'content', 'url', 'comments') + ordering = ('-created',) + + def url(self, instance): + return reverse('blog-post', + kwargs={'key': instance.key}, + request=self.request) + + def comments(self, instance): + return reverse('comments', + kwargs={'blogpost': instance.key}, + request=self.request) + + + class CommentResource(ModelResource): + """ + A Comment is associated with a given Blog Post and has a + *username* and *comment*, and optionally a *rating*. + """ + model = Comment + fields = ('username', 'comment', 'created', 'rating', 'url', 'blogpost') + ordering = ('-created',) + + def blogpost(self, instance): + return reverse('blog-post', + kwargs={'key': instance.blogpost.key}, + request=self.request) + +There's a bit of a mix of concerns going on there. We've got some information about how the data should be serialized, such as the `fields` attribute, and some information about how it should be retrieved from the database - the `ordering` attribute. + +Let's start to re-write this for REST framework 2.0. + + from rest_framework import serializers + + class BlogPostSerializer(serializers.HyperlinkedModelSerializer): + model = BlogPost + fields = ('created', 'title', 'slug', 'content', 'url', 'comments') + + class CommentSerializer(serializers.HyperlinkedModelSerializer): + model = Comment + fields = ('username', 'comment', 'created', 'rating', 'url', 'blogpost') + +[cite]: http://www.wired.com/business/2012/02/zuck-letter/ diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md new file mode 100644 index 00000000..a466f4b1 --- /dev/null +++ b/docs/topics/release-notes.md @@ -0,0 +1,116 @@ +# Release Notes + +> Release Early, Release Often +> +> — Eric S. Raymond, [The Cathedral and the Bazaar][cite]. + +## 2.0.0 + +* **Fix all of the things.** (Well, almost.) +* For more information please see the [2.0 migration guide][migration]. + +--- + +## 0.4.0 + +* Supports Django 1.5. +* Fixes issues with 'HEAD' method. +* Allow views to specify template used by TemplateRenderer +* More consistent error responses +* Some serializer fixes +* Fix internet explorer ajax behaviour +* Minor xml and yaml fixes +* Improve setup (eg use staticfiles, not the defunct ADMIN_MEDIA_PREFIX) +* Sensible absolute URL generation, not using hacky set_script_prefix + +## 0.3.3 + +* Added DjangoModelPermissions class to support `django.contrib.auth` style permissions. +* Use `staticfiles` for css files. + - Easier to override. Won't conflict with customised admin styles (eg grappelli) +* Templates are now nicely namespaced. + - Allows easier overriding. +* Drop implied 'pk' filter if last arg in urlconf is unnamed. + - Too magical. Explict is better than implicit. +* Saner template variable autoescaping. +* Tider setup.py +* Updated for URLObject 2.0 +* Bugfixes: + - Bug with PerUserThrottling when user contains unicode chars. + +## 0.3.2 + +* Bugfixes: + * Fix 403 for POST and PUT from the UI with UserLoggedInAuthentication (#115) + * serialize_model method in serializer.py may cause wrong value (#73) + * Fix Error when clicking OPTIONS button (#146) + * And many other fixes +* Remove short status codes + - Zen of Python: "There should be one-- and preferably only one --obvious way to do it." +* get_name, get_description become methods on the view - makes them overridable. +* Improved model mixin API - Hooks for build_query, get_instance_data, get_model, get_queryset, get_ordering + +## 0.3.1 + +* [not documented] + +## 0.3.0 + +* JSONP Support +* Bugfixes, including support for latest markdown release + +## 0.2.4 + +* Fix broken IsAdminUser permission. +* OPTIONS support. +* XMLParser. +* Drop mentions of Blog, BitBucket. + +## 0.2.3 + +* Fix some throttling bugs. +* ``X-Throttle`` header on throttling. +* Support for nesting resources on related models. + +## 0.2.2 + +* Throttling support complete. + +## 0.2.1 + +* Couple of simple bugfixes over 0.2.0 + +## 0.2.0 + +* Big refactoring changes since 0.1.0, ask on the discussion group if anything isn't clear. + The public API has been massively cleaned up. Expect it to be fairly stable from here on in. + +* ``Resource`` becomes decoupled into ``View`` and ``Resource``, your views should now inherit from ``View``, not ``Resource``. + +* The handler functions on views ``.get() .put() .post()`` etc, no longer have the ``content`` and ``auth`` args. + Use ``self.CONTENT`` inside a view to access the deserialized, validated content. + Use ``self.user`` inside a view to access the authenticated user. + +* ``allowed_methods`` and ``anon_allowed_methods`` are now defunct. if a method is defined, it's available. + The ``permissions`` attribute on a ``View`` is now used to provide generic permissions checking. + Use permission classes such as ``FullAnonAccess``, ``IsAuthenticated`` or ``IsUserOrIsAnonReadOnly`` to set the permissions. + +* The ``authenticators`` class becomes ``authentication``. Class names change to ``Authentication``. + +* The ``emitters`` class becomes ``renderers``. Class names change to ``Renderers``. + +* ``ResponseException`` becomes ``ErrorResponse``. + +* The mixin classes have been nicely refactored, the basic mixins are now ``RequestMixin``, ``ResponseMixin``, ``AuthMixin``, and ``ResourceMixin`` + You can reuse these mixin classes individually without using the ``View`` class. + +## 0.1.1 + +* Final build before pulling in all the refactoring changes for 0.2, in case anyone needs to hang on to 0.1. + +## 0.1.0 + +* Initial release. + +[cite]: http://www.catb.org/~esr/writings/cathedral-bazaar/cathedral-bazaar/ar01s04.html +[migration]: migration.md
\ No newline at end of file diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md new file mode 100644 index 00000000..885d1918 --- /dev/null +++ b/docs/topics/rest-framework-2-announcement.md @@ -0,0 +1,100 @@ +# Django REST framework 2 + +What it is, and why you should care. + +> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result. +> +> — [Roy Fielding][cite] + +--- + +**Announcement:** REST framework 2 released - Tue 30th Oct 2012 + +--- + +REST framework 2 is an almost complete reworking of the original framework, which comprehensively addresses some of the original design issues. + +Because the latest version should be considered a re-release, rather than an incremental improvement, we've skipped a version, and called this release Django REST framework 2.0. + +This article is intended to give you a flavor of what REST framework 2 is, and why you might want to give it a try. + +## User feedback + +Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters… + +"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - [Kit La Touche][quote1] + +"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - [Ian Strachan][quote2] + +"I switched to the 2.0 branch and I don't regret it - fully refactored my code in another ½ day and it's *much* more to my tastes" - [Bruno Desthuilliers][quote3] + +Sounds good, right? Let's get into some details... + +## Serialization + +REST framework 2 includes a totally re-worked serialization engine, that was initially intended as a replacement for Django's existing inflexible fixture serialization, and which meets the following design goals: + +* A declarative serialization API, that mirrors Django's `Forms`/`ModelForms` API. +* Structural concerns are decoupled from encoding concerns. +* Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms. +* Validation that can be mapped to obvious and comprehensive error responses. +* Serializers that support both nested, flat, and partially-nested representations. +* Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations. + +Mapping between the internal state of the system and external representations of that state is the core concern of building Web APIs. Designing serializers that allow the developer to do so in a flexible and obvious way is a deceptively difficult design task, and with the new serialization API we think we've pretty much nailed it. + +## Generic views + +When REST framework was initially released at the start of 2011, the current Django release was version 1.2. REST framework included a backport of Django 1.3's upcoming `View` class, but it didn't take full advantage of the generic view implementations. + +With the new release the generic views in REST framework now tie in with Django's generic views. The end result is that framework is clean, lightweight and easy to use. + +## Requests, Responses & Views + +REST framework 2 includes `Request` and `Response` classes, than are used in place of Django's existing `HttpRequest` and `HttpResponse` classes. Doing so allows logic such as parsing the incoming request or rendering the outgoing response to be supported transparently by the framework. + +The `Request`/`Response` approach leads to a much cleaner API, less logic in the view itself, and a simple, obvious request-response cycle. + +REST framework 2 also allows you to work with both function-based and class-based views. For simple API views all you need is a single `@api_view` decorator, and you're good to go. + + +## API Design + +Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independantly of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions. + +## The Browseable API + +Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints. + +Browseable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with. + +With REST framework 2, the browseable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with. + +There are also some functionality improvments - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions. + +![Browseable API][image] + +**Image above**: An example of the browseable API in REST framework 2 + +## Documentation + +As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling. + +We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great. + +## Summary + +In short, we've engineered the hell outta this thing, and we're incredibly proud of the result. + +If you're interested please take a browse around the documentation. [The tutorial][tut] is a great place to get started. + +There's also a [live sandbox version of the tutorial API][sandbox] available for testing. + +[cite]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-724 +[quote1]: https://twitter.com/kobutsu/status/261689665952833536 +[quote2]: https://groups.google.com/d/msg/django-rest-framework/heRGHzG6BWQ/ooVURgpwVC0J +[quote3]: https://groups.google.com/d/msg/django-rest-framework/flsXbvYqRoY/9lSyntOf5cUJ +[image]: ../img/quickstart.png +[readthedocs]: https://readthedocs.org/ +[tut]: ../tutorial/1-serialization.md +[sandbox]: http://restframework.herokuapp.com/ diff --git a/docs/topics/rest-hypermedia-hateoas.md b/docs/topics/rest-hypermedia-hateoas.md new file mode 100644 index 00000000..d7646892 --- /dev/null +++ b/docs/topics/rest-hypermedia-hateoas.md @@ -0,0 +1,53 @@ +# REST, Hypermedia & HATEOAS + +> You keep using that word "REST". I do not think it means what you think it means. +> +> — Mike Amundsen, [REST fest 2012 keynote][cite]. + +First off, the disclaimer. The name "Django REST framework" was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs". + +If you are serious about designing a Hypermedia APIs, you should look to resources outside of this documentation to help inform your design choices. + +The following fall into the "required reading" category. + +* Roy Fielding's dissertation - [Architectural Styles and +the Design of Network-based Software Architectures][dissertation]. +* Roy Fielding's "[REST APIs must be hypertext-driven][hypertext-driven]" blog post. +* Leonard Richardson & Sam Ruby's [RESTful Web Services][restful-web-services]. +* Mike Amundsen's [Building Hypermedia APIs with HTML5 and Node][building-hypermedia-apis]. +* Steve Klabnik's [Designing Hypermedia APIs][designing-hypermedia-apis]. +* The [Richardson Maturity Model][maturitymodel]. + +For a more thorough background, check out Klabnik's [Hypermedia API reading list][readinglist]. + +## Building Hypermedia APIs with REST framework + +REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style. + +## What REST framework provides. + +It is self evident that REST framework makes it possible to build Hypermedia APIs. The browseable API that it offers is built on HTML - the hypermedia language of the web. + +REST framework also includes [serialization] and [parser]/[renderer] components that make it easy to build appropriate media types, [hyperlinked relations][fields] for building well-connected systems, and great support for [content negotiation][conneg]. + +## What REST framework doesn't provide. + +What REST framework doesn't do is give you is machine readable hypermedia formats such as [Collection+JSON][collection] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope. + +[cite]: http://vimeo.com/channels/restfest/page:2 +[dissertation]: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm +[hypertext-driven]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven +[restful-web-services]: +[building-hypermedia-apis]: … +[designing-hypermedia-apis]: http://designinghypermediaapis.com/ +[restisover]: http://blog.steveklabnik.com/posts/2012-02-23-rest-is-over +[readinglist]: http://blog.steveklabnik.com/posts/2012-02-27-hypermedia-api-reading-list +[maturitymodel]: http://martinfowler.com/articles/richardsonMaturityModel.html + +[collection]: http://www.amundsen.com/media-types/collection/ +[microformats]: http://microformats.org/wiki/Main_Page +[serialization]: ../api-guide/serializers.md +[parser]: ../api-guide/parsers.md +[renderer]: ../api-guide/renderers.md +[fields]: ../api-guide/fields.md +[conneg]: ../api-guide/content-negotiation.md |
