Django is one of the popular web development framework based on Python. It follows MVT (Model view template) architecture. It handles security, backend, database all in one.
You can build Web apps using django as a backend and Use normal/Plain HTML with any CSS framework like Bootstrap on frontend. But, If you want to use Django as a back and want to use third party frontend frameworks like Reactjs, AngularJs, etc. You need something more with django.
You can Use Rest API to connect Frontend frameworks with Django and easily make your web apps. To get the REST API feature, Django has a module called Django Rest Framework which helps to convert our data into json format in Django.
Today, We will learn that how you can easily create CRUD API using Django Rest framework. CRUD Simple means Create, Retrive, Update and Delete. These are the simple http methods that every web apps need to use.
To create an API using Django rest framework , we need to setup our Django project first. So, follow the below proces.
How to Create Basic Django Project?
1 . First of all, Create a New Folder in your Desktop.
2. Make sure Python is installed.
3. Open cmd and Install Virtual Environment with this command
pip install virtualenv
4. Now, Open the folder in any code editor like VS Code.
5. Open the intergrated terminal.
6. Now, we need to create Virtual environment first. For that type the command -
virtualenv env
7. Now, Activate the virtual environment by typing this command
8. Now, You've to install Django module. For that type the following command
pip install django
9. Now, we will create our first django project. So, type the command
django-admin startproject project_name
10. switch to the django project root folder and type the command to run the server
python manage.py runserver
11 . Now, we have created our Basic django project. follow the below steps to create CRUP API using django rest framework
How to Create CRUD API using Django Rest framework?
Before beginning, make sure you have activated the virutal environment.
1 . Open your Django project in any Code editor and Open Integrated Terminal.
2. Now, we need to install django rest framework module by typing this command
pip install django-rest-framework
3. Add the module 'rest_framework" in installed apps in settings.py.
4. Now, we will create new app inside django project by typing this command
python manage.py startapp api
5. Add the apps inside settings.py > installed apps.
6. Create urls.py file inside api folder and include that urls.py file in your django project root urls.
7. Now to complete the operation we will create a new model with any name you choose in api>models.py file
class Project(models.Model):
title= models.CharField(max_length=100,blank=True,null=True)
description = models.TextField(blank=True,null=True)
8. Register this model in admin.py file and migrate your app.
9. Now, create a new file called serializers.py and enter these codes inside it.
# Create your serializers here.
from rest_framework import serializers
from .models import Project
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ["id","title","description"]
10. In api/views.py import these modules like this
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import permissions
from .models import Project
from .serializers import ProjectSerializer
11 . we will create a class based views like this and define two functions (Get and Post ).
with the help of get function, we will return the list of data inside the project model and with the post method, we will create new project inside project model
class ProjectAPIView(APIView):
permission_classes = [permissions.AllowAny]
def get(self,request,*args,**kwargs):
projects = Project.objects.all()
serializer = ProjectSerializer(projects, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def post(self, request, *args, **kwargs):
data = {
'title': request.data.get('title'),
'description': request.data.get('description'),
}
serializer = ProjectSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
12 . Now, we will create another new class based view to update and delete the the projects from project model.
class ProjectDetailAPIView(APIView):
permission_classes = [permissions.AllowAny]
def delete(self, request, id, *args, **kwargs):
if Project.objects.filter(id=id).exists():
project = Project.objects.get(id=id)
project.delete()
return Response({"response":"Project Deleted"}, status=status.HTTP_200_OK)
else:
return Response(
{"res": "Project Doesn't Exists"},
status=status.HTTP_400_BAD_REQUEST
)
def patch(self, request, id, *args, **kwargs):
if Project.objects.filter(id=id).exists():
project = Project.objects.get(id=id)
data = {
'title': request.data.get('title'),
'description': request.data.get('description'),
}
serializer = ProjectSerializer(instance = project, data=data, partial = True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response(
{"res": "Project Doesn't Exists"},
status=status.HTTP_400_BAD_REQUEST
)
13. Now, Add two urls inside api/urls.py file like this
from django.urls import path
from .views import ProjectAPIView, ProjectDetailAPIView
urlpatterns = [
path("project",ProjectAPIView.as_view()),
path("project/<int:id>",ProjectDetailAPIView.as_view()),
]
14. Now, You have successfully created CRUD Api using django rest framework. You can integrated these apis with your frontend frameworks.
If you need any help related to Django and Django Rest framework, You can send us directly inquiry and Our Team of Experts will help you.
Comments