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…

hashtag-regrets


the official django documentation really is the best way to start: https://docs.djangoproject.com/en/2.2/intro/tutorial01/

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: https://www.django-rest-framework.org/tutorial/quickstart/


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 manage.py startapp timeseries

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

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

now we create a simple view: in timeseries views.py, 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 urls.py 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 urls.py file:

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

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

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

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


in dq/settings.py, add the below to INSTALLED_APPS:


# this tells the project what apps are present! 
# TimeseriesConfig is present in the timeseries app.py file
INSTALLED_APPS = (
    ...
    'rest_framework',
)

in timeseries views.py, 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)})
    else:
        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 = requests.post("http://xxx.0.0.1:8000/timeseries/", json=json_data)

#print(r.text)
print(r.status_code)

df = pd.read_json(json.loads(r.text)[0])
df.to_csv('received_data.csv')


YOU ARE DONE CONGRATULATIONS!!!!!