crud in python

muhammedshamal

Muhammed Shamal PV

Posted on August 2, 2024

crud in python

Follow me on LinkedIn
Follow me on Github.com

Click & Read

Building a Simple CRUD API with Django Rest Framework Using Class-Based Views

In this tutorial, we'll build a simple CRUD (Create, Read, Update, Delete) API for a TODO application using Django Rest Framework (DRF) with normal class-based views. This is ideal for beginners who want to understand how to manually handle HTTP methods in Django without relying on DRF's generic views.

1. Models

First, let's define our Todo model. This model will have fields for the title, description, completed status, and timestamps for when the TODO item was created and last updated.

# models.py
from django.db import models

class Todo(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    completed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title
Enter fullscreen mode Exit fullscreen mode

2. Serializers

Next, we'll create a serializer for our Todo model. Serializers in DRF work similarly to Django forms, converting complex data types such as querysets and model instances into native Python data types.

# serializers.py
from rest_framework import serializers
from .models import Todo

class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = '__all__'
Enter fullscreen mode Exit fullscreen mode

3. Views

We'll now create views for each CRUD operation using APIView. This approach gives us full control over how each HTTP method is handled.

# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
from .models import Todo
from .serializers import TodoSerializer

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

    def post(self, request):
        serializer = TodoSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class TodoDetailAPIView(APIView):
    def get_object(self, pk):
        return get_object_or_404(Todo, pk=pk)

    def get(self, request, pk):
        todo = self.get_object(pk)
        serializer = TodoSerializer(todo)
        return Response(serializer.data)

    def put(self, request, pk):
        todo = self.get_object(pk)
        serializer = TodoSerializer(todo, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request, pk):
        todo = self.get_object(pk)
        serializer = TodoSerializer(todo, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        todo = self.get_object(pk)
        todo.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Enter fullscreen mode Exit fullscreen mode

4. URLs

We need to set up our URLs to route to these views. This involves mapping URL patterns to the appropriate view classes.

# urls.py
from django.urls import path
from .views import TodoListCreateAPIView, TodoDetailAPIView

urlpatterns = [
    path('todos/', TodoListCreateAPIView.as_view(), name='todo-list-create'),
    path('todos/<int:pk>/', TodoDetailAPIView.as_view(), name='todo-detail'),
]
Enter fullscreen mode Exit fullscreen mode

5. Settings

Ensure you have Django Rest Framework installed and added to your INSTALLED_APPS:

# settings.py
INSTALLED_APPS = [
    # Other installed apps
    'rest_framework',
    'your_app_name',
]
Enter fullscreen mode Exit fullscreen mode

Summary

With this setup, you can perform CRUD operations on the Todo model using the following endpoints:

  • Create: POST /todos/ - handled by TodoListCreateAPIView
  • Read: GET /todos/ (list) - handled by TodoListCreateAPIView
  • Read: GET /todos/{id}/ (retrieve) - handled by TodoDetailAPIView
  • Update: PUT /todos/{id}/ (update) - handled by TodoDetailAPIView
  • Partial Update: PATCH /todos/{id}/ (partial update) - handled by TodoDetailAPIView
  • Delete: DELETE /todos/{id}/ - handled by TodoDetailAPIView

Example of Creating a TODO Item

Using Postman or any HTTP client, you can create a TODO item by sending a POST request to http://localhost:8000/todos/ with a JSON body:

{
    "title": "Buy groceries",
    "description": "Milk, Bread, Cheese, Eggs",
    "completed": false
}
Enter fullscreen mode Exit fullscreen mode

Example of Reading TODO Items

Send a GET request to http://localhost:8000/todos/ to retrieve a list of TODO items.

Conclusion

This approach uses normal class-based views to handle CRUD operations, providing a straightforward way to manage TODO items with Django Rest Framework. Adjust the model, serializer, and views as needed for your specific application requirements.


Happy Coding

💖 💪 🙅 🚩
muhammedshamal
Muhammed Shamal PV

Posted on August 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related