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
├── manage.py
└── stock
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py

Next we are gonna create an App

python manage.py startapp thestockapp

The following is the directory structure after this operation

.
├── manage.py
├── stock
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-35.pyc
│ │ └── settings.cpython-35.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── thestockapp
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
4 directories, 14 files

Creating The Model

The next step is creating the database for our app.This is done in the thestockapp/models.py 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/admin.py.

from django.contrib import admin

from .models import *
admin.site.register(Stock)

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 manage.py makemigrations
python manage.py migrate
python manage.py 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 manage.py runserver

Open a browser and go to this url http://127.0.0.1:8000/admin/ (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/serializer.py 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(serializer.data)

We are one step away from seeing our API in action.The final step is to edit the urls.py file.After editing the urls.py 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'^admin/', admin.site.urls),
url(r'^stocks/', views.StockList.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)

Now if we hit the url http://127.0.0.1:8000/stocks/ 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.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.