Django REST API CRUD Using Class Based View in Django REST Framework

Welcome to my Blog, In this article, we will learn Django REST API CRUD using Class Based View in Django REST Framework (GET, POST, PUT and DELETE) Django REST Framework is a set of tools that make it easy to create a web API, and the Framework provides a serializer that can be used for data transfer and a variety of other functions.
The transferred data is usually transmitted in JSON or XML form, which gives the front-end flexibility in implementing on other languages such as ReactJS, VueJS or Angular, etc.
Let’s start with the installation of the Django REST Framework, go to the terminal window, and type the following command into the command line.

Firstly we verify Python is installed open terminal type the command python3 –version on your system.

$ python3 --version
Python 3.6.13

now verify virtualenv is installed open terminal and execute the command.

$ virtualenv --version
virtualenv 20.0.31 from /home/development/.local/lib/python3.6/site-packages/virtualenv/__init__.py
  1. Create a virtual environment for your project run.
$ python3.6 -m virtualenv env

The env the name of your environment.

2. To activate the environment.

$ source venv/bin/activate

3. Let’s start with the installation of the Django and Django REST Framework, go to the terminal window, and type the following command into the command line.

$ pip install django
$ pip install djangorestframework

I have installed all packages in our virtual environment.

Creating the CrudAPI project

let’s create your django CrudAPI Project now running the command on the terminal.

$ django-admin startproject CrudAPI

After successfully creating the project go to our project directory and run the Django developement server run the command.

$ python manage.py runserver

Visit the URL http://127.0.0.1:8000/ and should view the django welcome page.now we are going to create a django app todo.

$ python manage.py startapp todo

Now add the todo app in our django CrudAPI project and add django rest framework to the installed apps in settings.py.

#./CrudAPI/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'todo',
    'rest_framework',
]

Let me explain briefly: todo is the name of the app, and it is also included in the installed_app section. If you look at the path at the top of this snippet of code, you will see a different name. Depending on what you choose to do when creating your app, you may have different names or the same name.

Read More : how to integrate CKEditor in Django

Read More : Django admin full Customization step by step

Read More : How model queries work in Django

Read More : How to make Chatbot in Python?

Creating the Todo model

now go to your todo app folder and open models.py and create a todo model.

#./todo/models.py

from django.db import models

# Create your models here.
class Todo(models.Model):
    title = models.CharField(max_length = 200)
    description = models.CharField(max_length = 200)
    is_completed = models.BooleanField(default=False)
    date_created = models.DateField(auto_created=True)
    last_modified = models.DateField(auto_now=True)

    def __str___(self):
        return self.title

After creating the model register into admin panel open the admin.py and write the following code.

#./todo/admin.py

from django.contrib import admin
from . models import *

# Register your models here.

admin.site.register(Todo)

To create todo table in the database, we will run the command makemigrations to create a SQL query that used to create a todo table in the database. when we run the migrate command create a todo table in the database.

$ python manage.py makemigrations
$ python manage.py migrate

Now running the server command again for checking everything working fine and now we are going to create a superuser run the following command.

$ python manage.py createsuperuser

Go to http://127.0.0.1:8000/admin after login with credentials now you see your todo table name. now create some entries after you creating them you should see the same page that we have to see here.

todo admin entries
Django Admin

Todo Serializer

So create a serializers.py in your app folder and add the following code below make sure to import serializers from the rest framework here we used the ModelSerializer instance we want to work with. create a TodoSerializer the name of the class is user-defined and we have only need to pass the model we can easily convert any model data and we are serializing all model fields that’s why we are passing all our fields variable and you can choose any field as well.

#./todo/serializers.py

from rest_framework import serializers
from todo.models import Todo

class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = "__all__"

Todo APIView

Now create the necessary views that are used for different CRUD API operations. go to app folder and open views.py and import Response from rest framework to render the content as requested and now we are also importing the APIView and using Class Based View. now we need to create a class of each CRUD API endpoint and add a serializer class and todo model. now creating different crud views using database queries. we use serializers to manage the data being passed.

