From d5edf20cee559050b70dd095bf243287bf2c2248 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 17 Nov 2013 18:26:41 +0000 Subject: gh-pages hosted docs --- topics/2.2-announcement.html | 350 ++++++++++++++ topics/2.3-announcement.html | 443 +++++++++++++++++ topics/ajax-csrf-cors.html | 263 ++++++++++ topics/browsable-api.html | 357 ++++++++++++++ topics/browser-enhancements.html | 297 ++++++++++++ topics/contributing.html | 351 ++++++++++++++ topics/credits.html | 432 +++++++++++++++++ topics/documenting-your-api.html | 302 ++++++++++++ topics/release-notes.html | 771 ++++++++++++++++++++++++++++++ topics/rest-framework-2-announcement.html | 298 ++++++++++++ topics/rest-hypermedia-hateoas.html | 266 +++++++++++ topics/writable-nested-serializers.html | 274 +++++++++++ 12 files changed, 4404 insertions(+) create mode 100644 topics/2.2-announcement.html create mode 100644 topics/2.3-announcement.html create mode 100644 topics/ajax-csrf-cors.html create mode 100644 topics/browsable-api.html create mode 100644 topics/browser-enhancements.html create mode 100644 topics/contributing.html create mode 100644 topics/credits.html create mode 100644 topics/documenting-your-api.html create mode 100644 topics/release-notes.html create mode 100644 topics/rest-framework-2-announcement.html create mode 100644 topics/rest-hypermedia-hateoas.html create mode 100644 topics/writable-nested-serializers.html (limited to 'topics') diff --git a/topics/2.2-announcement.html b/topics/2.2-announcement.html new file mode 100644 index 00000000..fbd04e29 --- /dev/null +++ b/topics/2.2-announcement.html @@ -0,0 +1,350 @@ + + + + + Django REST framework - REST framework 2.2 announcement + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

REST framework 2.2 announcement

+

The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy.

+

Python 3 support

+

Thanks to some fantastic work from Xavier Ordoquy, Django REST framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and it's worth keeping in mind that Django's Python 3 support is currently considered experimental.

+

Django 1.6's Python 3 support is expected to be officially labeled as 'production-ready'.

+

If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's Porting to Python 3 documentation.

+

Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with Django 1.5's Python compatibility.

+

Deprecation policy

+

We've now introduced an official deprecation policy, which is in line with Django's deprecation policy. This policy will make it easy for you to continue to track the latest, greatest version of REST framework.

+

The timeline for deprecation works as follows:

+
    +
  • +

    Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise PendingDeprecationWarning warnings if you use bits of API that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using python -Wd manage.py test, you'll be warned of any API changes you need to make.

    +
  • +
  • +

    Version 2.3 will escalate these warnings to DeprecationWarning, which is loud by default.

    +
  • +
  • +

    Version 2.4 will remove the deprecated bits of API entirely.

    +
  • +
+

Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.

+

Community

+

As of the 2.2 merge, we've also hit an impressive milestone. The number of committers listed in the credits, is now at over one hundred individuals. Each name on that list represents at least one merged pull request, however large or small.

+

Our mailing list and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great django-rest-framework-docs package from Marc Gibbons.

+
+

API changes

+

The 2.2 release makes a few changes to the API, in order to make it more consistent, simple, and easier to use.

+ +

The ManyRelatedField() style is being deprecated in favor of a new RelatedField(many=True) syntax.

+

For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following:

+
class UserSerializer(serializers.HyperlinkedModelSerializer):
+    questions = serializers.PrimaryKeyRelatedField(many=True)
+
+    class Meta:
+        fields = ('username', 'questions')
+
+

The new syntax is cleaner and more obvious, and the change will also make the documentation cleaner, simplify the internal API, and make writing custom relational fields easier.

+

The change also applies to serializers. If you have a nested serializer, you should start using many=True for to-many relationships. For example, a serializer representation of an Album that can contain many Tracks might look something like this:

+
class TrackSerializer(serializer.ModelSerializer):
+    class Meta:
+        model = Track
+        fields = ('name', 'duration')
+
+class AlbumSerializer(serializer.ModelSerializer):
+    tracks = TrackSerializer(many=True)
+
+    class Meta:
+        model = Album
+        fields = ('album_name', 'artist', 'tracks')
+
+

Additionally, the change also applies when serializing or deserializing data. For example to serialize a queryset of models you should now use the many=True flag.

+
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
+serializer.data
+
+

This more explicit behavior on serializing and deserializing data makes integration with non-ORM backends such as MongoDB easier, as instances to be serialized can include the __iter__ method, without incorrectly triggering list-based serialization, or requiring workarounds.

+

The implicit to-many behavior on serializers, and the ManyRelatedField style classes will continue to function, but will raise a PendingDeprecationWarning, which can be made visible using the -Wd flag.

+

Note: If you need to forcibly turn off the implicit "many=True for __iter__ objects" behavior, you can now do so by specifying many=False. This will become the default (instead of the current default of None) once the deprecation of the implicit behavior is finalised in version 2.4.

+

Cleaner optional relationships

+

Serializer relationships for nullable Foreign Keys will change from using the current null=True flag, to instead using required=False.

+

For example, is a user account has an optional foreign key to a company, that you want to express using a hyperlink, you might use the following field in a Serializer class:

+
current_company = serializers.HyperlinkedRelatedField(required=False)
+
+

This is in line both with the rest of the serializer fields API, and with Django's Form and ModelForm API.

+

Using required throughout the serializers API means you won't need to consider if a particular field should take blank or null arguments instead of required, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data.

+

The null=True argument will continue to function, and will imply required=False, but will raise a PendingDeprecationWarning.

+

Cleaner CharField syntax

+

The CharField API previously took an optional blank=True argument, which was intended to differentiate between null CharField input, and blank CharField input.

+

In keeping with Django's CharField API, REST framework's CharField will only ever return the empty string, for missing or None inputs. The blank flag will no longer be in use, and you should instead just use the required=<bool> flag. For example:

+
extra_details = CharField(required=False)
+
+

The blank keyword argument will continue to function, but will raise a PendingDeprecationWarning.

+

Simpler object-level permissions

+

Custom permissions classes previously used the signature .has_permission(self, request, view, obj=None). This method would be called twice, firstly for the global permissions check, with the obj parameter set to None, and again for the object-level permissions check when appropriate, with the obj parameter set to the relevant model instance.

+

The global permissions check and object-level permissions check are now separated into two separate methods, which gives a cleaner, more obvious API.

+
    +
  • Global permission checks now use the .has_permission(self, request, view) signature.
  • +
  • Object-level permission checks use a new method .has_object_permission(self, request, view, obj).
  • +
+

For example, the following custom permission class:

