Building Better Web Services With Django (Part 1)

Building a RESTful webservice is pretty straight-forward with Django, but in many cases you want to have both a human readable website and a machine readable api. A lot of websites solve this problem by using as the human site, an as the machine site. They also will typically have different structures to support the different usecases.

Unless your documentation is really excellent and the person writing the client to your service actually reads it building a client for the service is an error prone process. In an ideal world the developer would be able to browse the website and use the same urls in their client program. Fortunately HTTP has two headers which make it possible to do just that, Content-Type and Accept.

The Content-Type header describes the type of data that is included in the body of the HTTP request. Typically this will be values such as text/html, application/json or application/x-www-form-urlencoded. A content type is sent by the client when POSTing or PUTing data, and whenever the webserver includes some data in its response. The Accept header is sent by a client to specify what content types it can accept in the response. This header has a more complicated format that Content-Type because it can used to specify a number of different content types and to give a weighting to each.

When combined these two headers can be used to allow a normal user to browse the site and to allow a robot to make api calls on the same site, using the same urls. This makes it easier both for the creator of the programmer accessing your site and for you because you can easily share code between the site and your api.

I’m going to outline a decorator that will let write a webservice such as this, that will support HTML and JSON output, and JSON and form encoded data as inputs.

First we’ll create a decorator that parses any post data as JSON and passes it the view as the second parameter (after the request object). It will also JSON encode any return value that’s not an HTTPResponse object.

import simplejson as json

from django.http import HttpResponse

def json_view(func):
    def wrap(req, *args, **kwargs):
            j = json.loads(req.raw_post_data)
        except ValueError:
            j = None

        resp = func(req, j, *args, **kwargs)

        if isinstance(resp, HttpResponse):
            return resp

        return HttpResponse(json.dumps(resp), mimetype="application/json")

    return wrap

This decorator should be pretty easy follow, but here is an example to illustrate its use.

def view(req, json, arg1, arg2):
    obj = get_obj(arg1, arg2)
    if req.method == "POST" and json is not None:
        # process json here
        return {"status": "ok"}
        return {"status": "failed"}

This really cuts down on the code you need to write, but this view only handles JSON as its input and output. Next we need to parse the Accept headers and return an ordered list of content types so we can choose the preferred option. No need to reinvent the wheel, so we just pull some code from

All the parts are in place now, and in my next post we’ll create a decorator which takes these parts ands puts them together.


Author: Andrew Wilkinson

I'm a computer programmer and team leader working at the UK grocer and tech company, Ocado Technology. I mostly write multithreaded real time systems in Java, but in the past I've worked with C#, C++ and Python.

4 thoughts on “Building Better Web Services With Django (Part 1)”

  1. Hi Moritz,

    No, because that function only tells you if it is an AJAX request. Here I’m building something can be consumed by programs running on other machines, not just browsers.


  2. Hi, Andrew.

    I am building a Python web service for my final year project. I am still in the first stage of the project and everything is still in scratch. My project is bout using Silverlight as the front end and grab some data from django through the web service. I am not familiar with web service programming. So, is that possible to do so ?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s