Tech With Galvan
Back to Articles
DevelopmentFeb 28, 2027 • 6 min read

Django REST Framework: Build a Production API

Build a production REST API with Django REST Framework — serializers, viewsets, authentication, permissions, and pagination. Complete guide.

Galvan
Galvan

Founder & Creator

Introduction

Django + Django REST Framework (DRF) is the most battle-tested Python stack for production APIs. It gives you an ORM, admin panel, auth, and a REST framework — all in one. This post builds a production API with DRF.

Setup

pip install django djangorestframework
django-admin startproject myapi
cd myapi
python manage.py startapp notes

Step 1: Settings

# settings.py
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",
    "notes",
]

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.TokenAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",
    ],
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 20,
}

Step 2: Model

# notes/models.py
from django.db import models
from django.contrib.auth.models import User

class Note(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="notes")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return self.title

Migrate:

python manage.py makemigrations
python manage.py migrate

Step 3: Serializer

# notes/serializers.py
from rest_framework import serializers
from .models import Note

class NoteSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source="owner.username")

    class Meta:
        model = Note
        fields = ["id", "title", "body", "owner", "created_at", "updated_at"]
        read_only_fields = ["id", "owner", "created_at", "updated_at"]

Serializers convert models ↔ JSON. ModelSerializer auto-generates fields from the model.

Step 4: ViewSet

# notes/views.py
from rest_framework import viewsets, permissions
from .models import Note
from .serializers import NoteSerializer

class NoteViewSet(viewsets.ModelViewSet):
    queryset = Note.objects.all()
    serializer_class = NoteSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        # Users only see their own notes
        return Note.objects.filter(owner=self.request.user)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

ModelViewSet gives you CRUD (list, create, retrieve, update, destroy) for free.

Step 5: URLs (router)

# notes/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import NoteViewSet

router = DefaultRouter()
router.register(r"notes", NoteViewSet, basename="note")

urlpatterns = [
    path("", include(router.urls)),
]

# myapi/urls.py
from django.urls import path, include
from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    path("api/", include("notes.urls")),
    path("api/auth/token/", obtain_auth_token),
    path("admin/", admin.site.urls),
]

The router auto-generates URLs:

  • GET /api/notes/ — list
  • POST /api/notes/ — create
  • GET /api/notes/{id}/ — retrieve
  • PUT /api/notes/{id}/ — update
  • DELETE /api/notes/{id}/ — delete

Step 6: Authentication (token)

# Create a user
python manage.py createsuperuser

Get a token:

curl -X POST http://localhost:8000/api/auth/token/ \
  -d "username=admin&password=yourpassword"
# {"token": "abc123..."}

Use the token:

curl http://localhost:8000/api/notes/ \
  -H "Authorization: Token abc123..."
# settings.py
REST_FRAMEWORK = {
    ...
    "DEFAULT_FILTER_BACKENDS": [
        "django_filters.rest_framework.DjangoFilterBackend",
        "rest_framework.filters.SearchFilter",
        "rest_framework.filters.OrderingFilter",
    ],
}

# views.py
class NoteViewSet(viewsets.ModelViewSet):
    ...
    filterset_fields = ["owner"]
    search_fields = ["title", "body"]
    ordering_fields = ["created_at", "title"]

Now you can:

  • Filter: GET /api/notes/?owner=1
  • Search: GET /api/notes/?search=meeting
  • Order: GET /api/notes/?ordering=-created_at

Step 8: Permissions

from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.owner == request.user

class NoteViewSet(viewsets.ModelViewSet):
    ...
    permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly]

Users can read any note but only edit/delete their own.

Step 9: Testing

# tests/test_notes.py
from django.test import TestCase
from rest_framework.test import APIClient
from django.contrib.auth.models import User

class NoteTests(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user("test", password="pass")
        self.client.force_authenticate(user=self.user)

    def test_create_note(self):
        r = self.client.post("/api/notes/", {"title": "Test", "body": "Hello"})
        self.assertEqual(r.status_code, 201)
        self.assertEqual(r.data["title"], "Test")

    def test_list_notes(self):
        r = self.client.get("/api/notes/")
        self.assertEqual(r.status_code, 200)

Run: python manage.py test

Step 10: Deploy

pip install gunicorn
gunicorn myapi.wsgi:application -w 4 -b 0.0.0.0:8000

Use with Docker + nginx for production.

DRF vs FastAPI

DRF FastAPI
ORM Built-in (Django ORM) Bring your own (SQLAlchemy)
Admin panel Built-in No
Auth Built-in (token, session, OAuth) Manual (or fastapi-users)
Async Limited Native
Auto docs Browsable API (HTML) Swagger/OpenAPI
Performance Good Excellent
Learning curve Medium (Django ecosystem) Low
Ecosystem Massive (10+ years) Growing
Best for Full-stack apps, admin-heavy Microservices, async, APIs

Choose DRF when:

  • You need an admin panel.
  • You’re building a full-stack app (Django templates + API).
  • You want auth, ORM, and migrations out of the box.
  • Your team knows Django.

Choose FastAPI when:

  • Building a pure API (no admin, no templates).
  • You need async I/O.
  • You want auto-generated OpenAPI docs.
  • Performance is critical.

Common mistakes

  • No permissions — default to IsAuthenticated, not AllowAny.
  • N+1 queries — use select_related/prefetch_related in get_queryset.
  • Serializing everything — use read_only_fields to avoid over-posting.
  • No pagination — large datasets crash clients. Always paginate.
  • Debug mode in production — DEBUG = False in settings.

Key Concepts

  • Model = database table (Django ORM)
  • Serializer = model ↔ JSON conversion
  • ViewSet = CRUD logic
  • Router = auto-generates URLs
  • Permission = access control
  • Token auth = stateless authentication

What to Try Next

FAQ

DRF vs FastAPI — which for a new project?

FastAPI for pure APIs and microservices. DRF for full-stack apps with admin panels. If you need an admin UI, DRF. If you just need an API, FastAPI.

Is Django too heavy for a simple API?

Yes — Django + DRF has significant overhead. For a simple CRUD API, FastAPI or Flask is lighter. Django shines when you need the full stack (ORM, admin, auth, migrations).

Can I use DRF with async views?

DRF 3.14+ supports async views, but the ORM is still sync. For truly async, use FastAPI + SQLAlchemy (async). DRF’s async support is improving but not there yet.