Building a CRUD API with Django REST Framework: A Step-by-Step Guide

What is Django?
Django is a free, open-source, Python-based web framework that follows the Model-View-Template (MVT) architectural pattern. It simplifies web development, allowing you to focus on writing your app instead of reinventing the wheel.

What is a REST API?
A REST API is a popular way for systems to expose useful functions and data. It can be made up of one or more resources that can be accessed at a given URL and returned in various formats, such as JSON, images, HTML, and more.

Why Django REST Framework?
Django REST framework (DRF) is a powerful and flexible toolkit for building web APIs. Its main benefit is that it simplifies the process of serialization. DRF is based on Django’s class-based views, making it an excellent option if you’re familiar with Django.

Setting Up Django REST Framework

To get started, create a virtual environment to isolate dependencies (optional). Then, install Django and Django REST framework in your project using the following commands:

python -m venv django_env
source./django_env/bin/activate
pip install django djangorestframework

Create a new Django project called todo and a new app for your API:

django-admin startproject todo
cd todo
python manage.py startapp todo_api

RESTful Structure: GET, POST, PUT, and DELETE Methods

In a RESTful API, endpoints define the structure and usage of the GET, POST, PUT, and DELETE HTTP methods. You must organize these methods logically. Let’s create an example to-do API with two endpoints:

| Endpoint | HTTP Method | Description |
| — | — | — |
| /todos/api/ | GET | Retrieve all to-dos |
| /todos/api/ | POST | Create a new to-do |
| /todos/api/<int:todo_id> | GET | Retrieve a single to-do |
| /todos/api/<int:todo_id> | PUT | Update a to-do |
| /todos/api/<int:todo_id> | DELETE | Delete a to-do |

Creating Models for Our Django App

Let’s create the model for our to-do list:
“`python
from django.db import models

class Todo(models.Model):
title = models.CharField(maxlength=200)
completed = models.BooleanField(default=False)
created
at = models.DateTimeField(autonowadd=True)
updatedat = models.DateTimeField(autonow=True)

Migrate the model to the database:

python manage.py makemigrations
python manage.py migrate
“`
Model Serializer

Use the ModelSerializer class to convert the Todo model to serialized JSON objects:
“`python
from rest_framework import serializers
from.models import Todo

class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = [‘id’, ‘title’, ‘completed’, ‘createdat’, ‘updatedat’]
“`
Creating API Views in Django

Let’s create two API views: ListView and DetailView.

ListView
“`python
from restframework.response import Response
from rest
framework.views import APIView
from.serializers import TodoSerializer
from.models import Todo

class TodoListApiView(APIView):
permission_classes = [IsAuthenticated]

def get(self, request):
    todos = Todo.objects.filter(user=request.user)
    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=201)
    return Response(serializer.errors, status=400)


**DetailView**
python
class TodoDetailApiView(APIView):
permission_classes = [IsAuthenticated]

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

def put(self, request, pk):
    todo = Todo.objects.get(pk=pk)
    serializer = TodoSerializer(todo, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=400)

def delete(self, request, pk):
    todo = Todo.objects.get(pk=pk)
    todo.delete()
    return Response(status=204)

“`
Authentication and Permission in Django

Implement authentication and permissions in your Django apps using packages like Simple JWT and djoser.

Customizing HTTP Responses in Django

Customize HTTP responses using the Response object:
“`python
from rest_framework.response import Response

def get(self, request):
todos = Todo.objects.filter(user=request.user)
serializer = TodoSerializer(todos, many=True)
return Response({‘count’: todos.count(), ‘esults’: serializer.data, ‘essage’: ‘Success’}, status=200)
“`
Best Practices for Testing REST APIs Built with Django REST Framework

Implement best practices to test your REST API projects:

  • Use Django testing frameworks and functionalities like TestCase or APITestCase.
  • Test all HTTP methods to verify their behavior and document them for maintenance.
  • Mock external dependencies and services for test isolation.
  • Test edge cases like empty payloads, invalid data, and boundary conditions.
  • Integrate your API workflows into a CI/CD pipeline to automate testing.

By following these steps and best practices, you’ll have a fully functional CRUD Django REST API up and running. Happy coding!

Leave a Reply

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