Web development has become a crucial component of enterprises in the modern world. To build an effective web application, we need to create a robust API.
The Django Rest Framework (DRF) is a powerful tool to create CRUD API in the Django web framework, which is based on python
In this post, we will look at how to create CRUD API in the Django Rest Framework. Create, Retrieve, Update, and Delete are the four fundamental activities you may do using a CRUD API. To interface with a database, web applications frequently use these operations.
Also, Check the Previous Article Implement Join Operations in Django ORM
Django CRUD (Create, Read, Update, Delete) Operation
Before we start building the CRUD API, we need to install Django and Django Rest Framework. The steps are as follows.
Setting Django Rest Framework
Install Django and Rest Framework
Pip install Django Pip install djangorestframework
Create a new Django Project
Django-admin startproject CRUD_API_Restframework
Create a new App
Python manage.py startapp CRUD_API
Configure the Settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'CRUD_API', 'rest_framework', ]
Create Django Models
Now we need to create a Models in our app. The model will define the structure of data.
from django.db import models # Create your models here. class authentication(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) emailid = models.CharField(max_length=100,default=True) is_active = models.IntegerField() firstname = models.CharField(max_length=100,default=True) lastname = models.CharField(max_length=100,default=True) address = models.CharField(max_length=100,default=True) contactno = models.CharField(max_length=100,default=True) gender = models.CharField(max_length=100,default=True) def __str__(self): return self.username
Migration
Python manage.py makemigrations Python manage.py migrate
Create Serializers
Serializers create a format for complicated data types, like Python objects, so that it may be quickly translated into JSON or XML content. Models in DRF are transformed into JSON, XML, or other content types using serializers.
from rest_framework import serializers from .models import authentication class serialize(serializers.ModelSerializer): class Meta: model = authentication fields =['id','username','password','emailid'] class messagserializer(serializers.Serializer): Response = serializers.CharField() Message = serializers.CharField()
Create a Views
The API’s fundamental component views, respond to queries, process data, and handle incoming request. Django Rest Framework has a number of views that can be customized to support CRUD activities
from django.shortcuts import get_object_or_404, redirect, render from django.template.response import TemplateResponse from django.http import HttpResponse,HttpRequest from rest_framework import serializers,status from rest_framework.response import Response from rest_framework.decorators import api_view from django.urls import reverse from django.contrib import messages from django.contrib.auth import authenticate from .models import authentication from .Serializers import serialize,messagserializer import json import requests # Create your views here. @api_view(['GET',]) def getusers(request): if request.method == 'GET': getusers = authentication.objects.all() serializer = serialize(getusers, many=True) request.session['users'] = serializer.data return Response(serializer.data) @api_view(['GET']) def getusersid(request): if request.method == 'GET': argdata = request.data getuserss = authentication.objects.filter(username=argdata['username'] , password=argdata['password']) serializer = serialize(getuserss, many=True) request.session['users'] =serializer.data return Response(serializer.data) return Response('Failure') @api_view(['POST',]) def postusers(request, *args, **kwargs): argdata = request.data if request.method == 'POST': argdata = request.data isvalid = authentication.objects.filter(username=argdata['username']).exists() if isvalid==False: postusers = authentication.objects.create(username=argdata['username'],password=argdata['password'],emailid=argdata['emailid'],is_active=1) postusers.save() getuserss = authentication.objects.filter(username=argdata['username']) serializer = serialize(getuserss, many=True) context = {"getdata":serializer.data,"response":"Success"} return Response(context) else: context = [{"Response":'User Already Registered',"Message":'403'}] serializer = messagserializer(context, many=True) return Response(serializer.data) @api_view(['PUT','GET']) def Editusers(request, *args, **kwargs): if request.method == 'PUT': user_instance = authentication.objects.get(username=request.data.get('username')) #self.get_object(id,request.data.id) if not user_instance: return Response({"message":'User Not Registered'},status=status.HTTP_404_NOT_FOUND) data = { 'username': request.data.get('username'), 'password': request.data.get('password'), 'emailid': request.data.get('emailid'), 'is_active': request.data.get('is_active') } serializer = serialize(instance=user_instance, data=data,partial=True) if serializer.is_valid(): serializer.save() context = {"getdata":serializer.data,"response":"Success"} return Response(context) return Response(serializer._errors,status=status.HTTP_400_BAD_REQUEST) @api_view(['DELETE']) def Delete_User(request): argdata = request.data isvalid = authentication.objects.filter(username=argdata['username']).exists() if isvalid==True: users = get_object_or_404(authentication,username=argdata['username']) users.delete() context = {"response":"Success"} return Response(context) else: context = [{"Response":'User Not Registered',"Message":'403'}] return Response(context)
Create URLS
We need to map the views to URLs to make them accessible through the API. Here are the steps to follow.
- Create a new file urls.py in the CRUD_API directory
Configure the URLs for the views
from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('getusers/',views.getusers, name="getusers"), path('getusersid/',views.getusersid, name="GetUseById"), path('Addusers/',views.postusers, name="postusers"), path('Editusers/',views.Editusers, name="Editusers"), path('Delete_User/',views.Delete_User, name="Delete_User"), ]
Include the app Urls in the project URLs
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('CRUD_API.urls')), ]
Start the Django Development Server
Python manage.py runserver
Testing the API using POSTMAN
Here can test the API using the POSTMAN tool.