Press ESC to close

Create a REST API for a Todo Application Using Django REST Framework in Python

Photo by twiri

To create a REST API for a Todo application using Django REST Framework (DRF) in python, follow these steps:

Step 1: Install Django and Django REST Framework

First, create a virtual environment and install Django and DRF:

Also learn “Write a Program to Compress and Decompress Files using the Zipfile Module in python”

# Create virtual environment
python -m venv venv
source venv/bin/activate  # For Linux/Mac
venv\Scripts\activate  # For Windows

# Install Django and DRF
pip install django djangorestframework

Step 2: Create a New Django Project

Create a Django project and a new app for the Todo application:

# Create project
django-admin startproject todo_project

# Navigate to the project directory
cd todo_project

# Create a new app
python manage.py startapp todo

Step 3: Add the App and DRF to settings.py

Edit the todo_project/settings.py to include the todo app and rest_framework:

INSTALLED_APPS = [
    # Other installed apps
    'rest_framework',
    'todo',
]

Step 4: Create the Todo Model

In the todo/models.py file, define the Todo model:

from django.db import models

class Todo(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title
After defining the model, run the following commands to apply migrations:
python manage.py makemigrations
python manage.py migrate

Step 5: Create a Serializer for the Todo ModelIn the todo/serializers.py file, create a serializer for the Todo model:

from rest_framework import serializers
from .models import Todo

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

Step 6: Create Views for the Todo API

In todo/views.py, create API views using Django REST Framework’s APIView or ViewSets. For simplicity, we will use ViewSets.

from rest_framework import viewsets
from .models import Todo
from .serializers import TodoSerializer

class TodoViewSet(viewsets.ModelViewSet):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer

Step 7: Define API RoutesIn todo/urls.py, define the API routes using DRF’s routers

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import TodoViewSet

router = DefaultRouter()
router.register(r'todos', TodoViewSet, basename='todo')

urlpatterns = [
    path('', include(router.urls)),
]
Also, include the todo app's URLs in the project's todo_project/urls.py:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('todo.urls')),  # Include the todo app's URLs
]

Step 8: Run the Server

Run the development server:

python manage.py runserver

Now, you can access the Todo API at http://127.0.0.1:8000/api/todos/.

Step 9: Testing the API

You can test the following endpoints using tools like Postman or curl:

  1. GET /api/todos/: Get a list of all todos.
  2. POST /api/todos/: Create a new todo by sending JSON data like:
{
    "title": "Buy groceries",
    "description": "Milk, Eggs, Bread",
    "completed": false
}

3. PUT /api/todos/{id}/: Update a todo with specific ID.

4. DELETE /api/todos/{id}/: Delete a todo with specific ID.

    This basic REST API allows you to create, read, update, and delete todo items. 

    Leave a Reply

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