Step by Step create Simple API using python-django

TechtunesBd

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

  4. DELETE




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


print(django.get_version()

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 manage.py 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 models.py 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 manage.py makemigrations basicinfoapp

Figure 12

Now type this command for migrate the project.



python manage.py 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 serializers.py 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 urls.py

Create new file as urls.py 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 views.py 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(serializer.data, safe=

False

)

Figure 17

  1. Edit urls.py 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 > urls.py file.

Add following highlights:

Figure 19

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



python manage.py 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


URL

:

http://127.0.0.1:8000/student/list

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 manage.py 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 ‘admin@localhost.com’

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 admin.py file
  1. Add following code:


from

django.contrib

import

admin


from

.models

import

Student


# Register your models here.


admin.site.register(Student)

Figure 23

  1. Now start the py server again



Terminal:> python manage.py runserver




and navigate the URL:


http://127.0.0.1:8000/admin

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 views.py 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)


try

:


if

Student.objects.filter(student_id=student_id).exists():

response = json.dumps({

‘Status’

:

‘Student already exists’

})


else

:

student.save()

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 > urls.py 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 manage.py runserver

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


URL

:

http://127.0.0.1:8000/student/add


Method

: POST


Body

: {

“student_id”:”103″,

“student_name”:”salman”,

“department”:”CSE”,

“contact_no”:”01602020110″

}

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 views.py file
  3. Add this code.

@api_view([

‘GET’

, ])


def

get_student(request, student_id):


try

:

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})


except

:

response = json.dumps({

‘Error’

:

‘No student found’

})


return

HttpResponse(response, content_type=

“text/json”

)

Figure 33

  1. Add this line to urls.py

path(

‘show/<str:student_id>’

, views.StudentViewSet.get_student, name=

‘get_student’

),

Figure 34

  1. Hit the URL to the browser/Postman/RestClient


http://127.0.0.1:8000/student/show/<student_id

> //pattern


http://127.0.0.1:8000/student/show/101

//student id

Figure 35




Create PUT API for data update

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

@api_view([

‘PUT’

, ])


def

update_student(request, student_id):


try

:

student = Student.objects.get(student_id=student_id)

serializer = studentSerializers(student, data=request.data)

data = {}


if

(serializer.is_valid()):

serializer.save()

data[

“success”

] =

“Update successful”



return

Response(data=data)


except

:

response = json.dumps({

‘Status’

:

‘No student found’

})


return

HttpResponse(response, content_type=

“text/json”

)

Figure 36

  1. Then Add line in urls.py 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 manage.py runserver


  1. Set the parameters as:


URL

: http://127.0.0.1:8000/student/update/103


Method

: PUT


Body

: {

“student_id”:”103″,

“student_name”:”Salman Rahman”,

“department”:”CSE”,

“contact_no”:”01602020110″

}

  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/views.py file
  3. Add following code.

@api_view([

‘DELETE’

, ])


def

delete_student(request, student_id):


try

:

student = Student.objects.get(student_id=student_id)

student.delete()

response = json.dumps({

‘Status’

:

‘Deleted’

})


except

:

response = json.dumps({

‘Status’

:

‘No student found’

})


return

HttpResponse(response, content_type=

“text/json”

)

Figure 40

  1. Add this line to urls.py 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:


URL

:

http://127.0.0.1:8000/student/delete/102


Method

: DELETE

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

Figure 42

Leave a Reply

Your email address will not be published.