Build To-Do List API in Django Rest Framework

In this tutorial, we will learn How to create APIs for a To-Do list using the Django rest framework. In this tutorial, we will get to learn about how we can implement all the HTTP methods such as get, post, put, patch, and delete. And we will create APIs to perform all the CRUD operations.

While creating APIs in Real-time programming we have to perform all the crud operations. Through this Todo list app, we will understand how to create the crud APIs using the Django Rest framework. Before that let’s understand some terms related to Django Rest Framework.

APIs

The API stands for Application Programming Interface which is used to communicate between different applications. APIs are created on the server side and communicate with the clint/front end side.

REST

Rest stands for Representational State Transfer. It is a set of instructions to create APIs that give us data sets when a certain URL is clicked. A RESTAPIs is a standardized way to provide data to other applications/clients/frontends. Then the clients can decide how they are going to use the data.

Django Rest Framework:

Django REST framework is a powerful toolkit to develop web APIs using Django. It has many benefits that it provides such as:

  • Helps to make web browsable APIs easily
  • It makes serialization easy for ORM or non-ORM data sources.
  • It has authentication policies that include packages for Oauth1 and Oauth2 authentication.

Django To-Do List API in Django Rest Framework

Let’s now create APIs for a To-Do list using the Django Rest Framework. For this, We are going to use Django to create projects and apps and Django rest framework to create APIs.

In this Django ToDoList project, we are going to create 5 APIs. Where we are going to use class-based views where we will create all the CRUD operations using all the HTTP request methods such as get, post, put/patch and delete.

we are going to create APIs for a To-Do list application, where we are going to have four fields Task, Description, Date and Completed.

Let’s start with creating the app using the Django Rest Framework. For that, we have to go through the following steps.

  • Setting Up Django Rest framework for creating APIs
  • Creating Django project and application
  • Creating the Django project
  • Creating Models for the ToDoapi app
  • Creating a superuser
  • registering our models in models.py
  • Creating serializer in serializer.py file
  • Creating APIs in views.py
  • Creating URLs
  • API Testing in Django rest framework

Step1: Setting Up Django Rest framework for creating APIs

To set up a Django project create a folder (in case not created) in which you want to set up your project open that folder in vs code and run the below command in the terminal to create a virtual environment.

python -m venv venv

now we have created our virtual environment and to activate this virtual environment run the below command.

venv\Scripts\activate

Step2:Creating a Django project and application

To create Django and Rest Apis we need to install Django and Django rest API first. For that, we need to run the below commands in the terminal first.

pip install django
pip install django_rest_framework

Step3: Creating the Django project

To create a Django project ToDoList we have to use the following command

django-admin startproject ToDoList

We need to move inside the project directory to access the manage.py file to work within our Python Django project directory. Follow the below command in the terminal.

cd ToDoList

After entering the Django directory we need to create an application named ToDoapi, For that run the below command.

python manage.py createapp ToDoapi

Now after creating the ToDoapi app, We have to write the app name and the rest_framework in the installed apps in the settings.py of the project. Like the example given below

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

]

Step4: Creating Models for the ToDoapi app

Now it’s time to create models where we are going to write the fields on which we are going to perform the crud operations on the Django rest framework.

We have taken Four fields for our ToDo application as Task, Description, Date, and Completed. We are going to write the fields on the models.py file so that relevant tables will be generated and data can be stored and retrieved in the SQLite database which is the default in the Django framework when needed.

To create the models we have to write the following code in the models.py of the ToDoapi app.

models.py

from django.db import models

class ToDo(models.Model):
    Task=models.CharField(max_length=100,blank=False)
    Description=models.TextField(blank=True)
    Date=models.DateField(blank=False)
    Completed=models.BooleanField(default=False)

After creating the model we have to

Make Migrations

After creating or editing a model it is important for us to run migrations to make the changes and apply those changes in our database. To run migrations follow the below commands in the terminal.

#To create migrations for the changes we have to run
> python manage.py makemigrations

#To apply the changes
> python manage.py migrate

Step5: Creating a superuser

After making the migration we need to see our table whether it is working properly or not, for that Django-provided admin UI, To see our models in the admin panel we have to register the Django model with the admin page. To do so we have to create a superuser first to be able to login to the admin panel. for that, we have to run the following command in the terminal and enter credentials.

