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
- Create a virtual environment
shell
python -m venv env
- Activate virtual environment
shell
env\scripts\activate # windows source env/bin/activate #macOS and linux
- Install Django and DRF (Django Rest Framework):
shell
pip install django djangorestframework
- Create a Django Project:
shell
django-admin startproject myproject cd myproject
- Create a Django App:
shell
python manage.py startapp crudapp
- Add the App and DRF to
INSTALLED_APPS
insettings.py
:pythonINSTALLED_APPS = [ ... 'rest_framework', 'crudapp', ]
Creating Models
Define your models in crudapp/models.py
. For example, a simple Book
model:
pythonfrom 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
shellpython manage.py makemigrations python manage.py migrate
Creating Serializers
Create a serializer for your Book
model in crudapp/serializers.py
:
pythonfrom 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:
pythonfrom 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
:
pythonfrom 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
:
pythonfrom 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:
shellpython manage.py runserver
You can now test the API using tools like Postman or cURL