How to Build a Todo API in Django Rest Framework?

Published On: 29/08/2022 | Category: Django


Hi Dev,

Today, I will let you know example of how to build a todo api in django rest framework?. I explained simply about how to build a todo api with serializers in django. if you want to see example of how to create a todo api using django rest framework then you are a right place. if you have question about django rest framework todo api example then I will give simple example with solution. Let's see bellow example django rest todo api tutorial.

Here i explained Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds. There are three stages before creating a API through REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, Creating a URL for mapping to the viewset.

In this tutorial we'll create a basic Django To Do app and then convert it into a web API using serializers, viewsets, and routers.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App

Now we'll create a single app called todos to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python manage.py startapp todos
Step 3: Update setting.py

In this step we require to do two things in our settings.py file, One is our installed app name Add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:

example/settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'todos',
]
Step 4: Create a Model

In this step we will require the database model for storing contacts.Open the todos/models.py file and add the following code:

todos/models.py
from django.db import models


class Todo(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()

    def __str__(self):
        return self.title

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python manage.py makemigrations
python manage.py migrate
Step 5: Update admin.py File todos/models.py
from django.contrib import admin

from .models import Todo

admin.site.register(Todo)
Django Admin Interface:

Step 6: Install a Django REST Framework

First of all let’s install django and djangorestframework which are the necessary Python libraries.Django Rest Framework and then create a new our second app apis app. All of our API information will be routed through here. Even if we had multiple apps in our project, we'd still only need a single app to control what the API does.

pip install djangorestframework
python manage.py startapp apis

Next, you need to add it in the settings.py file as follows:

settings.py
....
INSTALLED_APPS = [
    ...
    'rest_framework', # new
    'apis', # new
    'todos',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ]
}
Step 7: Creating the Serializers

In this step, we need to create Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. Let’s start creating a serializer.

apis/serializers.py
from rest_framework import serializers
from todos import models


class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
            'id',
            'title',
            'description',
        )
        model = models.Todo
Step 8: Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the todo_api/views.py file and add:

Django Rest Framework performs all the heavy lifting for us within its generics class that we import at the top. This is quite kindred to generic class-predicated views in traditional Django. We designate our model and serializer for each of the views.

Next up is our view. DRF views are very homogeneous to traditional Django views and even come with several generic views that provide lots of functionality with a minimal magnitude of code on our component. We want a ListView as well as a DetailView of individual todo items. Here's what the code looks akin to.

todo_api/views.py
from rest_framework import generics
from todos import models
from .serializers import TodoSerializer

class ListTodo(generics.ListCreateAPIView):
    queryset = models.Todo.objects.all()
    serializer_class = TodoSerializer


class DetailTodo(generics.RetrieveUpdateDestroyAPIView):
    queryset = models.Todo.objects.all()
    serializer_class = TodoSerializer

Step 9: Creating URLs

In this section, we need a urls.py file within the apis app however Django doesn't create one for us with the startapp command. Create apis/urls.py with your text editor and paste below code.

apis/urls.py
from django.urls import include, path
from .views import ListTodo, DetailTodo

urlpatterns = [
    path('', ListTodo.as_view()),
    path('<int:pk>/', DetailTodo.as_view()),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('apis/v1/', include('apis.urls')), # new
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://127.0.0.1:8000/apis/v1/ address with a web browser.

List Page

List Page

I Hope It will help you....