Flying Santa
Kimkorng

Building a CRUD API With Django and Django Rest Framework

07 FEB, 2023

In here, we are going to create a API that can create, read, update, and delete tasks with Django and Django Rest Framework to help you enhance your web application and improve user experience.

Setting Up the Django Project

  1. Create a virtual environment
    shell
    python -m venv env
  2. Activate virtual environment
    shell
    env\scripts\activate # windows source env/bin/activate #macOS and linux
  3. Install Django and DRF (Django Rest Framework):
    shell
    pip install django djangorestframework
  4. Create a Django Project:
    shell
    django-admin startproject myproject cd myproject
  5. Create a Django App:
    shell
    python manage.py startapp crudapp
  6. Add the App and DRF to INSTALLED_APPS in settings.py:
    python
    INSTALLED_APPS = [ ... 'rest_framework', 'crudapp', ]

Creating Models

Define your models in crudapp/models.py. For example, a simple Book model:

python
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) published_date = models.DateField() def __str__(self): return self.title

Create and Run Migrations

shell
python manage.py makemigrations python manage.py migrate

Creating Serializers

Create a serializer for your Book model in crudapp/serializers.py:

python
from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__'

Creating Views

Create views in crudapp/views.py using DRF's generic views:

python
from rest_framework import generics from .models import Book from .serializers import BookSerializer # Create Book's record. class BookListCreate(generics.ListCreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializer # Retrive, Update and Delete Book's record. class BookRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): queryset = Book.objects.all() serializer_class = BookSerializer

Creating URLs

Define your URLs in crudapp/urls.py:

python
from django.urls import path from .views import BookListCreate, BookRetrieveUpdateDestroy urlpatterns = [ path('books/', BookListCreate.as_view(), name='book-list-create'), path('books/<int:pk>/', BookRetrieveUpdateDestroy.as_view(), name='book-rud'), ]

Include your app's URLs in the project-level urls.py:

python
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('crudapp.urls')), ]

Testing the API

Run the development server:

shell
python manage.py runserver

You can now test the API using tools like Postman or cURL

SHARE