python manage.py createsuperuser 

After creating the superuser we need to register the models with the admin site. For that, we have to go to the admin.py file of the app and write the following code to register the model in the admin site of the Django app.

step 6: registering our models in models.py

admin.py

from django.contrib import admin
from ToDoapi.models import ToDo

# Register your models here.
@admin.register(ToDo)
class ToDoModelAdmin(admin.ModelAdmin):
    list_display=['id','Task','Description','Date','Completed']

now if we run the server and go to the admin site we can see that the todo API is there in the admin site with all its fields. You can follow the given image to understand it better

Todo administration Django site admin
Todo administration Django site admin

As described earlier the To Dos model object is created in the admin site.

if we click on the ToDo Objects we can the Django admin has a table to add or remove the data in the admin site itself there we let create some data that we are going to manipulate further.

todo to change Django site admin
todo to change Django site admin

Step7: Creating serializer in serializer.py file:

Django Rest Api provides easy serialization and deserialization to convert the Python object type to Python data type and vice-versa. To perform the serialization we have to create serializers as ToDoSerializer in the serializers.py file, which we have to create separately in our ToDoapi app. We have to write the following code in the serializers.py file. As its fields are the same as our model so we can use the Meta class to create the serializer fields

serializer.py

from rest_framework import serializers
from ToDoapi.models import ToDo

class ToDoSerializer(serializers.ModelSerializer):
    class Meta:
        model= ToDo
        fields=['id','Task','Description','Date','Completed']

Step8: Create the APIs in the views.py file

After creating serializers our main job is to create the APIs. To create the APIs we are going to write the business logic in the views.py file where we are going to write the class-based views and perform all the crud operations for the given fields using all the HTTP methods such as get, Post, put, patch and delete.

before moving forward let’s understand the HTTP methods first.

HTTP methods

When a client clicks on the browser with any URL that is called an HTTP request. The HTTP request comes to the backend and interacts with the database and does the given changes and takes the output and gives the required response to the user. The HTTP methods mostly are the following types.

get– The HTTP method sends the request through the browser and gives the response without performing any changes in the database.

Post– When we have to save some data in the database we use the post method. for example, if we are going to save in the database what we are going to do the whole day in our to-do list app then we use the post method.

put/patch: The HTTP put and patch methods are used to update the database tables that are already created and the put method is used to complete the update where whereas the patch method is used when we are going to partially update the table.

delete: The HTTP delete method is used to delete specific information or rows in the database.

Let’s move to the views.py file where we are going to create the APIs and write the proper business logic regarding the APIs. For creating the APIs let’s follow the codes below. First, we have to import the following files for creating the APIs such as

views.py

from rest_framework.response import Response
from ToDoapi.models import ToDo
from ToDoapi.serializers import ToDoSerializer
from rest_framework.views import APIView
from rest_framework import status

for the above code first, we have imported the Response from the rest_framework which gives the response to the API user/client in the form of JSON data or serializer data.

Then we have to import the ToDo model from the models.py file.

We have to import the ToDoSerializer for the serialization and deserialization and to validate the data.

From rest_framework we have to import APIViews to create the APIs in class-based views.

From rest_framework we have to import status to return HTTP status in the response.

To create class-based Api views we have to create the class ToDoView which is a subclass of APIVIew class so that we can use APIview class methods in the ToDoview class for creating Django restAPIs.

Let’s consider the following example of the get method inside the ToDoview class.

views.py
# Create your views here.