+
class IsOwner(permissions.BasePermission):
+    """
+    Custom permission to only allow owners of an object to view or edit it.
+    Model instances are expected to include an `owner` attribute.
+    """
+
+    def has_permission(self, request, view, obj=None):
+        if obj is None:
+            # Ignore global permissions check
+            return True
+
+        return obj.owner == request.user
+
+

Now becomes:

+
class IsOwner(permissions.BasePermission):
+    """
+    Custom permission to only allow owners of an object to view or edit it.
+    Model instances are expected to include an `owner` attribute.
+    """
+
+    def has_object_permission(self, request, view, obj):
+        return obj.owner == request.user
+
+

If you're overriding the BasePermission class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but its use will raise a PendingDeprecationWarning.

+

Note also that the usage of the internal APIs for permission checking on the View class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions.

+ +

When using a serializer with a HyperlinkedRelatedField or HyperlinkedIdentityField, the hyperlinks would previously use absolute URLs if the serializer context included a 'request' key, and fall back to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not.

+

From version 2.2 onwards, serializers with hyperlinked relationships always require a 'request' key to be supplied in the context dictionary. The implicit behavior will continue to function, but its use will raise a PendingDeprecationWarning.

+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/2.3-announcement.html b/topics/2.3-announcement.html new file mode 100644 index 00000000..82c2f8d0 --- /dev/null +++ b/topics/2.3-announcement.html @@ -0,0 +1,443 @@ + + + + + Django REST framework - REST framework 2.3 announcement + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

REST framework 2.3 announcement

+

REST framework 2.3 makes it even quicker and easier to build your Web APIs.

+

ViewSets and Routers

+

The 2.3 release introduces the ViewSet and Router classes.

+

A viewset is simply a type of class based view that allows you to group multiple views into a single common class.

+

Routers allow you to automatically determine the URLconf for your viewset classes.

+

As an example of just how simple REST framework APIs can now be, here's an API written in a single urls.py module:

+
"""
+A REST framework API for viewing and editing users and groups.
+"""
+from django.conf.urls.defaults import url, patterns, include
+from django.contrib.auth.models import User, Group
+from rest_framework import viewsets, routers
+
+
+# ViewSets define the view behavior.
+class UserViewSet(viewsets.ModelViewSet):
+    model = User
+
+class GroupViewSet(viewsets.ModelViewSet):
+    model = Group
+
+
+# Routers provide an easy way of automatically determining the URL conf
+router = routers.DefaultRouter()
+router.register(r'users', UserViewSet)
+router.register(r'groups', GroupViewSet)
+
+
+# Wire up our API using automatic URL routing.
+# Additionally, we include login URLs for the browseable API.
+urlpatterns = patterns('',
+    url(r'^', include(router.urls)),
+    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
+)
+
+

The best place to get started with ViewSets and Routers is to take a look at the newest section in the tutorial, which demonstrates their usage.

+

Simpler views

+

This release rationalises the API and implementation of the generic views, dropping the dependency on Django's SingleObjectMixin and MultipleObjectMixin classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.

+

This improvement is reflected in improved documentation for the GenericAPIView base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses.

+

Easier Serializers

+

REST framework lets you be totally explicit regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships.

+

The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the fields metadata of the serializer class.

+

For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class.

+
class BlogSerializer(serializers.ModelSerializer):
+    comments = serializers.PrimaryKeyRelatedField(many=True)
+
+    class Meta:
+        model = Blog
+        fields = ('id', 'title', 'created', 'comments')
+
+

As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship.

+
class BlogSerializer(serializers.ModelSerializer):
+    """
+    Don't need to specify the 'comments' field explicitly anymore.
+    """
+    class Meta:
+        model = Blog
+        fields = ('id', 'title', 'created', 'comments')
+
+

Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata.

+
class BlogSerializer(serializers.HyperlinkedModelSerializer):
+    """
+    This is a hyperlinked serializer, which default to using
+    a field named 'url' as the primary identifier.
+    Note that we can now easily also add in the 'id' field.
+    """
+    class Meta:
+        model = Blog
+        fields = ('url', 'id', 'title', 'created', 'comments')
+
+

More flexible filtering

+

The FILTER_BACKEND setting has moved to pending deprecation, in favor of a DEFAULT_FILTER_BACKENDS setting that takes a list of filter backend classes, instead of a single filter backend class.

+

The generic view filter_backend attribute has also been moved to pending deprecation in favor of a filter_backends setting.

+

Being able to specify multiple filters will allow for more flexible, powerful behavior. New filter classes to handle searching and ordering of results are planned to be released shortly.

+
+

API Changes

+

Simplified generic view classes

+

The functionality provided by SingleObjectAPIView and MultipleObjectAPIView base classes has now been moved into the base class GenericAPIView. The implementation of this base class is simple enough that providing subclasses for the base classes of detail and list views is somewhat unnecessary.

+

Additionally the base generic view no longer inherits from Django's SingleObjectMixin or MultipleObjectMixin classes, simplifying the implementation, and meaning you don't need to cross-reference across to Django's codebase.

+

Using the SingleObjectAPIView and MultipleObjectAPIView base classes continues to be supported, but will raise a PendingDeprecationWarning. You should instead simply use GenericAPIView as the base for any generic view subclasses.

+

Removed attributes

+

The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unused and have now been entirely removed.

+
    +
  • context_object_name
  • +
  • get_context_data()
  • +
  • get_context_object_name()
  • +
+

The following attributes and methods, which were previously present as part of Django's generic view implementations have also been entirely removed.

+
    +
  • paginator_class
  • +
  • get_paginator()
  • +
  • get_allow_empty()
  • +
  • get_slug_field()
  • +
+

There may be cases when removing these bits of API might mean you need to write a little more code if your view has highly customized behavior, but generally we believe that providing a coarser-grained API will make the views easier to work with, and is the right trade-off to make for the vast majority of cases.

+

Note that the listed attributes and methods have never been a documented part of the REST framework API, and as such are not covered by the deprecation policy.

+

Simplified methods

+

The get_object and get_paginate_by methods no longer take an optional queryset argument. This makes overridden these methods more obvious, and a little more simple.

+

Using an optional queryset with these methods continues to be supported, but will raise a PendingDeprecationWarning.

+

The paginate_queryset method no longer takes a page_size argument, or returns a four-tuple of pagination information. Instead it simply takes a queryset argument, and either returns a page object with an appropriate page size, or returns None, if pagination is not configured for the view.

+

Using the page_size argument is still supported and will trigger the old-style return type, but will raise a PendingDeprecationWarning.

+

Deprecated attributes

+

The following attributes are used to control queryset lookup, and have all been moved into a pending deprecation state.

+
    +
  • pk_url_kwarg = 'pk'
  • +
  • slug_url_kwarg = 'slug'
  • +
  • slug_field = 'slug'
  • +
+

Their usage is replaced with a single attribute:

+
    +
  • lookup_field = 'pk'
  • +
+

This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the lookup_field argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name.

+

