How to Build REST APIs with Django: A Step-by-Step Tutorial
Building REST APIs is essential for modern web development, allowing frontend and mobile apps to communicate with backend services. Django, combined with the Django REST framework (Official site), provides a powerful toolkit to create REST APIs quickly and efficiently. This guide walks you through building your first REST API with Django step-by-step.
Prerequisites
- Basic knowledge of Python and Django.
- Python 3 installed (preferably Python 3.8+).
- Familiarity with REST concepts is helpful but not mandatory.
- A working development environment (you can use virtualenv or venv).
Step 1: Setting Up Your Django Project
python -m venv env
source env/bin/activate # On Windows: env\Scripts\activate
pip install django djangorestframework
django-admin startproject myproject
cd myproject
python manage.py startapp api
This creates a Django project and an app called api where our API code will reside.
Step 2: Configure Django REST Framework
Add rest_framework and your app to INSTALLED_APPS in myproject/settings.py:
INSTALLED_APPS = [
# existing apps...
'rest_framework',
'api',
]
Step 3: Create a Simple Model
In api/models.py, define a model. For example, a simple Book model:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
published = models.DateField()
def __str__(self):
return self.title
Step 4: Make and Apply Migrations
python manage.py makemigrations
python manage.py migrate
Step 5: Create a Serializer
Serializers convert model instances to JSON and validate incoming request data. Create api/serializers.py:
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
Step 6: Build API Views
Use Django REST framework’s generic views for common API operations. Edit api/views.py:
from rest_framework import generics
from .models import Book
from .serializers import BookSerializer
class BookListCreate(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
Step 7: Configure URLs
Create api/urls.py to route API requests:
from django.urls import path
from .views import BookListCreate, BookDetail
urlpatterns = [
path('books/', BookListCreate.as_view(), name='book-list-create'),
path('books/<int:pk>/', BookDetail.as_view(), name='book-detail'),
]
Include the app URLs in the project’s urls.py (myproject/urls.py):
from django.urls import path, include
urlpatterns = [
path('api/', include('api.urls')), # API endpoints under /api/
]
Step 8: Run Your Server and Test
python manage.py runserver
You can test your REST API using curl, Postman, or your browser at http://127.0.0.1:8000/api/books/.
Example of Creating a Book using curl:
curl -X POST http://127.0.0.1:8000/api/books/ \
-H "Content-Type: application/json" \
-d '{"title": "Django for Beginners", "author": "William S. Vincent", "published": "2018-12-12"}'
Troubleshooting Tips
- Migration errors: If you change models, always remember to make and apply migrations.
- 404 Not Found on API URLs: Check URL patterns and make sure you included app URLs in the project.
- JSON errors: Ensure you send proper JSON with all required fields when creating or updating.
- Development server not running: Verify no other process is using port 8000 or specify different port with
--port.
Summary Checklist
- Set up Django project and app.
- Install and configure Django REST framework.
- Define data models.
- Create serializers for models.
- Build API Views for CRUD operations.
- Configure API URLs routes.
- Run server and test API endpoints.
This tutorial showed you how to build a robust REST API with Django. For more details on specific Django features, see our guide on How to Install Django Rest Framework: Step-by-Step Guide. Start creating rich backend services for your web and mobile apps with Django today!
