Building a Basic Django REST API
Learn to build a REST API with Django REST Framework: models, serializers, ViewSets, and URL routing — using a TodoList app as the working example.
Django REST Framework (DRF) is the standard library for building REST APIs in Django. It handles serialization, authentication, viewsets, and browsable API documentation out of the box. This guide builds a simple TodoList API to demonstrate the core pieces.
Setup
Install Django and Django REST Framework:
pip install django djangorestframework
Create a project and app:
django-admin startproject mysite
cd mysite
python manage.py startapp TodoList
Register both in settings.py:
INSTALLED_APPS = [
'TodoList.apps.TodolistConfig',
'rest_framework',
# ... default apps
]
Apply the initial migrations:
python manage.py migrate
python manage.py createsuperuser
HTTP Methods at a Glance
| Method | Action |
|---|---|
| GET | Retrieve a resource or list |
| POST | Create a new resource |
| PUT | Replace an existing resource |
| PATCH | Update specific fields |
| DELETE | Remove a resource |
Defining Models
TodoList/models.py:
from django.db import models
class Group(models.Model):
title = models.CharField(max_length=200)
def __str__(self):
return self.title
class Item(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(default='')
date = models.DateTimeField()
completed = models.BooleanField(default=False)
todo_list = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='items')
def __str__(self):
return self.title
Run migrations:
python manage.py makemigrations
python manage.py migrate
Registering Models in the Admin
TodoList/admin.py:
from django.contrib import admin
from .models import Group, Item
class ItemInline(admin.TabularInline):
model = Item
extra = 1
class GroupAdmin(admin.ModelAdmin):
inlines = [ItemInline]
admin.site.register(Group, GroupAdmin)
Creating Serializers
Serializers convert model instances to JSON and validate incoming data.
TodoList/serializers.py:
from rest_framework import serializers
from .models import Group, Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('id', 'title', 'date', 'completed')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
items = ItemSerializer(many=True, read_only=True)
class Meta:
model = Group
fields = ('id', 'title', 'items')
Setting Up Views
DRF's ModelViewSet automatically provides list, create, retrieve, update, and destroy actions.
TodoList/views.py:
from rest_framework import viewsets
from .models import Group
from .serializers import GroupSerializer
class GroupViewSets(viewsets.ModelViewSet):
queryset = Group.objects.all().order_by('id')
serializer_class = GroupSerializer
Configuring URLs
TodoList/urls.py:
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'groups', views.GroupViewSets)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
mysite/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('TodoList.urls')),
]
Running and Testing the API
python manage.py runserver
Test with curl:
# List all groups
curl http://127.0.0.1:8000/api/groups/
# Create a group
curl -X POST http://127.0.0.1:8000/api/groups/ \
-H "Content-Type: application/json" \
-d '{"title": "Work Tasks"}'
# Retrieve a specific group
curl http://127.0.0.1:8000/api/groups/1/
Or navigate to http://127.0.0.1:8000/api/groups/ in your browser — DRF renders a browsable API UI where you can explore and test endpoints interactively.
Conclusion
DRF's ModelViewSet + router gives you a full CRUD API with minimal code. The key components are: models (data structure), serializers (validation and JSON conversion), viewsets (request handling), and routers (URL generation). From here, explore DRF's authentication classes, permissions, and filtering to build production-ready APIs.