class ToDoview(APIView):
    #API to get all the data or perticular data
    def get(self,request,pk=None, format=None):
        id=pk

        if id is not None:
            queryset=ToDo.objects.get(pk=id)
            serializer=ToDoSerializer(queryset)
            return Response(serializer.data,status=status.HTTP_200_OK)
        
        queryset=ToDo.objects.all()
        serializer = ToDoSerializer(queryset,many=True)
        return Response(serializer.data,status=status.HTTP_200_OK)
    
    #API to save the data in the database
    def post(self,request,format=None):
        serializer = ToDoSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'msg':'new list created'},status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
    
    #API to update the data
    def put(self,request,pk,format=None):
        id=pk
        queryset=ToDo.objects.get(pk=id)
        serializer = ToDoSerializer(queryset,data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'msg':'list updated'})
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
    
    #API to update the data partially
    def patch(self,request,pk,format=None):
        id=pk
        queryset=ToDo.objects.get(pk=id)
        serializer = ToDoSerializer(queryset,data=request.data,partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({'msg':'list updated'})
        return Response(serializer.errors)
    
    # API to delete the data 
    def delete(self, request,pk,format=None):
        id=pk
        queryset=ToDo.objects.get(pk=id)
        queryset.delete()
        return Response({'msg':'item deleted'})

step9: Creating URLs

For the above example after creating the views we have to define the Urls in the Urls.py files of the project and the app.In the project we have to route the app Url. First we have to go to the ToDoList urls.py there we have to route the URLs to ToDoapi URLs as given below.

ToDolist urls.py

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


urlpatterns = [
    path('admin/', admin.site.urls),
    path('todoapi/', include('ToDoapi.urls')),
]

Then we have to create a urls.py file in our ToDoapi application. Here we have to write the URLs for the views.py file of the app. As we have created the class based views we have to write the URLs as follows.

Todoapi urls.py
from django.urls import path
from ToDoapi import views


urlpatterns = [
    path('todo/',views.ToDoview.as_view()),
    path('todo/<int:pk>',views.ToDoview.as_view()),

]

As we have used the class-based views we have to call the ToDoview class in the URLs and we also have used the regular expression todo/<int: pk> to call the function by their id.

So when a URL request comes at first it comes to the project URLs and then it is routed to the app URL using include. In the app URLs it is directed to the views where all the logic is written and gives the output through response.

Step10:API Testing

After creating all the APIs now it’s time to test the APIs. Django rest framework provides the default API testing kit, So when we run the server with the proper URL we will get the required output.

Now let’s understand all the methods one by one. Let’s understand how all the API functions

  • Get request API
  • Post request API
  • Put/Patch request API
  • Delete request API

Get request API

First, let’s start with the get method. When we click 127.0.0.1:8000/todoapi/todo/ from the browser then a get request is sent to get all the data whichever are stored in the database so we are getting the following output.

To Do view Django REST framework
To Do view Django REST framework

Now let’s understand the code when a get request is sent from the following code.

  • when a get request is sent then it is captured by the get request and if any id is not provided then the query set will get all the output using ToDo.objects.all()
  • After that, the data is passed to the serializer to convert the object type data to the Python type
  • Now the data is given as a response to the user in the Response hence giving the above output.
ToDoList getView
ToDoList getView
  • Similarly, when we give an id to the get method, It will give us a value specific to the id, that is why we have written the if statement as, if the id is not any the query set will fetch the specific id data. and give us the output.
  • In the below example, we will try to fetch the data with id-1 with an HTTP request to the browser as http://127.0.0.1:8000/todoapi/todo/1, It will give us all the data of id-1.
To Do get view Django REST framework
To view Django REST framework

Post request API

The Django rest framework has the default API testing. There we can send the post request with the JSON data.

ToDoview post Django REST framework
ToDoview post-Django REST framework

When we click on the post request the data get stored in the database and we get the following output as it gets stored.

post ToDoview DjangoRESTframework
Post ToDoview Django REST Framework

To see the data we can click on the get request for which we will get the output as the new data gets stored in the database at a new id.

ToDoview alldata Django REST Framework
ToDoview alldata Django REST Framework

Let’s understand the code below.

post Todo view code

when a post request is sent through the browser the data is checked through the serializer to check if that is valid. after the data is validated it gets saved in the database.

Put/Patch request API

As we know the put/patch request is used to update data in the database. when a put request is used to update the data completely and the patch is used to update the data partially. So when the put request is sent to update data with id 4 in the example given below. we have to send our JSON data in the put terminal of the rest API given below.

put ToDoview Django REST Framework

when we send the put/patch request the data gets updated in the database it gets updated partially or completely. So we get the following output.

put Doview Django REST framework

Delete request API

To delete a data from the database, we have to send a delete request, so when a delete request is sent to the API, with a certain id that id gets deleted.

delete ToDoview Django REST framework

if we click on the delete in the API the data gets deleted.

Conclusion:

In the above tutorial, we created CRUD-based ToDo APIs, We saw how the APIs are created to perform all the get, post, put, patch delete functions. We created the models for each field and created the URLs for the requests, then at the view page, we wrote the APIs and executed them, and tested the APIs in the default framework.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.