Building a simple REST API on Django

07 Apr 2019

so apparently me two days ago thought django was not going to be too difficult to learn…


the official django documentation really is the best way to start:

otherwise you have no clue what is going on…

so apparently i tried to do this first - while copying pasting works, did not have a clue what was going on:

let me try to make some sense of what is going on (in the second link)

# create and go into the project directory
mkdir proj_django_api
cd proj_django_api

# create a virtual environment to isolate our package dependencies locally
pipenv --three
pipenv install django
pipenv install djangorestframework
pipenv shell # enter the virtual env

# set up a new project called dq
django-admin startproject dq
cd dq

# create an app inside the project called timeseries
python startapp timeseries

# sync database for the first time
python migrate # default uses sqlite

# run the server to see what you have done so far!
python runserver # you will see a rocket on the webpage

now we create a simple view: in timeseries, input the below:

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the index page.")

now we map it to a url. create a file in the timeseries directory and input the below.

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),

this is within the timeseries app. we need to tell the project (dq) to point to it. we will add the below in the dq directory’s file:

from django.contrib import admin
# add an import
from django.urls import include, path

urlpatterns = [
    path('timeseries/', include('timeseries.urls')), #new
    path('admin/',, # existing

you can try python runserver again to see what has happened!

remember to add /timeseries/ at the end of the URL.

in dq/, add the below to INSTALLED_APPS:

# this tells the project what apps are present! 
# TimeseriesConfig is present in the timeseries file

in timeseries, change to the below.

you need to add the decorator, AND for me i was used a POST request (send a json over, calculate using my outlier algorithm saved in another pyscript, then return another json)

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .outlier import get_anomalies

@api_view(['GET', 'POST'])
def get_anoms(request):
    if request.method == 'POST':
        return Response({get_anomalies(request.body)})
        return Response(f"please use POST")

to test your server (make sure it is running), just create a random script somewhere and you can use requests to do a POST!

import requests, json
import pandas as pd

with open('ec2_cpu_utilization_24ae8d.json') as f:
    json_data = json.load(f)

r ="http://xxx.0.0.1:8000/timeseries/", json=json_data)


df = pd.read_json(json.loads(r.text)[0])