For example, a view with 'username' based lookup might look like this:

+
class UserDetail(generics.RetrieveAPIView):
+    lookup_field = 'username'
+    queryset = User.objects.all()
+    serializer_class = UserSerializer
+
+

And would have the following entry in the urlconf:

+
 url(r'^users/(?P<username>\w+)/$', UserDetail.as_view()),
+
+

Usage of the old-style attributes continues to be supported, but will raise a PendingDeprecationWarning.

+

The allow_empty attribute is also deprecated. To use allow_empty=False style behavior you should explicitly override get_queryset and raise an Http404 on empty querysets.

+

For example:

+
class DisallowEmptyQuerysetMixin(object):
+    def get_queryset(self):
+        queryset = super(DisallowEmptyQuerysetMixin, self).get_queryset()
+        if not queryset.exists():
+            raise Http404
+        return queryset
+
+

In our opinion removing lesser-used attributes like allow_empty helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-enforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views.

+

Simpler URL lookups

+

The HyperlinkedRelatedField class now takes a single optional lookup_field argument, that replaces the pk_url_kwarg, slug_url_kwarg, and slug_field arguments.

+

For example, you might have a field that references it's relationship by a hyperlink based on a slug field:

+
    account = HyperlinkedRelatedField(read_only=True,
+                                      lookup_field='slug',
+                                      view_name='account-detail')
+
+

Usage of the old-style attributes continues to be supported, but will raise a PendingDeprecationWarning.

+

FileUploadParser

+

2.3 adds a FileUploadParser parser class, that supports raw file uploads, in addition to the existing multipart upload support.

+

DecimalField

+

2.3 introduces a DecimalField serializer field, which returns Decimal instances.

+

For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering Decimal instances to your renderer implementation.

+

ModelSerializers and reverse relationships

+

The support for adding reverse relationships to the fields option on a ModelSerializer class means that the get_related_field and get_nested_field method signatures have now changed.

+

In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now (self, model_field, related_model, to_many). For reverse relationships model_field will be None.

+

The old-style signature will continue to function but will raise a PendingDeprecationWarning.

+

View names and descriptions

+

The mechanics of how the names and descriptions used in the browseable API are generated has been modified and cleaned up somewhat.

+

If you've been customizing this behavior, for example perhaps to use rst markup for the browseable API, then you'll need to take a look at the implementation to see what updates you need to make.

+

Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated.

+
+

Other notes

+

More explicit style

+

The usage of model attribute in generic Views is still supported, but it's usage is generally being discouraged throughout the documentation, in favour of the setting the more explicit queryset and serializer_class attributes.

+

For example, the following is now the recommended style for using generic views:

+
class AccountListView(generics.RetrieveAPIView):
+    queryset = MyModel.objects.all()
+    serializer_class = MyModelSerializer
+
+

Using an explicit queryset and serializer_class attributes makes the functioning of the view more clear than using the shortcut model attribute.

+

It also makes the usage of the get_queryset() or get_serializer_class() methods more obvious.

+
class AccountListView(generics.RetrieveAPIView):
+    serializer_class = MyModelSerializer
+
+    def get_queryset(self):
+        """
+        Determine the queryset dynamically, depending on the
+        user making the request.
+
+        Note that overriding this method follows on more obviously now
+        that an explicit `queryset` attribute is the usual view style.
+        """
+        return self.user.accounts
+
+

Django 1.3 support

+

The 2.3.x release series will be the last series to provide compatibility with Django 1.3.

+

Version 2.2 API changes

+

All API changes in 2.2 that previously raised PendingDeprecationWarning will now raise a DeprecationWarning, which is loud by default.

+

What comes next?

+
    +
  • Support for read-write nested serializers is almost complete, and due to be released in the next few weeks.
  • +
  • Extra filter backends for searching and ordering of results are planned to be added shortly.
  • +
+

The next few months should see a renewed focus on addressing outstanding tickets. The 2.4 release is currently planned for around August-September.

+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/ajax-csrf-cors.html b/topics/ajax-csrf-cors.html new file mode 100644 index 00000000..47a73333 --- /dev/null +++ b/topics/ajax-csrf-cors.html @@ -0,0 +1,263 @@ + + + + + Django REST framework - Working with AJAX, CSRF & CORS + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

Working with AJAX, CSRF & CORS

+
+

"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

+
+

Javascript clients

+

If you’re building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.

+

AJAX requests that are made within the same context as the API they are interacting with will typically use SessionAuthentication. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.

+

AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as TokenAuthentication.

+

CSRF protection

+

Cross Site Request Forgery protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.

+

To guard against these type of attacks, you need to do two things:

+
    +
  1. Ensure that the 'safe' HTTP operations, such as GET, HEAD and OPTIONS cannot be used to alter any server-side state.
  2. +
  3. Ensure that any 'unsafe' HTTP operations, such as POST, PUT, PATCH and DELETE, always require a valid CSRF token.
  4. +
+

If you're using SessionAuthentication you'll need to include valid CSRF tokens for any POST, PUT, PATCH or DELETE operations.

+

In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.

+

CORS

+

Cross-Origin Resource Sharing is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.

+

The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.

+

Otto Yiu maintains the django-cors-headers package, which is known to work correctly with REST framework APIs.

+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/browsable-api.html b/topics/browsable-api.html new file mode 100644 index 00000000..88165d49 --- /dev/null +++ b/topics/browsable-api.html @@ -0,0 +1,357 @@ + + + + + Django REST framework - The Browsable API + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

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, 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 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 and Chrome.

+

Customizing

+

The browsable API is built with Twitter's Bootstrap (v 2.1.1), making it easy to customize the look-and-feel.

+

To customize the default style, create a template called rest_framework/api.html that extends from rest_framework/base.html. For example:

+

templates/rest_framework/api.html

+
{% extends "rest_framework/base.html" %}
+
+...  # Override blocks with required customizations
+
+

Overriding the default theme

+

To replace the default theme, 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. There are also pre-made themes available at Bootswatch. 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.

+

Full example:

+
{% extends "rest_framework/base.html" %}
+
+{% block bootstrap_theme %}
+    <link rel="stylesheet" href="http://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
+{% endblock %}
+
+{% block bootstrap_navbar_variant %}{% endblock %}
+
+

For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the style block.

+
+

Cerulean theme

+

Screenshot of the bootswatch 'Cerulean' theme

+
+

Slate theme

+

Screenshot of the bootswatch 'Slate' theme

+
+

Blocks

+

All of the blocks available in the browsable API base template that can be used in your api.html.

+
    +
  • bodyclass - Class attribute for the <body> tag, empty by default.
  • +
  • bootstrap_theme - CSS for the Bootstrap theme.
  • +
  • bootstrap_navbar_variant - CSS class for the navbar.
  • +
  • branding - Branding section of the navbar, see Bootstrap components.
  • +
  • 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.
  • +
  • footer - Any copyright notices or similar footer materials can go here (by default right-aligned).
  • +
  • script - JavaScript files for the page.
  • +
  • style - CSS stylesheets for the page.
  • +
  • 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 standard Bootstrap components 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 will display a tooltip on hover events.