#./todo/views.py

from django.shortcuts import render
from rest_framework.response import Response
from . models import Todo
from . serializers import TodoSerializer
from rest_framework.views import APIView


# Create your views here.

class ListTodoAPIView(APIView):
    def get(self,request):
        todos = Todo.objects.all()
        serializer = TodoSerializer(todos, many=True)
        return Response(serializer.data)

class TodoDetailAPIView(APIView):
    def get(self,request,pk):
        todos = Todo.objects.get(id=pk)
        serializer = TodoSerializer(todos, many=False)
        return Response(serializer.data)

class CreateTodoAPIView(APIView):
    def post(self,request):
        serializer = TodoSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors)

class UpdateTodoAPIView(APIView):
    def post(self,request,pk):
        todo = Todo.objects.get(id=pk)
        serializer = TodoSerializer(instance=todo, data=request.data)
        if serializer.is_valid():
            serializer.save()
        return Response(serializer.data)

class DeleteTodoAPIView(APIView):
    def get(self,request,pk):
        todo = Todo.objects.get(id=pk)
        todo_instance = Todo.objects.get(id=pk)
        todo_instance.delete()
        return Response('Deleted')

URL paths for Todo endpoints

After created the CRUD API views, now we will create the necessary URLs for these views. the URLs allow interacting with the various todo crud views. firstly create a urls.py in the app folder and write the URLs for various endpoints.

#./todo/views.py

from django.urls import path
from . views import *

urlpatterns = [
    path('',ListTodoAPIView.as_view(),name='todo'),
    path('detail/<str:pk>/',TodoDetailAPIView.as_view(),name='detail'),
    path('create',CreateTodoAPIView.as_view(),name='create'),
    path('update/<str:pk>/',UpdateTodoAPIView.as_view(),name='update'),
    path('delete/<str:pk>/',DeleteTodoAPIView.as_view(),name='delete'),
]

Now go to main project CRUD API directory and add the path to the app URLs.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/todos/', include('todo.urls')),
]

Before testing the API endpoints firstly make sure the server is running up now running command python manage.py runserver. now check all views are properly working fine.

Testing the endpoints

Todo List View

go to http://127.0.0.1:8000/api/todos/ to see the all database entries that we have already created.

list view in api view class based view
Todo List View

Todo Detail View

Go to http://127.0.0.1:8000/api/todos/detail/1/ the see the individual entries.you can the number in the URL for individual entry.

class based detail view
Detail View

Todo Create View

Go to http://127.0.0.1:8000/api/todos/create where you can create new entries. you have remembered all attributes of the model write in the box as JSON form make sure to write each key or value in double quote. if you do not remember copy the entry from the entries list and change it.after you submit the data you can see the newly created entry top of the page.

create view in class based view
Create View
newly entry in api view
New Entry in Create View

Todo Update View

Go to http://127.0.0.1:8000/api/todos/update/4/ in the content box have you paste the attributes that you have update make sure to write the id in the data. when submitting the data, the id data will be updated to the correct entry id number. Submit the entry by clicking POST. After submitting data you can see the data has been updated to the correct id data. I have to create or delete many entries that why’s your entry id number may be different.

Update View
Update View
list view in api view
LIst View

Todo Delete View

Go to http://127.0.0.1:8000/api/todos/delete/4/ to delete entries. change the number in the URL to delete individual entries. I have pass 4 has deleted. after you call the URL then you see the deleted message. you can check the entry have to delete go to all entries list page.

If you liked the article and share it with your friends and if you have any questions about the article feel free to leave me a comment and I will answer the question you have and that’s about it hopefully I will see you again in another article.

One thought on “Django REST API CRUD Using Class Based View in Django REST Framework

Leave a Reply

Your email address will not be published. Required fields are marked *