Building RESTful API with Django

In order to demonstrate how RESTframework for Cocoa works, I’m going to create a small RESTful API demo in Django/Python and use that as a demo web service we’re gonna query from our soon-to-be demo iOS app. Hopefully, you can also pick up a thing or two from this tutorial as well since Django seems to be a very powerful framework for building RESTful APIs with. If you don’t want to bother with Django, you can simply download the project (see the end of this post) and run it as a demo web service. Next post will explain how to use my RESTframework to consume this web service.

Requirements

You’ll need Python, of course, and I’ve tested this on v2.7 although I’m pretty sure it should also work on v2.6 and possibly v2.5. Then you’ll need django and djangorestframework both available for install with pip or easy_install.

Django project

Create a new django project and the first django app.

$ django-admin.py startproject DjangoTest
$ cd DjangoTest
$ django-admin.py startapp api

Now we need to modify our initial project settings. For the sake of simplicity, I’ll be using SQLite3 database since it doesn’t require any installation or setup. To do this, edit settings.py in your project dir.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'database.db',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

Another thing we need to do in settings.py is to add your app and djangorestframework to the installed apps section.

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'DjangoTest.api',
    'djangorestframework',
)

Okay, now let’s run and test if it worked.

$ python manage.py runserver

Now go to http://localhost:8000/ and make sure you see “It worked” message.

Next step is creating some resources for our RESTful API. I’ve created a simple model to hold a name and creation date. Looks like this:

class Object(models.Model):
	name = models.CharField(max_length=50)
	date = models.DateTimeField()

We’re almost there. We need to sync our database now after we’ve created the model (do this every time you change the model, see more info here)

$ python manage.py syncdb

RESTful API using django-rest-framework

Now our django project is ready. Using djangorestframework we will add RESTful API interface for our ‘api’ app. Assuming you’ve installed it correctly, all we need to do is to create another python file where we will store our resources. Name it resources.py and put this inside:

from djangorestframework.resources import ModelResource
from api.models import Object
 
class ObjectResource(ModelResource):
	model = Object
	fields = ('name', 'date')

When this is done, we need to add some URLs where our resources will be located. I’m using nifty views provided by djangorestframework which work with your models without a single line of code. You get 2 URLs for viewing a list of objects (or creating a new one) and one for viewing your object details. urls.py looks like this:

from django.conf.urls.defaults import patterns, include, url
 
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
from api.resources import ObjectResource
 
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'DjangoTest.views.home', name='home'),
    # url(r'^DjangoTest/', include('DjangoTest.foo.urls')),
 
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
 
    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
 
    url(r'^objects/$', ListOrCreateModelView.as_view(resource=ObjectResource), name='object-root'),
    url(r'^objects/(?P[^/]+)/$', InstanceModelView.as_view(resource=ObjectResource), name='object'),
)

That’s it. Save and run your project and you’ll be able to access your resources at http://localhost:8000/objects/
For example, querying an URL like this one (providing you added an object with id=1) http://localhost:8000/objects/1/?_accept=application/json would result in this:

{"date": "2011-11-28 09:38:21", "name": "Test"}

Download sample project

Help yourself with the sources for this project ready to unzip & run. You can download the project here – DjangoRESTfulAPI.

One thought on “Building RESTful API with Django

  1. Pingback: Consuming RESTful API with RESTframework | Dizzey.com

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>