+

Login Template

+

To add branding and customize the look-and-feel of the login template, create a template called login.html and add it to your project, eg: templates/rest_framework/login.html. The template should extend from rest_framework/login_base.html.

+

You can add your site name or branding by including the branding block:

+
{% block branding %}
+    <h3 style="margin: 0 0 20px;">My Site Name</h3>
+{% endblock %}
+
+

You can also customize the style by adding the bootstrap_theme or style block similar to api.html.

+

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)
  • +
  • display_edit_forms : A boolean indicating whether or not POST, PUT and PATCH forms will be displayed
  • +
  • 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
  • +
+

You can override the BrowsableAPIRenderer.get_context() method to customise the context that gets passed to the template.

+

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.

+

Autocompletion

+

When a ChoiceField has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly. One solution is to replace the selector by an autocomplete widget, that only loads and renders a subset of the available options as needed.

+

There are a variety of packages for autocomplete widgets, such as django-autocomplete-light. To setup django-autocomplete-light, follow the installation documentation, add the the following to the api.html template:

+
{% block script %}
+{{ block.super }}
+{% include 'autocomplete_light/static.html' %}
+{% endblock %}
+
+

You can now add the autocomplete_light.ChoiceWidget widget to the serializer field.

+
import autocomplete_light
+
+class BookSerializer(serializers.ModelSerializer):
+    author = serializers.ChoiceField(
+        widget=autocomplete_light.ChoiceWidget('AuthorAutocomplete')
+    )
+
+    class Meta:
+        model = Book
+
+
+

Autocomplete

+

Screenshot of the autocomplete-light widget

+
+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/browser-enhancements.html b/topics/browser-enhancements.html new file mode 100644 index 00000000..7f71b932 --- /dev/null +++ b/topics/browser-enhancements.html @@ -0,0 +1,297 @@ + + + + + Django REST framework - Browser enhancements + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

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, 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.

+

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".

+

HTTP header based method overriding

+

REST framework also supports method overriding via the semi-standard X-HTTP-Method-Override header. This can be useful if you are working with non-form content such as JSON and are working with an older web server and/or hosting provider that doesn't recognise particular HTTP methods such as PATCH. For example Amazon Web Services ELB.

+

To use it, make a POST request, setting the X-HTTP-Method-Override header.

+

For example, making a PATCH request via POST in jQuery:

+
$.ajax({
+    url: '/myresource/',
+    method: 'POST',
+    headers: {'X-HTTP-Method-Override': 'PATCH'},
+    ...
+});
+
+

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 determining 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. There remains +ongoing discussion about adding support for PUT and DELETE, +as well as how to support content types other than form-encoded data.

+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/contributing.html b/topics/contributing.html new file mode 100644 index 00000000..4c96c60c --- /dev/null +++ b/topics/contributing.html @@ -0,0 +1,351 @@ + + + + + Django REST framework - Contributing to REST framework + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

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

+
+

There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.

+

Community

+

If you use and enjoy REST framework please consider staring the project on GitHub, and upvoting it on Django packages. Doing so helps potential new users see that the project is well used, and help us continue to attract new users.

+

You might also consider writing a blog post on your experience with using REST framework, writing a tutorial about using the project with a particular javascript framework, or simply sharing the love on Twitter.

+

Other really great ways you can help move the community forward include helping answer questions on the discussion group, or setting up an email alert on StackOverflow so that you get notified of any new questions with the django-rest-framework tag.

+

When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.

+

Issues

+

It's really helpful if you make sure you address issues to the correct channel. Usage questions should be directed to the discussion group. Feature requests, bug reports and other issues should be raised on the GitHub issue tracker.

+

Some tips on good issue reporting:

+
    +
  • When describing issues try to phrase your ticket in terms of the behavior you think needs changing rather than the code you think need changing.
  • +
  • Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
  • +
  • +

    If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.

    +
  • +
  • +

    TODO: Triage

    +
  • +
+

Development

+
    +
  • git clone & PYTHONPATH
  • +
  • Pep8
  • +
  • Recommend editor that runs pep8
  • +
+

Pull requests

+
    +
  • Make pull requests early
  • +
  • Describe branching
  • +
+

Managing compatibility issues

+
    +
  • Describe compat module
  • +
+

Testing

+
    +
  • Running the tests
  • +
  • tox
  • +
+

Documentation

+

The documentation for REST framework is built from the Markdown source files in the docs directory.

+

There are many great markdown editors that make working with the documentation really easy. The Mou editor for Mac is one such editor that comes highly recommended.

+

Building the documentation

+

To build the documentation, simply run the mkdocs.py script.

+
./mkdocs.py
+
+

This will build the html output into the html directory.

+

You can build the documentation and open a preview in a browser window by using the -p flag.

+
./mkdocs.py -p
+
+

Language style

+

Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.

+

Some other tips:

+
    +
  • Keep paragraphs reasonably short.
  • +
  • Use double spacing after the end of sentences.
  • +
  • Don't use the abbreviations such as 'e.g..' but instead use long form, such as 'For example'.
  • +
+

Markdown style

+

There are a couple of conventions you should follow when working on the documentation.

+
1. Headers
+

Headers should use the hash style. For example:

+
### Some important topic
+
+

The underline style should not be used. Don't do this:

+
Some important topic
+====================
+
+ +

Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.

+
Here is a link to [some other thing][other-thing].
+
+More text...
+
+[other-thing]: http://example.com/other/thing
+
+

This style helps keep the documentation source consistent and readable.

+

If you are hyperlinking to another REST framework document, you should use a relative link, and link to the .md suffix. For example:

+
[authentication]: ../api-guide/authentication.md
+
+

Linking in this style means you'll be able to click the hyperlink in your markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.

+
3. Notes
+

If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:

+
---
+
+**Note:** Make sure you do this thing.
+
+---
+
+

Third party packages

+
    +
  • Django reusable app
  • +
+

Core committers

+
    +
  • Still use pull reqs
  • +
  • Credits
  • +
+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/credits.html b/topics/credits.html new file mode 100644 index 00000000..03f0ba76 --- /dev/null +++ b/topics/credits.html @@ -0,0 +1,432 @@ + + + + + Django REST framework - Credits + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

Credits

+

The following people have helped make REST framework great.

+ +

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.

+

The live sandbox is hosted on Heroku.

+

Various inspiration taken from the Rails, Piston, Tastypie, Dagny and django-viewsets projects.

+

Development of REST framework 2.0 was sponsored by DabApps.

+

Contact

+

For usage questions please see the REST framework discussion group.

+

You can also contact @_tomchristie directly on twitter.

