Simple Django Piston Tutorial

Do you like this?

Summary:
Django Piston is an easy-to-use application that allows you to create your own REST API for your applications. This short tutorial is straight forward and gives you a good starting point to set out your projects.


Content:

This project is not only a demonstration of how Django Piston can be integrated but also a continuation of my earlier projects: Django Development With Eclipse and PyDev and Django Comments Framework Tutorial. In the earlier projects, we have created a simple Django application using PyDev and then enhanced it by integrating the Django Comments Framework. Now, what we are going to do is to re-use the application and then improve it by utilising the Django Piston framework to build our REST API.

Download Link: Simple Django Piston Tutorial

If you want to have some understanding as to how the initial project looked like before implementing Django Piston, please take a look at Number 2 - OUR APP BEFORE PISTON.

As recommended on the official site, you should create a separate folder for your Piston-based REST API as highlighted in the following screenshot with 2 key files handlers.py and urls.py:
Django Piston Tutorial - Step sshot-1.jpg

In your main urls.py, you should define an entry pointing to the urls.py file in your Piston api folder.
Django Piston Tutorial - Step sshot-2.jpg

Here from my experience, we should use a custom class for our handlers instead of the BaseHandler class provided by Piston because the custom class CsrfExemptBaseHandler can just remove the csrfmiddlewaretoken key in the request. Hence, you can easily access your API by typing http://localhost:8000/api/piston/YOUR_MODEL. And this method was taken from the site http://andrew.io as shown in the picture:
Django Piston Tutorial - Step sshot-3.jpg

We have only one model called Article in our project so we can create one handler for it named ArticleHandler. The method read() is used to handle GET requests. Django Piston Tutorial - Step sshot-4.jpg

For our Article model, we have declared only 3 attributes: name, value and status. However the status attribute contains integer values so we want to make it more human readable by converting it to the corresponding text value.
class Article(models.Model):
    STATUS_TYPES = (
        (0 , 'Pending'),
        (1 , 'Reviewed'),
        (2 , 'Published'),
        (3 , 'Expired')
    )
    ...........

Django Piston Tutorial - Step sshot-5.jpg

For further handling, you can read more detailed information on the official site. As can be seen, there are 4 possible methods to be implemented for GET, POST, PUT and DELETE.
Django Piston Tutorial - Step sshot-6.jpg

Below you can see the relationship between the declaration in urls.py and handlers.py:
Django Piston Tutorial - Step sshot-7.jpg

Following is the end result you can get from this:
Django Piston Tutorial - Step sshot-8.jpg

 
comments powered by Disqus