Canarys | IT Services

Blogs

Building a RESTful API using python and Django

Date:
Author:
Share
What you Need?
  • Python 2.6+
  • Django 1.5+
  • django-tastypie 
  • Sqllite3
Django is Free and Open Source web application framework written in Python.
Which works on MVT(model view template) Framework .
 
Step 1: Create a model 
 
As it is MVT architecture we have to define a model.It inludes what are all field required in your api you have to declare here with proper class fields.
Here i have created a model class with fields with their type .
 
from django.db import models
 
class Company(models.Model):
    name = models.CharField("Coamapny's official Name",max_length=100)
    address = models.CharField(max_length=100)
    no_of_employee = models.IntegerField("Number of Employees",default=0)
    business = models.TextField()
 
Step 2: Create a view
 
This layer contains the logic that access the model and defers to the appropriate template which includes POST and GET request
 
Once you have declared data fields in model next step is create Form for posting data into database here i created ComapnyForm class with model delared  and crerated a POST request in views .which is passed to template with all the data entered in form as a dicttionary.
 
 
from django import forms
from models import Company
 
class CompanyForm(forms.ModelForm):
    class Meta:
        model = Company
 
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
 
def create_company(request):
    if request.POST:
        form = CompanyForm(request.POST) 
        if form.is_valid():
              form.save()
              return HttpResponseRedirect('/articles/all')
    else:
           form = CompanyForm()
 
  args ={ }  
  args.update(csrf(request))
  args['form'] = form 
  return render_to_response('create_company.html',args)
 
Step 3 :Create a Template and Configure a URL
 
In the template we will display a form which will display in widget format to user  asking fields declared in Model .
Once you fill all the details and on click of Create Company it will save in database.by this way we can post N no of details to Database
 
 
Create a HTML File
 
 

 

{% csrf_token %}
{{ form.as_ul }}
 
 
 
 
 
 
Build a URL
 
Next step is build a URL through wich you can access your data.here you can declare a URL format which will call the views function
to get API details.
 
create an object of company resource and hook that to url config 
 
from django.conf.urls import patterns,include,url
from api import CompanyResource
 
comapny_resource = CompanyResource()
 
urlpatterns = patterns('',
url(r'^create_company/$','company.views.create_company'),
url(r'^api/',include(comapny_resource.urls)),
)
 
Step 4:Create a Resources for model
 
Why TaStypie?
 
Which provides a rest style API
you can  create a new resource (POST)
Upadate the existing resources (PUT)
Deleting a Resources(DELETE)
 
Tastypie supports 
  • Caching
  • Authentication
  • Validation
  • Throating limits to a certain number of requests per hour.
  • Serialization -You DON’T want to have to write your own serializer to make the output right
Here we will import our model class with all posted class objects. and resouce name which we will display in api. it will build API format with data.
 
from tastypie.resources import ModelResource
from models import Company
 
class CompanyResource(ModelResource):
    class Meta:
        queryset = Company.objects.all()
        resource_name = 'company'
 
Step 5: In the browser hit url
 
Final Step is run a localserver and open a formed API which include resource name and serilization type
 
http://127.0.0.1:8000/api/company/?format=json/
 
Which will give api resource in json format.

Leave a Reply

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

Reach Us

With Canarys,
Let’s Plan. Grow. Strive. Succeed.