Using Django REST framework Mixin classes

This example demonstrates creating a REST API without using Django REST framework’s Resource or ModelResource, but instead using Django View class, and adding the EmitterMixin class to provide full HTTP Accept header content negotiation, a browseable Web API, and much of the other goodness that Django REST framework gives you for free.

Note

A live sandbox instance of this API is available for testing:

You can browse the API using a web browser, or from the command line:

curl -X GET http://api.django-rest-framework.org/mixin/

URL configuration

Everything we need for this example can go straight into the URL conf...

urls.py

from djangorestframework.compat import View  # Use Django 1.3's django.views.generic.View, or fall back to a clone of that if Django < 1.3 
from djangorestframework.mixins import ResponseMixin
from djangorestframework.renderers import DEFAULT_RENDERERS
from djangorestframework.response import Response

from django.conf.urls.defaults import patterns, url
from django.core.urlresolvers import reverse


class ExampleView(ResponseMixin, View):
    """An example view using Django 1.3's class based views.
    Uses djangorestframework's RendererMixin to provide support for multiple output formats."""
    renderers = DEFAULT_RENDERERS

    def get(self, request):
        response = Response(200, {'description': 'Some example content',
                                  'url': reverse('mixin-view')})
        return self.render(response)


urlpatterns = patterns('',
    url(r'^$', ExampleView.as_view(), name='mixin-view'),
)

That’s it. Auto-magically our API now supports multiple output formats, specified either by using standard HTTP Accept header content negotiation, or by using the &_accept=application/json style parameter overrides. We even get a nice HTML view which can be used to self-document our API.

Project Versions

Table Of Contents

Previous topic

Sandbox Root API

This Page