+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/documenting-your-api.html b/topics/documenting-your-api.html new file mode 100644 index 00000000..79bba0d6 --- /dev/null +++ b/topics/documenting-your-api.html @@ -0,0 +1,302 @@ + + + + + Django REST framework - Documenting your API + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

Documenting your API

+
+

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state.

+

— Roy Fielding, REST APIs must be hypertext driven

+
+

There are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints.

+

Endpoint documentation

+

The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.

+
+

Django REST Swagger

+

Marc Gibbons' Django REST Swagger integrates REST framework with the Swagger API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.

+

The package is fully documented, well supported, and comes highly recommended.

+

Django REST Swagger supports REST framework versions 2.3 and above.

+

Screenshot - Django REST Swagger

+
+

REST Framework Docs

+

The REST Framework Docs package is an earlier project, also by Marc Gibbons, that offers clean, simple autogenerated documentation for your API.

+

Screenshot - REST Framework Docs

+
+

Apiary

+

There are various other online tools and services for providing API documentation. One notable service is Apiary. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing & prototyping, and various other tools.

+

Screenshot - Apiary

+
+

Self describing APIs

+

The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.

+

Screenshot - Self describing API

+
+

Setting the title

+

The title that is used in the browsable API is generated from the view class name or function name. Any trailing View or ViewSet suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.

+

For example, the view UserListView, will be named User List when presented in the browsable API.

+

When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set UserViewSet will generate views named User List and User Instance.

+

Setting the description

+

The description in the browsable API is generated from the docstring of the view or viewset.

+

If the python markdown library is installed, then markdown syntax may be used in the docstring, and will be converted to HTML in the browsable API. For example:

+
class AccountListView(views.APIView):
+    """
+    Returns a list of all **active** accounts in the system.
+
+    For more details on how accounts are activated please [see here][ref].
+
+    [ref]: http://example.com/activating-accounts
+    """
+
+

Note that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view.

+

The OPTIONS method

+

REST framework APIs also support programmatically accessible descriptions, using the OPTIONS HTTP method. A view will respond to an OPTIONS request with metadata including the name, description, and the various media types it accepts and responds with.

+

When using the generic views, any OPTIONS requests will additionally respond with metadata regarding any POST or PUT actions available, describing which fields are on the serializer.

+

You can modify the response behavior to OPTIONS requests by overriding the metadata view method. For example:

+
def metadata(self, request):
+    """
+    Don't include the view description in OPTIONS responses.
+    """ 
+    data = super(ExampleView, self).metadata(request)
+    data.pop('description')
+    return data
+
+
+

The hypermedia approach

+

To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.

+

In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the media types that are used. The available actions take may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.

+

To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The REST, Hypermedia & HATEOAS section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.

+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/release-notes.html b/topics/release-notes.html new file mode 100644 index 00000000..5d4322b2 --- /dev/null +++ b/topics/release-notes.html @@ -0,0 +1,771 @@ + + + + + Django REST framework - Release Notes + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

Release Notes

+
+

Release Early, Release Often

+

— Eric S. Raymond, The Cathedral and the Bazaar.

+
+

Versioning

+

Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.

+

Medium version numbers (0.x.0) may include API changes, in line with the deprecation policy. You should read the release notes carefully before upgrading between medium point releases.

+

Major version numbers (x.0.0) are reserved for substantial project milestones. No major point releases are currently planned.

+

Deprecation policy

+

REST framework releases follow a formal deprecation policy, which is in line with Django's deprecation policy.

+

The timeline for deprecation of a feature present in version 1.0 would work as follows:

+
    +
  • +

    Version 1.1 would remain fully backwards compatible with 1.0, but would raise PendingDeprecationWarning warnings if you use the feature that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using python -Wd manage.py test, you'll be warned of any API changes you need to make.

    +
  • +
  • +

    Version 1.2 would escalate these warnings to DeprecationWarning, which is loud by default.

    +
  • +
  • +

    Version 1.3 would remove the deprecated bits of API entirely.

    +
  • +
+

Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.

+

Upgrading

+

To upgrade Django REST framework to the latest version, use pip:

+
pip install -U djangorestframework
+
+

You can determine your currently installed version using pip freeze:

+
pip freeze | grep djangorestframework
+
+
+

2.3.x series

+

2.3.9

+

Date: 15th November 2013

+
    +
  • Fix Django 1.6 exception API compatibility issue caused by ValidationError.
  • +
  • Include errors in HTML forms in browsable API.
  • +
  • Added JSON renderer support for numpy scalars.
  • +
  • Added transform_<fieldname> hooks on serializers for easily modifying field output.
  • +
  • Added get_context hook in BrowsableAPIRenderer.
  • +
  • Allow serializers to be passed files but no data.
  • +
  • HTMLFormRenderer now renders serializers directly to HTML without needing to create an intermediate form object.
  • +
  • Added get_filter_backends hook.
  • +
  • Added queryset aggregates to allowed fields in OrderingFilter.
  • +
  • Bugfix: Fix decimal suppoprt with YAMLRenderer.
  • +
  • Bugfix: Fix submission of unicode in browsable API through raw data form.
  • +
+

2.3.8

+

Date: 11th September 2013

+
    +
  • Added DjangoObjectPermissions, and DjangoObjectPermissionsFilter.
  • +
  • Support customizable exception handling, using the EXCEPTION_HANDLER setting.
  • +
  • Support customizable view name and description functions, using the VIEW_NAME_FUNCTION and VIEW_DESCRIPTION_FUNCTION settings.
  • +
  • Added MAX_PAGINATE_BY setting and max_paginate_by generic view attribute.
  • +
  • Added cache attribute to throttles to allow overriding of default cache.
  • +
  • 'Raw data' tab in browsable API now contains pre-populated data.
  • +
  • 'Raw data' and 'HTML form' tab preference in browseable API now saved between page views.
  • +
  • Bugfix: required=True argument fixed for boolean serializer fields.
  • +
  • Bugfix: client.force_authenticate(None) should also clear session info if it exists.
  • +
  • Bugfix: Client sending empty string instead of file now clears FileField.
  • +
  • Bugfix: Empty values on ChoiceFields with required=False now consistently return None.
  • +
+

2.3.7

+

Date: 16th August 2013

+
    +
  • Added APITestClient, APIRequestFactory and APITestCase etc...
  • +
  • Refactor SessionAuthentication to allow esier override for CSRF exemption.
  • +
  • Remove 'Hold down "Control" message from help_text' widget messaging when not appropriate.
  • +
  • Added admin configuration for auth tokens.
  • +
  • Bugfix: AnonRateThrottle fixed to not throttle authenticated users.
  • +
  • Bugfix: Don't set X-Throttle-Wait-Seconds when throttle does not have wait value.
  • +
  • Bugfix: Fixed PATCH button title in browsable API.
  • +
  • Bugfix: Fix issue with OAuth2 provider naive datetimes.
  • +
