Django REST Framework Tutorial
The Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs with Django. It simplifies creating RESTful endpoints with features like serialization, authentication, and browsable APIs. In this tutorial, you’ll learn to build a simple API to manage a collection of books.
🛠️ Set Up Your Project
First, create a new Django project and app:
pip install django djangorestframework
django-admin startproject myapi
cd myapi
python manage.py startapp books
Add 'rest_framework' and your app ('books') to your INSTALLED_APPS in myapi/settings.py:
INSTALLED_APPS = [
# other apps...
'rest_framework',
'books',
]
📄 Create the Book Model
In books/models.py:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
def __str__(self):
return self.title
Run migrations to create the database tables:
python manage.py makemigrations
python manage.py migrate
🔄 Create a Serializer
Serializers convert model instances to JSON and vice versa. Create books/serializers.py:
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
🌐 Create API Views
In books/views.py, use DRF’s generic views for CRUD operations:
from rest_framework import generics
from .models import Book
from .serializers import BookSerializer
class BookListCreateAPIView(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
🚦Set Up URLs
In books/urls.py, create URL patterns for your API endpoints:
from django.urls import path
from .views import BookListCreateAPIView, BookRetrieveUpdateDestroyAPIView
urlpatterns = [
path('books/', BookListCreateAPIView.as_view(), name='book-list'),
path('books/<int:pk>/', BookRetrieveUpdateDestroyAPIView.as_view(), name='book-detail'),
]
Then include these URLs in your project’s myapi/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('books.urls')),
]
🚀 Test Your API
Run the development server:
python manage.py runserver
Now, visit:
http://127.0.0.1:8000/api/books/ – to list or create books.
http://127.0.0.1:8000/api/books/<id>/ – to retrieve, update, or delete a specific book.
DRF provides a beautiful browsable API interface where you can test your endpoints directly from the browser!
✅ Conclusion
Congratulations! 🎉 You’ve built a basic CRUD API using Django REST Framework. You learned how to:
- Define a model,
- Create a serializer,
- Build API views,
- Set up URL routing.
From here, you can add authentication, filtering, pagination, or permissions to make your API production-ready.
Learn Fullstack Python Training Course
Read More:
Creating a Simple Web App with Flask
Django vs Flask: Which One Should You Learn?
Python Decorators and How to Use Them
Visit Quality Thought Training Institute
Comments
Post a Comment