A very simple Django API example

I quite often find myself in need of a REST API which does this or that. Yet if enough time pass between me making an REST API in Django I feel I have to start over and learn the process again. Here I’ve outlined a very basic calculator API which can add, subtract and multiply floating numbers.

I assume that you have python and virtualenv installed and you are working on a system with a proper commandline interface.

The Environment

Setting up the environment is just a few steps. First make a virtual environment for us to work in and start the django project.

$ pipenv install django django-settings-cmd
$ pipenv shell
(calc)$ django-admin startproject calc_api
(calc)$ cd calc_api/
(calc)$ django-admin startapp calc
(calc)$ django-settings-enable-app calc

Add the calc app urls to the global list of urls in calc_api/urls.py

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
url(r'^calc/', include('calc.urls')),
url(r'^admin/', admin.site.urls),
]

Create the list of endpoints in the calc app (calc/urls.py)

from django.conf.urls import url

from . import views

urlpatterns = [
url(r'^add$', views.add, name='add'),
url(r'^sub$', views.add, name='sub'),
url(r'^mul$', views.add, name='mul'),
]

Create the calc app endpoints in the calc/views.py

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, Http404

def getFloatParam( name, request ):
  try:
    val = request.GET[name]
  except:
    raise Http404( "Missing parameter %s"%name )
  try:
    fval = float( val )
  except:
    raise Http404( "Parameter %s is not a float value"%name )
  return fval

def add(request):
  left = getFloatParam( "left", request )
  right = getFloatParam( "right", request )
  return JsonResponse( {"result":left + right} )

def sub(request):
  left = getFloatParam( "left", request )
  right = getFloatParam( "right", request )
  return JsonResponse( {"result":left - right} )

def mul(request):
  left = getFloatParam( "left", request )
  right = getFloatParam( "right", request )
  return JsonResponse( {"result":left * right} )

Now lets get things running

(calc)$ ./manage.py migrate
(calc)$ ./manage.py runserver
(calc)$ open "http://127.0.0.1:8000/calc/add?left=1.5e2&right=2"

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 )

Google photo

You are commenting using your Google 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