Introduction
Imagine you’re building a book management system where users can browse available books and add new ones. To make this possible, we need a REST API to handle book data efficiently.
REST APIs are the backbone of modern web applications, enabling seamless communication between frontend and backend systems. Django REST Framework (DRF) simplifies API development by providing a powerful toolkit built on top of Django. In this guide, we’ll build a simple REST API to manage books.
Prerequisites
Before starting this tutorial, you should have:
Basic understanding of Python programming
Familiarity with web development concepts
Python 3.8+ installed on your system
Basic knowledge of the Django framework
Understanding of HTTP methods (GET, POST, PUT, DELETE)
Experience using the command-line interface
Learning Objectives
By the end of this tutorial, you will be able to:
Set up a Django REST Framework project from scratch
Create API endpoints using function-based views (FBVs) and class-based views (CBVs)
Implement model serialization for JSON responses
Perform CRUD operations via a REST API
Test API endpoints using browsable API and cURL commands
Why Django REST Framework?
Django REST Framework has become the go-to choice for building APIs with Django because it offers:
️ Powerful serialization capabilities
️ Built-in authentication and permissions
️ Browsable API interface for easy testing
️ Extensive documentation and strong community support
️ Flexible request/response handling
️ Support for pagination, filtering, and throttling
Project Setup
Let’s start building our REST API step by step.
Step 1: Environment Setup
First, create a clean development environment:
# Create a project foldermkdir book-api && cd book-api# Create a virtual environmentpython -m venv venv# Activate the virtual environment (Windows)venv\Scripts\activate# Activate the virtual environment (Mac/Linux)source venv/bin/activate# Install Django and Django REST Frameworkpip install django djangorestframework# Create a project folder mkdir book-api && cd book-api # Create a virtual environment python -m venv venv # Activate the virtual environment (Windows) venv\Scripts\activate # Activate the virtual environment (Mac/Linux) source venv/bin/activate # Install Django and Django REST Framework pip install django djangorestframework# Create a project folder mkdir book-api && cd book-api # Create a virtual environment python -m venv venv # Activate the virtual environment (Windows) venv\Scripts\activate # Activate the virtual environment (Mac/Linux) source venv/bin/activate # Install Django and Django REST Framework pip install django djangorestframework
Enter fullscreen mode Exit fullscreen mode
Step 2: Project Creation
Now, create a Django project and an app for managing books.
# Create a Django projectdjango-admin startproject bookapicd bookapi# Create a Django apppython manage.py startapp books# Create a Django project django-admin startproject bookapi cd bookapi # Create a Django app python manage.py startapp books# Create a Django project django-admin startproject bookapi cd bookapi # Create a Django app python manage.py startapp books
Enter fullscreen mode Exit fullscreen mode
Step 3: Configuration
Register Django REST Framework and the books app in settings.py:
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',# Third-party apps'rest_framework',# Local apps'books',]INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third-party apps 'rest_framework', # Local apps 'books', ]INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third-party apps 'rest_framework', # Local apps 'books', ]
Enter fullscreen mode Exit fullscreen mode
Building the API
Step 4: Model Definition
Define a Book model in books/models.py:
from django.db import modelsclass Book(models.Model):title = models.CharField(max_length=255)author = models.CharField(max_length=255)published_date = models.DateField()isbn = models.CharField(max_length=13, unique=True)def __str__(self):return self.titlefrom django.db import models class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) published_date = models.DateField() isbn = models.CharField(max_length=13, unique=True) def __str__(self): return self.titlefrom django.db import models class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) published_date = models.DateField() isbn = models.CharField(max_length=13, unique=True) def __str__(self): return self.title
Enter fullscreen mode Exit fullscreen mode
Apply the migrations:
python manage.py makemigrations bookspython manage.py migratepython manage.py makemigrations books python manage.py migratepython manage.py makemigrations books python manage.py migrate
Enter fullscreen mode Exit fullscreen mode
Step 5: Serializer Creation
Create books/serializers.py to handle data conversion:
from rest_framework import serializersfrom .models import Bookclass BookSerializer(serializers.ModelSerializer):class Meta:model = Bookfields = '__all__'from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__'from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__'
Enter fullscreen mode Exit fullscreen mode
Step 6: API Views
We’ll implement both function-based views (FBVs) and class-based views (CBVs).
Function-Based Views (FBVs)
Edit books/views.py:
from rest_framework.response import Responsefrom rest_framework.decorators import api_viewfrom .models import Bookfrom .serializers import BookSerializer@api_view(['GET'])def book_list(request):books = Book.objects.all()serializer = BookSerializer(books, many=True)return Response(serializer.data)@api_view(['POST'])def book_create(request):serializer = BookSerializer(data=request.data)if serializer.is_valid():serializer.save()return Response(serializer.data, status=201)return Response(serializer.errors, status=400)from rest_framework.response import Response from rest_framework.decorators import api_view from .models import Book from .serializers import BookSerializer @api_view(['GET']) def book_list(request): books = Book.objects.all() serializer = BookSerializer(books, many=True) return Response(serializer.data) @api_view(['POST']) def book_create(request): serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400)from rest_framework.response import Response from rest_framework.decorators import api_view from .models import Book from .serializers import BookSerializer @api_view(['GET']) def book_list(request): books = Book.objects.all() serializer = BookSerializer(books, many=True) return Response(serializer.data) @api_view(['POST']) def book_create(request): serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400)
Enter fullscreen mode Exit fullscreen mode
Class-Based Views (CBVs)
For a more scalable approach, use Django REST Framework’s generic views:
from rest_framework import genericsfrom .models import Bookfrom .serializers import BookSerializerclass BookListCreateView(generics.ListCreateAPIView):queryset = Book.objects.all()serializer_class = BookSerializerfrom rest_framework import generics from .models import Book from .serializers import BookSerializer class BookListCreateView(generics.ListCreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializerfrom rest_framework import generics from .models import Book from .serializers import BookSerializer class BookListCreateView(generics.ListCreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializer
Enter fullscreen mode Exit fullscreen mode
Step 7: URL Configuration
Set up books/urls.py:
from django.urls import pathfrom .views import book_list, book_create, BookListCreateViewurlpatterns = [# Function-based viewspath('books/', book_list, name='book-list'),path('books/create/', book_create, name='book-create'),# Class-based viewspath('books/cbv/', BookListCreateView.as_view(), name='book-list-cbv'),]from django.urls import path from .views import book_list, book_create, BookListCreateView urlpatterns = [ # Function-based views path('books/', book_list, name='book-list'), path('books/create/', book_create, name='book-create'), # Class-based views path('books/cbv/', BookListCreateView.as_view(), name='book-list-cbv'), ]from django.urls import path from .views import book_list, book_create, BookListCreateView urlpatterns = [ # Function-based views path('books/', book_list, name='book-list'), path('books/create/', book_create, name='book-create'), # Class-based views path('books/cbv/', BookListCreateView.as_view(), name='book-list-cbv'), ]
Enter fullscreen mode Exit fullscreen mode
**Update bookapi/urls.py:
from django.contrib import adminfrom django.urls import path, includeurlpatterns = [path('admin/', admin.site.urls),path('api/', include('books.urls')),]from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('books.urls')), ]from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('books.urls')), ]
Enter fullscreen mode Exit fullscreen mode
Testing the API
Using Browsable API
Run the server and visit:
http://127.0.0.1:8000/api/books/
Django REST Framework provides an interactive browsable API that allows you to test endpoints without external tools!
Using cURL
You can also test the API using cURL commands:
# GET requestcurl -X GET http://127.0.0.1:8000/api/books/# POST requestcurl -X POST http://127.0.0.1:8000/api/books/create/ \-H "Content-Type: application/json" \-d '{"title": "Django for Beginners", "author": "William Vincent", "published_date": "2021-09-01", "isbn": "9781735467207"}'# GET request curl -X GET http://127.0.0.1:8000/api/books/ # POST request curl -X POST http://127.0.0.1:8000/api/books/create/ \ -H "Content-Type: application/json" \ -d '{"title": "Django for Beginners", "author": "William Vincent", "published_date": "2021-09-01", "isbn": "9781735467207"}'# GET request curl -X GET http://127.0.0.1:8000/api/books/ # POST request curl -X POST http://127.0.0.1:8000/api/books/create/ \ -H "Content-Type: application/json" \ -d '{"title": "Django for Beginners", "author": "William Vincent", "published_date": "2021-09-01", "isbn": "9781735467207"}'
Enter fullscreen mode Exit fullscreen mode
Next Steps: Enhancing Your API
Now that you have a working API, consider improving it with:
️ Authentication & Permissions (e.g., only authenticated users can add books)
️ Pagination for Large Datasets
️ Filtering & Searching
️ ViewSets & Routers for cleaner URL management
Conclusion
Congratulations! You have successfully built a simple REST API using the Django REST Framework. This foundation can be expanded to develop more complex APIs with additional features and security measures.
Want to go further?
Explore the Django REST Framework Documentation for advanced topics.
Happy coding!
原文链接:Building a REST API with Django REST Framework: A Beginners Guide
暂无评论内容