CRUD APIs

  • Create complete CRUD REST APIs using Django REST Framework.
  • What are CRUD APIs?

    CRUD APIs allow basic database operations via API:

    Operation

    HTTP Method

    Description

    Create

    POST

    Add new record

    Read

    GET

    Fetch record(s)

    Update

    PUT / PATCH

    Modify existing record

    Delete

    DELETE

    Remove record

    Why CRUD APIs are Important?

    • Most applications need data management

    • APIs expose backend functionality to frontend, mobile, or third-party apps

    • DRF simplifies CRUD using ModelSerializer & APIViews

    Model Setup

Student Model

models.py

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    course = models.CharField(max_length=50)

    def __str__(self):
        return self.name
  •  Description

    • Model has name, email, course

    • Used for CRUD API operations

    Serializer Setup

ModelSerializer

serializers.py

from rest_framework import serializers
from .models import Student

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['id', 'name', 'email', 'course']
  •  Description

    • Converts Student objects ↔ JSON

    • Handles validation automatically

  • CRUD API Using Class-Based APIViews

Student List & Create API

views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Student
from .serializers import StudentSerializer

class StudentListCreateAPI(APIView):

    def get(self, request):
        students = Student.objects.all()
        serializer = StudentSerializer(students, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = StudentSerializer(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)
  • Description

    • get() → Fetch all students

    • post() → Create a new student

    • Returns JSON & proper HTTP status codes

Student Detail API (Read, Update, Delete)

class StudentDetailAPI(APIView):

    def get_object(self, pk):
        try:
            return Student.objects.get(pk=pk)
        except Student.DoesNotExist:
            return None

    def get(self, request, pk):
        student = self.get_object(pk)
        if not student:
            return Response({"error": "Not Found"}, status=status.HTTP_404_NOT_FOUND)
        serializer = StudentSerializer(student)
        return Response(serializer.data)

    def put(self, request, pk):
        student = self.get_object(pk)
        if not student:
            return Response({"error": "Not Found"}, status=status.HTTP_404_NOT_FOUND)
        serializer = StudentSerializer(student, 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):
        student = self.get_object(pk)
        if not student:
            return Response({"error": "Not Found"}, status=status.HTTP_404_NOT_FOUND)
        serializer = StudentSerializer(student, 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):
        student = self.get_object(pk)
        if not student:
            return Response({"error": "Not Found"}, status=status.HTTP_404_NOT_FOUND)
        student.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
  • Description

    • Handles GET, PUT, PATCH, DELETE for single student

    • get_object() → Helper function to reduce repetition

    • Returns appropriate status codes

    URL Configuration

CRUD API URLs

urls.py

from django.urls import path
from .views import StudentListCreateAPI, StudentDetailAPI

urlpatterns = [
    path('api/students/', StudentListCreateAPI.as_view(), name='student-list'),
    path('api/students/<int:pk>/', StudentDetailAPI.as_view(), name='student-detail'),
]
  •  Description

    • /api/students/ → GET all / POST create

    • /api/students/<id>/ → GET, PUT, PATCH, DELETE single student