+

2.3.6

+

Date: 27th June 2013

+
    +
  • Added trailing_slash option to routers.
  • +
  • Include support for HttpStreamingResponse.
  • +
  • Support wider range of default serializer validation when used with custom model fields.
  • +
  • UTF-8 Support for browsable API descriptions.
  • +
  • OAuth2 provider uses timezone aware datetimes when supported.
  • +
  • Bugfix: Return error correctly when OAuth non-existent consumer occurs.
  • +
  • Bugfix: Allow FileUploadParser to correctly filename if provided as URL kwarg.
  • +
  • Bugfix: Fix ScopedRateThrottle.
  • +
+

2.3.5

+

Date: 3rd June 2013

+
    +
  • Added get_url hook to HyperlinkedIdentityField.
  • +
  • Serializer field default argument may be a callable.
  • +
  • @action decorator now accepts a methods argument.
  • +
  • Bugfix: request.user should be still be accessible in renderer context if authentication fails.
  • +
  • Bugfix: The lookup_field option on HyperlinkedIdentityField should apply by default to the url field on the serializer.
  • +
  • Bugfix: HyperlinkedIdentityField should continue to support pk_url_kwarg, slug_url_kwarg, slug_field, in a pending deprecation state.
  • +
  • Bugfix: Ensure we always return 404 instead of 500 if a lookup field cannot be converted to the correct lookup type. (Eg non-numeric AutoInteger pk lookup)
  • +
+

2.3.4

+

Date: 24th May 2013

+
    +
  • Serializer fields now support label and help_text.
  • +
  • Added UnicodeJSONRenderer.
  • +
  • OPTIONS requests now return metadata about fields for POST and PUT requests.
  • +
  • Bugfix: charset now properly included in Content-Type of responses.
  • +
  • Bugfix: Blank choice now added in browsable API on nullable relationships.
  • +
  • Bugfix: Many to many relationships with through tables are now read-only.
  • +
  • Bugfix: Serializer fields now respect model field args such as max_length.
  • +
  • Bugfix: SlugField now performs slug validation.
  • +
  • Bugfix: Lazy-translatable strings now properly serialized.
  • +
  • Bugfix: Browsable API now supports bootswatch styles properly.
  • +
  • Bugfix: HyperlinkedIdentityField now uses lookup_field kwarg.
  • +
+

Note: Responses now correctly include an appropriate charset on the Content-Type header. For example: application/json; charset=utf-8. If you have tests that check the content type of responses, you may need to update these accordingly.

+

2.3.3

+

Date: 16th May 2013

+
    +
  • Added SearchFilter
  • +
  • Added OrderingFilter
  • +
  • Added GenericViewSet
  • +
  • Bugfix: Multiple @action and @link methods now allowed on viewsets.
  • +
  • Bugfix: Fix API Root view issue with DjangoModelPermissions
  • +
+

2.3.2

+

Date: 8th May 2013

+
    +
  • Bugfix: Fix TIME_FORMAT, DATETIME_FORMAT and DATE_FORMAT settings.
  • +
  • Bugfix: Fix DjangoFilterBackend issue, failing when used on view with queryset attribute.
  • +
+

2.3.1

+

Date: 7th May 2013

+
    +
  • Bugfix: Fix breadcrumb rendering issue.
  • +
+

2.3.0

+

Date: 7th May 2013

+
    +
  • ViewSets and Routers.
  • +
  • ModelSerializers support reverse relations in 'fields' option.
  • +
  • HyperLinkedModelSerializers support 'id' field in 'fields' option.
  • +
  • Cleaner generic views.
  • +
  • Support for multiple filter classes.
  • +
  • FileUploadParser support for raw file uploads.
  • +
  • DecimalField support.
  • +
  • Made Login template easier to restyle.
  • +
  • Bugfix: Fix issue with depth>1 on ModelSerializer.
  • +
+

Note: See the 2.3 announcement for full details.

+
+

2.2.x series

+

2.2.7

+

Date: 17th April 2013

+
    +
  • Loud failure when view does not return a Response or HttpResponse.
  • +
  • Bugfix: Fix for Django 1.3 compatibility.
  • +
  • Bugfix: Allow overridden get_object() to work correctly.
  • +
+

2.2.6

+

Date: 4th April 2013

+
    +
  • OAuth2 authentication no longer requires unnecessary URL parameters in addition to the token.
  • +
  • URL hyperlinking in browsable API now handles more cases correctly.
  • +
  • Long HTTP headers in browsable API are broken in multiple lines when possible.
  • +
  • Bugfix: Fix regression with DjangoFilterBackend not worthing correctly with single object views.
  • +
  • Bugfix: OAuth should fail hard when invalid token used.
  • +
  • Bugfix: Fix serializer potentially returning None object for models that define __bool__ or __len__.
  • +
+

2.2.5

+

Date: 26th March 2013

+
    +
  • Serializer support for bulk create and bulk update operations.
  • +
  • Regression fix: Date and time fields return date/time objects by default. Fixes regressions caused by 2.2.2. See #743 for more details.
  • +
  • Bugfix: Fix 500 error is OAuth not attempted with OAuthAuthentication class installed.
  • +
  • Serializer.save() now supports arbitrary keyword args which are passed through to the object .save() method. Mixins use force_insert and force_update where appropriate, resulting in one less database query.
  • +
+

2.2.4

+

Date: 13th March 2013

+
    +
  • OAuth 2 support.
  • +
  • OAuth 1.0a support.
  • +
  • Support X-HTTP-Method-Override header.
  • +
  • Filtering backends are now applied to the querysets for object lookups as well as lists. (Eg you can use a filtering backend to control which objects should 404)
  • +
  • Deal with error data nicely when deserializing lists of objects.
  • +
  • Extra override hook to configure DjangoModelPermissions for unauthenticated users.
  • +
  • Bugfix: Fix regression which caused extra database query on paginated list views.
  • +
  • Bugfix: Fix pk relationship bug for some types of 1-to-1 relations.
  • +
  • Bugfix: Workaround for Django bug causing case where Authtoken could be registered for cascade delete from User even if not installed.
  • +
+

2.2.3

+

Date: 7th March 2013

+
    +
  • Bugfix: Fix None values for for DateField, DateTimeField and TimeField.
  • +
+

2.2.2

+

Date: 6th March 2013

+
    +
  • Support for custom input and output formats for DateField, DateTimeField and TimeField.
  • +
  • Cleanup: Request authentication is no longer lazily evaluated, instead authentication is always run, which results in more consistent, obvious behavior. Eg. Supplying bad auth credentials will now always return an error response, even if no permissions are set on the view.
  • +
  • Bugfix for serializer data being uncacheable with pickle protocol 0.
  • +
  • Bugfixes for model field validation edge-cases.
  • +
  • Bugfix for authtoken migration while using a custom user model and south.
  • +
