Getting Started - ViewsΒΆ

Note

A live sandbox instance of this API is available:

http://api.django-rest-framework.org/resource-example/

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

curl -X GET http://api.django-rest-framework.org/resource-example/ -H 'Accept: text/plain'

We’re going to start off with a simple example, that demonstrates a few things:

  1. Creating views.
  2. Linking views.
  3. Writing method handlers on views.
  4. Adding form validation to views.

First we’ll define two views in our urlconf.

urls.py

from django.conf.urls.defaults import patterns, url
from resourceexample.views import ExampleView, AnotherExampleView

urlpatterns = patterns('',
    url(r'^$',                 ExampleView.as_view(), name='example-resource'),
    url(r'^(?P<num>[0-9]+)/$', AnotherExampleView.as_view(), name='another-example'),
)

Now we’ll add a form that we’ll use for input validation. This is completely optional, but it’s often useful.

forms.py

from django import forms

class MyForm(forms.Form):
    foo = forms.BooleanField(required=False)
    bar = forms.IntegerField(help_text='Must be an integer.')
    baz = forms.CharField(max_length=32, help_text='Free text.  Max length 32 chars.')

Now we’ll write our views. The first is a read only view that links to three instances of the second. The second view just has some stub handler methods to help us see that our example is working.

views.py

from django.core.urlresolvers import reverse

from djangorestframework.views import View
from djangorestframework.response import Response
from djangorestframework import status

from resourceexample.forms import MyForm


class ExampleView(View):
    """
    A basic read-only view that points to 3 other views.
    """

    def get(self, request):
        """
        Handle GET requests, returning a list of URLs pointing to 3 other views.
        """
        return {"Some other resources": [reverse('another-example', kwargs={'num':num}) for num in range(3)]}


class AnotherExampleView(View):
    """
    A basic view, that can be handle GET and POST requests.
    Applies some simple form validation on POST requests.
    """
    form = MyForm

    def get(self, request, num):
        """
        Handle GET requests.
        Returns a simple string indicating which view the GET request was for.
        """
        if int(num) > 2:
            return Response(status.HTTP_404_NOT_FOUND)
        return "GET request to AnotherExampleResource %s" % num
    
    def post(self, request, num):
        """
        Handle POST requests, with form validation.
        Returns a simple string indicating what content was supplied.
        """
        if int(num) > 2:
            return Response(status.HTTP_404_NOT_FOUND)
        return "POST request to AnotherExampleResource %s, with content: %s" % (num, repr(self.CONTENT))

That’s us done. Our API now provides both programmatic access using JSON and XML, as well a nice browseable HTML view, so we can now access it both from the browser:

And from the command line:

 # Demonstrates API's input validation using form input
 bash: curl -X POST --data 'foo=true' http://api.django-rest-framework.org/resource-example/1/
 {"detail": {"bar": ["This field is required."], "baz": ["This field is required."]}}

 #  Demonstrates API's input validation using JSON input
 bash: curl -X POST -H 'Content-Type: application/json' --data-binary '{"foo":true}' http://api.django-rest-framework.org/resource-example/1/
{"detail": {"bar": ["This field is required."], "baz": ["This field is required."]}}

Project Versions

Previous topic

views

Next topic

Getting Started - Model Views

This Page