REST API Using Python Django

Python is a very simple and powerful language.It can be used in a multitude of domains from web development to scientific computing.Django is a python web framework.It can be used to make websites at a faster pace.It is has a similarity with the Ruby on rails framework.Django has powerfull ORM(Object Relational Mapper) that can make interactions with databases less painfull.The framework is so robust such that we can focus on implementing the core features of our app rather than wasting time reinventing the wheel.All iterative tasks that we do during web development is avialable readily in django.Django uses MVC framework at it’s heart.

The django rest framework that is used in making API’s.It is a very popular framework in the django landscape.The project that we are gonna make mimics a stock information API.It wil give out information about stock prices of different companies.

Setting Up the environment

Install the dependencies and create a django

pip install django
pip install djangorestframework
django-admin startproject stock

The resulting folder structure is as follows.This is a django project directory.According to django architecture a project can have many apps in it.

└── stock

Next we are gonna create an App

python startapp thestockapp

The following is the directory structure after this operation

├── stock
│ ├──
│ ├── __pycache__
│ │ ├── __init__.cpython-35.pyc
│ │ └── settings.cpython-35.pyc
│ ├──
│ ├──
│ └──
└── thestockapp
├── migrations
│ └──
4 directories, 14 files

Creating The Model

The next step is creating the database for our app.This is done in the thestockapp/ file as follows.

from django.db import models

class Stock(models.Model):
ticker = models.CharField(max_length=10) # Name of the stock
open = models.FloatField() # Stock prize at beginning
close = models.FloatField() # at the end of day
volume = models.IntegerField() # How many times sales was done for the particular stock
def __str__(self):
return self.ticker

If we want to add data to this model using the built in admin interface that django provide we have to register this model.To do that modify thestockapp/

from django.contrib import admin

from .models import *

Now it will be a good time to start the development server that django provides and add some data to the models.Before we can do that some housekeeping is to be done as follows.

python makemigrations
python migrate
python createsuperuser

The above steps will make sure that we have a user name and password for logging into to the django admin interface.Now start the server using the following command.

python runserver

Open a browser and go to this url (Only if default settings are applied and the server is running on the development machine)

Django Admin Page

Add some information to the model.

Sample Data

Creating the serializer

serializer is a mechanism that converts the model into a form in which it can be transmitted across the web.Add a file thestockapp/ and add in the following content.

from rest_framework import serializers
from .models import *

class StockSerializer(serializers.ModelSerializer):
class Meta:
model = Stock
fields = ('ticker','volume')

Creating views

The views has to crafted so as to return a JSON response.In this case we are converting the response to HTML page using the APIView class.

from django.shortcuts import render,get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import *
from .serializers import StockSerializer

# List all stocks & create new one

class StockList(APIView):
def get(self,request):
stocks = Stock.objects.all()
serializer = StockSerializer(stocks,many=True)
return Response(

We are one step away from seeing our API in action.The final step is to edit the file.After editing the file as follows, our API should start working.

from django.conf.urls import url
from django.contrib import admin
from rest_framework.urlpatterns import format_suffix_patterns
from thestockapp import views

urlpatterns = [
url(r'^stocks/', views.StockList.as_view()),
urlpatterns = format_suffix_patterns(urlpatterns)

Now if we hit the url we will get a nicely formatted JSON response as follows

API response

This a gentle introduction to creating API’s with django.The django rest framework is a mature framework.It is very has a truck load of features.Django coupled with this framework can give you the power to develop complex API’s.