Install Django and Django REST Framework:
pip install django djangorestframework
Start a New Django Project:
django-admin startproject todo_project
cd todo_project
Create a New Django App:
python manage.py startapp todos
Add the App and DRF to INSTALLED_APPS
in settings.py
:
INSTALLED_APPS = [
...
'rest_framework',
'todos',
]
Define the Todo
Model in todos/models.py
:
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
Run Migrations:
python manage.py makemigrations
python manage.py migrate
Create a Serializer for the Todo
Model in todos/serializers.py
:
from rest_framework import serializers
from .models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = '__all__'
Create API Views in todos/views.py
:
from rest_framework import generics
from .models import Todo
from .serializers import TodoSerializer
class TodoListCreate(generics.ListCreateAPIView):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
class TodoRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
Add URLs in todos/urls.py
:
from django.urls import path
from .views import TodoListCreate, TodoRetrieveUpdateDestroy
urlpatterns = [
path('todos/', TodoListCreate.as_view(), name='todo-list-create'),
path('todos/<int:pk>/', TodoRetrieveUpdateDestroy.as_view(), name='todo-retrieve-update-destroy'),
]
Include the App URLs in todo_project/urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('todos.urls')),
]
Run the Server:
python manage.py runserver
Test the API Endpoints:
http://127.0.0.1:8000/api/todos/
http://127.0.0.1:8000/api/todos/<id>/
You can use tools like Postman or cURL to test the API endpoints.
List Todos:
curl -X GET http://127.0.0.1:8000/api/todos/
Create a Todo:
curl -X POST -H "Content-Type: application/json" -d '{"title": "New Todo", "description": "Todo description", "completed": false}' http://127.0.0.1:8000/api/todos/
Retrieve a Todo:
curl -X GET http://127.0.0.1:8000/api/todos/1/
Update a Todo:
curl -X PUT -H "Content-Type: application/json" -d '{"title": "Updated Todo", "description": "Updated description", "completed": true}' http://127.0.0.1:8000/api/todos/1/
Delete a Todo:
curl -X DELETE http://127.0.0.1:8000/api/todos/1/