Build a REST API with Django REST Framework
tags: python, django, api, tutorial
tags: python, django, api, tutorial
Build a REST API with Django REST Framework in Under 30 Minutes
Imagine you’ve spent hours crafting a sleek Django model, but your frontend team is stuck waiting for you to manually format JSON responses or write boilerplate view functions. That friction ends today. With Django REST Framework (DRF), you can spin up a production-ready REST API that handles serialization, authentication, and routing automatically—letting you focus on what actually matters: your business logic.
DRF isn’t just a library; it’s the industry standard for building APIs in Python. It transforms Django’s powerful ORM and view system into a robust API backbone with minimal code. In this guide, you’ll build a working Task API with full CRUD support, ready to deploy or integrate with React, Vue, or mobile apps.
Step 1: Set Up Your Environment
Before writing code, ensure your Python environment is clean. Create a virtual environment and install the necessary packages:
python -m venv env
source env/bin/activate # On Windows: env\Scripts\activate
pip install django djangorestframework
Now, create your Django project and a dedicated app for the API:
django-admin startproject taskapi
cd taskapi
python manage.py startapp tasks
Step 2: Configure DRF in Your Project
Open taskapi/settings.py and add 'rest_framework' and your new app to INSTALLED_APPS:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'tasks',
]
This tells Django to recognize DRF’s components. You’re now ready to define your data model.
Step 3: Define the Task Model
In tasks/models.py, create a simple model to represent tasks:
from django.db import models
class Task(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
completed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Run migrations to create the database table:
python manage.py makemigrations
python manage.py migrate
Step 4: Create a Serializer
Serializers convert complex data types (like model instances) into native Python datatypes that can then be rendered into JSON. Create tasks/serializers.py:
from rest_framework import serializers
from .models import Task
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ['id', 'title', 'description', 'completed', 'created_at']
The ModelSerializer automatically generates fields based on your model, saving you from writing manual serialization logic.
Step 5: Build ViewSets for CRUD Operations
Instead of writing individual view functions for GET, POST, PUT, and DELETE, DRF provides ViewSets—classes that bundle all CRUD logic together. In tasks/views.py:
from rest_framework import viewsets
from .models import Task
from .serializers import TaskSerializer
class TaskViewSet(viewsets.ModelViewSet):
queryset = Task.objects.all()
serializer_class = TaskSerializer
This single class handles:
-
GET /tasks/→ List all tasks -
GET /tasks/{id}/→ Retrieve one task -
POST /tasks/→ Create a new task -
PUT /tasks/{id}/→ Update a task -
DELETE /tasks/{id}/→ Delete a task
Step 6: Register Routes with a Router
DRF’s DefaultRouter automatically generates URL patterns for your ViewSet. In taskapi/urls.py:
from django.contrib import admin
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from tasks.views import TaskViewSet
router = DefaultRouter()
router.register(r'tasks', TaskViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
]
Now your API lives under /api/tasks/. The router also adds helpful browsable endpoints like /api/tasks/ and /api/tasks/{id}/.
Step 7: Test Your API
Start the development server:
python manage.py runserver
Visit http://localhost:8000/api/tasks/ in your browser. You’ll see DRF’s browsable API—a clean HTML interface showing your endpoints and allowing you to test them directly.
To create a task via POST, use curl or any HTTP client:
curl -X POST http://localhost:8000/api/tasks/ \
-H "Content-Type: application/json" \
-d '{"title": "Finish blog post", "description": "Write about DRF", "completed": false}'
You’ll get a JSON response with the new task’s data, including its auto-generated id.
Why This Approach Wins
Traditional Django views require you to write separate functions for each action, manually parse JSON, handle errors, and format responses. DRF eliminates that noise:
- Serialization: Automatically converts models to JSON.
- Authentication: Built-in support for tokens, sessions, and OAuth.
- Pagination: Lists are paginated by default.
- Browsable API: Instant documentation without writing Swagger specs.
- Content Negotiation: Supports JSON, XML, and more.
You can extend this starter API with filters, permissions, or custom actions in minutes. For example, adding filter_fields = ['completed'] in your ViewSet lets users query ?completed=true.
Take It Further
This API is ready to use today, but DRF’s power scales with your needs. Consider adding:
-
Authentication: Use
TokenAuthenticationorSessionAuthentication. -
Permissions: Restrict access with
IsAuthenticatedOrReadOnly. -
Custom Actions: Add
@actionmethods for non-standard endpoints like/tasks/{id}/complete/. -
Testing: DRF provides
APIClientfor seamless integration tests.
The full source code for this project is available on GitHub—copy it, tweak it, and ship your next feature faster.
Your Next Move
Don’t let another API sit half-built. Fork this pattern, swap in your own model, and deploy. Then, share your API endpoint with your team and watch them integrate it in minutes.
What’s the first feature you’ll add? Drop your idea in the comments, or tag me on Twitter with your DRF-powered API. Let’s build something awesome together.
If you found this helpful, consider buying me a coffee ☕ — it keeps these articles coming!
Also check out my AI tools collection: AI 次元世界 — free AI tools for developers.
Top comments (0)