+

2.2.1

+

Date: 22nd Feb 2013

+
    +
  • Security fix: Use defusedxml package to address XML parsing vulnerabilities.
  • +
  • Raw data tab added to browsable API. (Eg. Allow for JSON input.)
  • +
  • Added TimeField.
  • +
  • Serializer fields can be mapped to any method that takes no args, or only takes kwargs which have defaults.
  • +
  • Unicode support for view names/descriptions in browsable API.
  • +
  • Bugfix: request.DATA should return an empty QueryDict with no data, not None.
  • +
  • Bugfix: Remove unneeded field validation, which caused extra queries.
  • +
+

Security note: Following the disclosure of security vulnerabilities in Python's XML parsing libraries, use of the XMLParser class now requires the defusedxml package to be installed.

+

The security vulnerabilities only affect APIs which use the XMLParser class, by enabling it in any views, or by having it set in the DEFAULT_PARSER_CLASSES setting. Note that the XMLParser class is not enabled by default, so this change should affect a minority of users.

+

2.2.0

+

Date: 13th Feb 2013

+
    +
  • Python 3 support.
  • +
  • Added a post_save() hook to the generic views.
  • +
  • Allow serializers to handle dicts as well as objects.
  • +
  • Deprecate ManyRelatedField() syntax in favor of RelatedField(many=True)
  • +
  • Deprecate null=True on relations in favor of required=False.
  • +
  • Deprecate blank=True on CharFields, just use required=False.
  • +
  • Deprecate optional obj argument in permissions checks in favor of has_object_permission.
  • +
  • Deprecate implicit hyperlinked relations behavior.
  • +
  • Bugfix: Fix broken DjangoModelPermissions.
  • +
  • Bugfix: Allow serializer output to be cached.
  • +
  • Bugfix: Fix styling on browsable API login.
  • +
  • Bugfix: Fix issue with deserializing empty to-many relations.
  • +
  • Bugfix: Ensure model field validation is still applied for ModelSerializer subclasses with an custom .restore_object() method.
  • +
+

Note: See the 2.2 announcement for full details.

+
+

2.1.x series

+

2.1.17

+

Date: 26th Jan 2013

+
    +
  • Support proper 401 Unauthorized responses where appropriate, instead of always using 403 Forbidden.
  • +
  • Support json encoding of timedelta objects.
  • +
  • format_suffix_patterns() now supports include style URL patterns.
  • +
  • Bugfix: Fix issues with custom pagination serializers.
  • +
  • Bugfix: Nested serializers now accept source='*' argument.
  • +
  • Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
  • +
  • Bugfix: Support nullable FKs with SlugRelatedField.
  • +
  • Bugfix: Don't call custom validation methods if the field has an error.
  • +
+

Note: If the primary authentication class is TokenAuthentication or BasicAuthentication, a view will now correctly return 401 responses to unauthenticated access, with an appropriate WWW-Authenticate header, instead of 403 responses.

+

2.1.16

+

Date: 14th Jan 2013

+
    +
  • Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module.
  • +
  • Bugfix: auto_now, auto_now_add and other editable=False fields now default to read-only.
  • +
  • Bugfix: PK fields now only default to read-only if they are an AutoField or if editable=False.
  • +
  • Bugfix: Validation errors instead of exceptions when serializers receive incorrect types.
  • +
  • Bugfix: Validation errors instead of exceptions when related fields receive incorrect types.
  • +
  • Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one
  • +
+

Note: Prior to 2.1.16, The Decimals would render in JSON using floating point if simplejson was installed, but otherwise render using string notation. Now that use of simplejson has been deprecated, Decimals will consistently render using string notation. See #582 for more details.

+

2.1.15

+

Date: 3rd Jan 2013

+
    +
  • Added PATCH support.
  • +
  • Added RetrieveUpdateAPIView.
  • +
  • Remove unused internal save_m2m flag on ModelSerializer.save().
  • +
  • Tweak behavior of hyperlinked fields with an explicit format suffix.
  • +
  • Relation changes are now persisted in .save() instead of in .restore_object().
  • +
  • Bugfix: Fix issue with FileField raising exception instead of validation error when files=None.
  • +
  • Bugfix: Partial updates should not set default values if field is not included.
  • +
+

2.1.14

+

Date: 31st Dec 2012

+
    +
  • Bugfix: ModelSerializers now include reverse FK fields on creation.
  • +
  • Bugfix: Model fields with blank=True are now required=False by default.
  • +
  • Bugfix: Nested serializers now support nullable relationships.
  • +
+

Note: From 2.1.14 onwards, relational fields move out of the fields.py module and into the new relations.py module, in order to separate them from regular data type fields, such as CharField and IntegerField.

+

This change will not affect user code, so long as it's following the recommended import style of from rest_framework import serializers and referring to fields using the style serializers.PrimaryKeyRelatedField.

+

2.1.13

+

Date: 28th Dec 2012

+
    +
  • Support configurable STATICFILES_STORAGE storage.
  • +
  • Bugfix: Related fields now respect the required flag, and may be required=False.
  • +
+

2.1.12

+

Date: 21st Dec 2012

+
    +
  • Bugfix: Fix bug that could occur using ChoiceField.
  • +
  • Bugfix: Fix exception in browsable API on DELETE.
  • +
  • Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg.
  • +
+

2.1.11

+

Date: 17th Dec 2012

+
    +
  • Bugfix: Fix issue with M2M fields in browsable API.
  • +
+

2.1.10

+

Date: 17th Dec 2012

+
    +
  • Bugfix: Ensure read-only fields don't have model validation applied.
  • +
  • Bugfix: Fix hyperlinked fields in paginated results.
  • +
+

2.1.9

+

Date: 11th Dec 2012

+
    +
  • Bugfix: Fix broken nested serialization.
  • +
  • Bugfix: Fix Meta.fields only working as tuple not as list.
  • +
  • Bugfix: Edge case if unnecessarily specifying required=False on read only field.
  • +
+

2.1.8

+

Date: 8th Dec 2012

+
    +
  • Fix for creating nullable Foreign Keys with '' as well as None.
  • +
  • Added null=<bool> related field option.
  • +
+

2.1.7

+

Date: 7th Dec 2012

+
    +
  • Serializers now properly support nullable Foreign Keys.
  • +
  • Serializer validation now includes model field validation, such as uniqueness constraints.
  • +
  • Support 'true' and 'false' string values for BooleanField.
  • +
  • Added pickle support for serialized data.
  • +
  • Support source='dotted.notation' style for nested serializers.
  • +
  • Make Request.user settable.
  • +
  • Bugfix: Fix RegexField to work with BrowsableAPIRenderer.
  • +
+

2.1.6

+

Date: 23rd Nov 2012

+
    +
  • Bugfix: Unfix DjangoModelPermissions. (I am a doofus.)
  • +
+

2.1.5

+

Date: 23rd Nov 2012

