Step by Step create Simple API using python-django

In this tutorial, we will learn how to create REST API. We will create 4 types of REST API.

  1. GET
  2. POST
  3. PUT

Start a project

  1. create new project in PyCharm

Figure 1

Figure 2

Figure 3

Install Django

  1. Go to Python Terminal and write following command and hit enter to install Django to your project.

Figure 4

python -m pip install Django

  1. To check if Django is installed properly, go to Python console and write following code:

      import django


Figure 5

Showing version is 3.0.3

That means, Django installed successfully.

Create new project

  1. Now need to create a project. Django always offer you to create a project at first and then you can create one or multiple app under the project. Write following command and hit enter at the terminal to create project.

django-admin startproject studentproject


After giving the command, you will see new project has been created in project tree.

Figure 6

  1. Now go to your project. Hit the command:

Cd studentproject


Figure 7

Create app

  1. Now create an app inside the project. Hit this command:

Terminal:> python startapp basicinfoapp

After giving the command, you will see an app name as basicinfoapp has been created in project inside.

Figure 8

  1. Now you need to install app on project settings.

For that, go to studentproject > settings

Find the INSTALLED_APP tag

Figure 9

Edit the installed app configuration.

Add the app name you just created.

Figure 10

Create Model

  1. Now create a model. Go to basicinfoapp folder.
  2. Open the file

Write following lines into the editor

from django.db import models

# Create your models here.
class Student(models.Model):
student_id = models.CharField(max_length=100)
student_name = models.CharField(max_length=100)
department = models.CharField(max_length=100)

contact_no = models.CharField(max_length=15)

def __str__(self):
return self.student_id

Figure 11

Migrate model to db

  1. Now need to migrate the model into database. Write following command and hit enter.

python makemigrations basicinfoapp

Figure 12

Now type this command for migrate the project.

python migrate

Figure 13

Install rest framework


  1. Now install rest framework. Go to terminal and hit this command:

pip install djangorestframework


Figure 14


After installing the package, you will see output


Create Serializer

  1. Create File in basicinfoapp folder.

Add following code:

from rest_framework import serializers
from .models import Student

class employeeSerializers(serializers.ModelSerializer):
class Meta:
model = Student
fields = [“student_id”,“student_name”,“department”,“contact_no”]

Figure 15


Create new file as in basicinfoapp folder and add following package.

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from . import views

Figure 16

Create GET API to view list

  1. Add following package in file

from django.shortcuts import render
from django.http import Http404, HttpResponse
from rest_framework.renderers import JSONRenderer
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.http import JsonResponse
from django.core import serializers
from django.conf import settings
from rest_framework import viewsets
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, renderer_classes
from .serializers import studentSerializers
from rest_framework.decorators import action
from .models import Student
import json

  1. Now create a function to view student data:

class StudentViewSet(viewsets.ModelViewSet):
@api_view([‘GET’, ])
def studentList(self):
queryset = Student.objects.all()
serializer = studentSerializers(queryset, many=True,)
return JsonResponse(, safe=False)

Figure 17

  1. Edit in basicinfoapp folder and configure URL:

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from . import views

