create simple example JSON REST API in Django 1.3


Creating REST JSON API in Django in pretty easy. I know several django modules like django-tastypie, django piston, etc provide easy ways to build REST API in Django, but at this time, I will show simple example.

First, we should define our urls. Eg : “/api/search/keyword”

APP/urls.py

1
2
3
4
5
from django.conf.urls.defaults import patterns, url

urlpatterns = patterns(‘price.views’,
    url(r’^api/search/(?P<keyword>[a-zA-Z0-9s+]+)$’, ‘search’, name=’search’),
)


APP/views.py

1
2
3
4
5
6
7
8
from price.models import PriceGrab
from django.core import serializers
from django.http import HttpResponse

def api(request, **kwargs):
    items = PriceGrab.objects.filter(keyword=kwargs[‘keyword’])
    items = serializers.serialize(‘json’, items, indent=4)
    return HttpResponse(items, mimetype=’application/json’)

Nothing more? Yes, that codes are enough.
Now you have simple example of JSON REST API in Django 🙂


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.