+
    +
  • Bugfix: Fix DjangoModelPermissions.
  • +
+

2.1.4

+

Date: 22nd Nov 2012

+
    +
  • Support for partial updates with serializers.
  • +
  • Added RegexField.
  • +
  • Added SerializerMethodField.
  • +
  • Serializer performance improvements.
  • +
  • Added obtain_token_view to get tokens when using TokenAuthentication.
  • +
  • Bugfix: Django 1.5 configurable user support for TokenAuthentication.
  • +
+

2.1.3

+

Date: 16th Nov 2012

+
    +
  • Added FileField and ImageField. For use with MultiPartParser.
  • +
  • Added URLField and SlugField.
  • +
  • Support for read_only_fields on ModelSerializer classes.
  • +
  • Support for clients overriding the pagination page sizes. Use the PAGINATE_BY_PARAM setting or set the paginate_by_param attribute on a generic view.
  • +
  • 201 Responses now return a 'Location' header.
  • +
  • Bugfix: Serializer fields now respect max_length.
  • +
+

2.1.2

+

Date: 9th Nov 2012

+
    +
  • Filtering support.
  • +
  • Bugfix: Support creation of objects with reverse M2M relations.
  • +
+

2.1.1

+

Date: 7th Nov 2012

+
    +
  • Support use of HTML exception templates. Eg. 403.html
  • +
  • Hyperlinked fields take optional slug_field, slug_url_kwarg and pk_url_kwarg arguments.
  • +
  • Bugfix: Deal with optional trailing slashes properly when generating breadcrumbs.
  • +
  • Bugfix: Make textareas same width as other fields in browsable API.
  • +
  • Private API change: .get_serializer now uses same instance and data ordering as serializer initialization.
  • +
+

2.1.0

+

Date: 5th Nov 2012

+
    +
  • Serializer instance and data keyword args have their position swapped.
  • +
  • queryset argument is now optional on writable model fields.
  • +
  • Hyperlinked related fields optionally take slug_field and slug_url_kwarg arguments.
  • +
  • Support Django's cache framework.
  • +
  • Minor field improvements. (Don't stringify dicts, more robust many-pk fields.)
  • +
  • Bugfix: Support choice field in Browsable API.
  • +
  • Bugfix: Related fields with read_only=True do not require a queryset argument.
  • +
+

API-incompatible changes: Please read this thread regarding the instance and data keyword args before updating to 2.1.0.

+
+

2.0.x series

+

2.0.2

+

Date: 2nd Nov 2012

+
    +
  • Fix issues with pk related fields in the browsable API.
  • +
+

2.0.1

+

Date: 1st Nov 2012

+
    +
  • Add support for relational fields in the browsable API.
  • +
  • Added SlugRelatedField and ManySlugRelatedField.
  • +
  • If PUT creates an instance return '201 Created', instead of '200 OK'.
  • +
+

2.0.0

+

Date: 30th Oct 2012

+
    +
  • Fix all of the things. (Well, almost.)
  • +
  • For more information please see the 2.0 announcement.
  • +
+
+

0.4.x series

+

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 behavior
  • +
  • Minor xml and yaml fixes
  • +
  • Improve setup (e.g. use staticfiles, not the defunct ADMIN_MEDIA_PREFIX)
  • +
  • Sensible absolute URL generation, not using hacky set_script_prefix
  • +
+
+

0.3.x series

+

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 customized admin styles (e.g. grappelli)
  • +
  • Templates are now nicely namespaced.
  • +
  • Allows easier overriding.
  • +
  • Drop implied 'pk' filter if last arg in urlconf is unnamed.
  • +
  • Too magical. Explicit is better than implicit.
  • +
  • Saner template variable auto-escaping.
  • +
  • Tidier 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.x series

+

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.x series

+

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.
  • +
+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/rest-framework-2-announcement.html b/topics/rest-framework-2-announcement.html new file mode 100644 index 00000000..99a0604b --- /dev/null +++ b/topics/rest-framework-2-announcement.html @@ -0,0 +1,298 @@ + + + + + Django REST framework - Django REST framework 2 + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

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

+
+
+

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

+

"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

+

"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

+

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 independently of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.

+

The Browsable 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.

+

Browsable 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 browsable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with.

+

There are also some functionality improvements - actions such as as POST and DELETE will only display if the user has the appropriate permissions.

+

Browsable API

+

Image above: An example of the browsable 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 is a great place to get started.

+

There's also a live sandbox version of the tutorial API available for testing.

+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/rest-hypermedia-hateoas.html b/topics/rest-hypermedia-hateoas.html new file mode 100644 index 00000000..2f26f901 --- /dev/null +++ b/topics/rest-hypermedia-hateoas.html @@ -0,0 +1,266 @@ + + + + + Django REST framework - REST, Hypermedia & HATEOAS + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+

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.

+
+

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.

+ +

For a more thorough background, check out Klabnik's Hypermedia API reading list.

+

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 browsable 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 for building well-connected systems, and great support for content negotiation.

+

What REST framework doesn't provide.

+

What REST framework doesn't do is give you is machine readable hypermedia formats such as HAL, Collection+JSON, JSON API 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.

+
+
+
+
+ +
+
+ + + + + + + + + + diff --git a/topics/writable-nested-serializers.html b/topics/writable-nested-serializers.html new file mode 100644 index 00000000..0ccdc25b --- /dev/null +++ b/topics/writable-nested-serializers.html @@ -0,0 +1,274 @@ + + + + + Django REST framework - Writable nested serializers + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + +
+ +
+ +
+ + + + +
+
+ +
+
+

To save HTTP requests, it may be convenient to send related documents along with the request.

+

JSON API specification for Ember Data.

+
+

Writable nested serializers

+

Although flat data structures serve to properly delineate between the individual entities in your service, there are cases where it may be more appropriate or convenient to use nested data structures.

+

Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependancies between the various model instances, and the need to save or delete multiple instances in a single action.

+

One-to-many data structures

+

Example of a read-only nested serializer. Nothing complex to worry about here.

+
class ToDoItemSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = ToDoItem
+        fields = ('text', 'is_completed')
+
+class ToDoListSerializer(serializers.ModelSerializer):
+    items = ToDoItemSerializer(many=True, read_only=True)
+
+    class Meta:
+        model = ToDoList
+        fields = ('title', 'items')
+
+

Some example output from our serializer.

+
{
+    'title': 'Leaving party preperations',
+    'items': {
+        {'text': 'Compile playlist', 'is_completed': True},
+        {'text': 'Send invites', 'is_completed': False},
+        {'text': 'Clean house', 'is_completed': False}            
+    }
+}
+
+

Let's take a look at updating our nested one-to-many data structure.

+

Validation errors

+

Adding and removing items

+

Making PATCH requests

+
+
+
+
+ +
+
+ + + + + + + + + + -- cgit v1.2.3