urlpatterns = [
path(‘list’, views.StudentViewSet.studentList, name=‘studentList’),


Figure 18

  1. Now go to studentproject > file.

Add following highlights:

Figure 19

  1. Now write this command and hit enter to start py server:

           python runserver

Figure 20

  1. Now py server is running the localhost. Navigate your app url and see list data.
  2. Hit this URL to any Rest Client like postman or RestLET or browser


Figure 21

  1. No data is found in list. Already you created GET API to view the list. Now it’s time to add some data. You need to create POST API to add some data to view on list. We will create POST API later. Before that, lets login with the root user to Django admin portal and add some data. Let’s go.

Create Admin User

  1. To create admin user, hit following command in terminal:

     python createsuperuser

Then system will prompt you to give name of super admin user

I have given the super user name as ‘admin’

Now the system will prompt you to give email address

I have given the email as ‘’

Now the system will prompt you to give password

I have given the password as ‘123456’

I have confirmed the password again

Now system will alert that the password is easy. If I want to keep this password. I input ‘y’ for confirmation.

Now system creates superuser for me.

Figure 22

  1. Now go to basicinfoapp folder and open file
  1. Add following code:

from django.contrib import admin
from .models import Student

# Register your models here.

Figure 23

  1. Now start the py server again

           Terminal:> python runserver


and navigate the URL:

Figure 24

  1. Input the username and password you just created and login the admin portal.
  2. You will see the model name in admin dashboard you created.

Figure 25

  1. Click on the model name showing on admin portal. You will see a portal to add student.

Figure 26

  1. Now click on “Add student” button and input data into admin portal

Figure 27

Figure 28

  1. Now hit the following URL into any rest client like RESTClient or postman and see your inserted data is showing in json list

Figure 29

Create POST API to add data

  1. Let’s create POST API to add data without admin portal.
  2. Go to basic info app and open file
  3. Add following code in code edit window:

@api_view([‘POST’, ])
def add_student(request):
if request.method == “POST”:
json_body = json.loads(request.body)
student_id = json_body[‘student_id’]
student_name = json_body[‘student_name’]
department = json_body[‘department’]
contact_no = json_body[‘contact_no’]

student = Student(student_id=student_id, student_name=student_name, department=department,contact_no=contact_no)
if Student.objects.filter(student_id=student_id).exists():
response = json.dumps({‘Status’: ‘Student already exists’})
response = json.dumps({‘Status’: ‘Student added successfully’})
except ValueError as e:
response = json.dumps({‘Status’: ‘Student added failed’})
# return JsonResponse(e.args[0], status.HTTP_400_BAD_REQUEST,safe=False)
return HttpResponse(response, content_type=“text/json”)

Figure 30

  1. Now open basicinfoapp > file and add this line:

path(‘add’, views.StudentViewSet.add_student, name=‘add_student’),

Figure 31

  1. Now hit the command in terminal:

           Terminal:> Python runserver

  1. Now open any client app like postman/RestLET and set the parameters as:


Method: POST

Body: {






Figure 32

Create GET API to get data against Id

  1. Now we will create a GET API to get information for a selected student Id. Let’s go.
  2. Open file
  3. Add this code.

@api_view([‘GET’, ])
def get_student(request, student_id):
student = Student.objects.get(student_id=student_id)
response = json.dumps({‘student_id’: student.student_id, ‘student_name’: student.student_name, ‘department’: student.department
, ‘contact_no’: student.contact_no})
response = json.dumps({‘Error’: ‘No student found’})
return HttpResponse(response, content_type=“text/json”)

Figure 33

  1. Add this line to

path(‘show/<str:student_id>’, views.StudentViewSet.get_student, name=‘get_student’),

Figure 34

  1. Hit the URL to the browser/Postman/RestClient<student_id> //pattern //student id

Figure 35

Create PUT API for data update

  1. Now we will create PUT API for Update
  2. Go to basicinfoapp >
  3. Add following lines

@api_view([‘PUT’, ])
def update_student(request, student_id):
student = Student.objects.get(student_id=student_id)
serializer = studentSerializers(student,
data = {}
if (serializer.is_valid()):
data[“success”] = “Update successful”
return Response(data=data)
response = json.dumps({‘Status’: ‘No student found’})
return HttpResponse(response, content_type=“text/json”)

Figure 36

  1. Then Add line in file

path(‘update/<str:student_id>’, views.StudentViewSet.update_student, name=‘update_student’),

Figure 37

  1. Run Py server from terminal and go to REST API Client

Terminal:> Python runserver


  1. Set the parameters as:


Method: PUT

Body: {


“student_name”:”Salman Rahman”,




  1. Output: Updated successfully

Figure 38

  1. Now you can check by calling your get data API to see the changes

Figure 39

Changes applied. So, update work successfully.

Create DELETE API to delete data

  1. Now we will create DELETE API to delete a data
  2. Open basicinfoapp/ file
  3. Add following code.

@api_view([‘DELETE’, ])
def delete_student(request, student_id):

student = Student.objects.get(student_id=student_id)
response = json.dumps({‘Status’: ‘Deleted’})

response = json.dumps({‘Status’: ‘No student found’})
return HttpResponse(response, content_type=“text/json”)

Figure 40

  1. Add this line to file.

path(‘delete/<str:student_id>’, views.StudentViewSet.delete_student, name=‘delete_student’),

Figure 41

  1. Now hit the URL to any Rest Client. Set parameters as:


Method: DELETE

to the REST Client and you will get output as “Deleted”

Figure 42