programmerislam.wordpress.com

python programmer

implement RESTful json API in django itself without django-piston or django-restframework 08 December 2011

Filed under: python — S.M.A.H. @ 13:12
Tags: , , ,

this is my first post on python programming for this blog..i will share with you how to implement REST
using only django..ok, let say i have this structure of django project

myproject/
  __init__.py  
  hello.py  
  lib/

  __init__.py
  rest.py
  shortcuts.py
  manage.py  
  settings.py  
  urls.py  

take note that hello.py and lib package(folder) is my code,not came with django-admin.py startproject myproject

ok,let me explain how we implement REST in this django project..
in the lib package,rest.py have some classes that will handle REST method and in shortcuts.py there is some functions that will handle json request and response

file : myproject/lib/rest.py

# myproject/lib/rest.py

from django.http import HttpResponseNotAllowed

class RESTmethod(object):
    methods = ['GET','POST','PUT','DELETE']

    def __call__(self, request, *args, **kwargs):
        callback = getattr(self, request.method.lower(), None)
        if callback:
            return callback(request, *args, **kwargs)
        else:
            return HttpResponseNotAllowed(self.get_allowed_methods())
    def get_allowed_methods(self):
        return [method for method in self.methods if hasattr(self, method.lower())]

class StatusCode(object):
    OK = 200
    NOT_FOUND = 404
    # add more status code according to your need

file : myproject/lib/shortcuts.py

# myproject/lib/shortcuts.py

from myproject.lib.rest import StatusCode
from django.utils import simplejson as json
from django.http import HttpResponse

def JSONResponse(data = None, status = StatusCode.OK):
    if data is None:
        return HttpResponse(status)
    if data and type(data) is dict:
        return HttpResponse(json.dumps(data, indent = 4, encoding = 'utf-8', sort_keys = True), \
            mimetype = 'application/json', status = status)
    else:
        return HttpResponse(status = StatusCode.NOT_FOUND)

def getJSONObject(request):
    data = None
    if request.raw_post_data:
        try:
            data = json.loads(request.raw_post_data.replace("'","\""), encoding = 'utf-8')
        except:
            data = data
    if data and type(data) is dict:
        return data

then in hello.py

file : hello.py

# myproject/hello.py

from myproject.lib.rest import RESTmethod, StatusCode
from myproject.lib.shortcuts import getJSONObject, JSONResponse

class Hello(RESTmethod):
    def get(self, request):
        requestdata = getJSONObject(request)
        if requestdata:
            return JSONResponse(requestdata)
        return JSONResponse(status = StatusCode.NOT_FOUND)

    def post(self, request):
        requestdata = getJSONObject(request)
        if requestdata:
            return JSONResponse(requestdata)
        return JSONResponse(status = StatusCode.NOT_FOUND)

    # add put, delete functions yourself..function is according to methods in RESTmehtod class in lowercase name

lastly in urls.py

file : myproject/urls.py

# myproject/urls.py

from django.conf.urls import *
from myproject.hello import Hello

urlpatterns = patterns('',
    (r'/hello$', Hello()),
)

that’s all,the project is ready for testing..but dont forget to append your parent folder of myproject in django.wsgi script..see the guide here

you can test it with googlechrome rest client Chrome REST Client or firefox rest client Firefox REST Client
remember to test with json request!
all the best guys!

Advertisement
 

3 Responses to “implement RESTful json API in django itself without django-piston or django-restframework”

  1. Howdy there admin, I absolutely wished to actually give a quick observation to mention that in fact I liked your particular piece of writing. Thanks!

  2. Jannet Hupy Says:

    As soon as I detected this website I went on reddit to share some of the love with them.

  3. Some really excellent articles on this site, appreciate it for contribution.


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s