[SOLVED] How to convert a python program into a REST API using Django?

Hi dear programmers,
If you have successfully made a python program and want to wrap it within Django, to make an HTTP Server, so that it can be accessed from different sources like Android/iOS apps, websites, or system applications(such as Windows/Linux/Mac), then you have come to the right place.


So, without much ado, let’s get started!
I am assuming you have a .py file(or a python project) ready with you which accepts some input and returns some output.
Below are the steps you need to follow to make a REST API using Django:
Step 1: Install Django
Type this command in cmd/Terminal to install Django.


1
pip install django

Step 2: Create a Django project
Go to a folder where you want to create Django project and run the below command. You can change mysite to whatever you would like to keep your website’s name.


1
django-admin startproject mysite

You should now have a project structure similar to this:


1
2
3
4
5
6
7
mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

Step 3: Add your .py file(or python project) to the Django project just created
Go inside the outer mysite folder. You should see manage.py and the inner mysite folder.
Create a Django app by running this command at this location in cmd/Terminal.


1
python manage.py startapp myapp

Go inside mysite/myapp folder. Create a new folder here, named my_python_project. Now paste your .py file(or the contents of your python project) inside this folder.
Step 4: Configure the Django app
Open mysite/mysite/settings.py in an editor.
Add myapp in the INSTALLED APPS list. It should now look like this:


1
2
3
4
5
6
7
8
9
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp'
]

Add 'django.middleware.common.CommonMiddleware' and 'django.middleware.csrf.CsrfViewMiddleware' in MIDDLEWARE list in the same order. It should now look like this:


1
2
3
4
5
6
7
8
9
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Save and close this file.
Open mysite/mysite/urls.py and paste the below code in it.


1
2
3
4
5
6
7
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls')),
]

Save and close this file.
Step 5: Configure your python project
Open mysite/myapp/urls.py and paste the below code in it.


1
2
3
4
5
6
7
from django.urls import path

from . import views

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

Open mysite/myapp/views.py and paste the below code in it.
Also, read the commented instructions in the code carefully and accordingly make changes in the code.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
# I am importing the 'askDoctor' function defined in 'getPrescription.py' file inside 'mysite/myapp/my_python_project' folder.
# In your case, name of file(getPrescription.py) and function(askDoctor) will be different.
from .my_python_project.getPrescription import askDoctor

@csrf_exempt
def index(request):
 if request.method == 'POST':
        # Accepting POST request from the user
  body_unicode = request.body.decode('utf-8')
  body = json.loads(body_unicode)

        # I am expecting a key,value pair where key is 'question'. Ofcourse, you may expect something else, so change accordingly.
  question = body['question']

        # I am passing user's question(data in HTTP request) to my imported function and storing result in 'answers' variable. 
        # In your case, function will be different.
  answers = askDoctor(question)

        # Structuring the response into a json
  result = []

  resDict = {
  'question': question,
  'answers': answers
  }

  result.append(resDict)

  json_result = json.dumps({"result":result})

        # Sending HTTP response back to the user
  return HttpResponse(json_result)
 else:
  return HttpResponse("Error! Not a valid request.")

I named my main .py file as getPrescription.py and created askDoctor function in it which accepts a ‘question’ and returns an ‘answer’. Your implementation will be similar to this. So, change the code accordingly.
Step 6: Run your HTTP Server
Go to outer mysite folder and run


1
python manage.py runserver

Your server will run at http://127.0.0.1:8000
Thanks for reading! Happy coding :)
Further Reading
This blog is the result of my attempt to implement this video (https://www.youtube.com/watch?v=J9kbZ5I8gdM) by Siraj Raval. After watching this video I came to know about this github repository(https://github.com/re-search/DocProduct).
After a few attempts, I was sure that this model cannot be converted into a .tflite file as it was a custom(or nested) model. Because there is no such function in Keras or Tensorflow to convert a custom model into a .tflite file as of now.
So, I decided to implement it in its own environment(i.e. python). To achieve this, first of all, I created a Django web server on my local computer. After doing the testing, I purchased an 8GB RAM(Ubuntu 16.04LTS) server on Linode (https://linode.com) and hosted my app there.
Then I made an Android app in java and used Volley library to make HTTP calls.
And finally, I decided to help out others who were wondering how to implement this.
I Hope, you enjoy this blog!

Buy Me a Coffee - https://www.buymeacoffee.com/agautam

Comments