Add an API layer to your Django app. Serializers convert models to JSON, ViewSets provide CRUD endpoints, and TokenAuth secures them.
pip install djangorestframework
# Add to INSTALLED_APPS: 'rest_framework'from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
author_name = serializers.CharField(source='author.username', read_only=True)
class Meta:
model = Post
fields = ['id', 'title', 'slug', 'body', 'author_name', 'created_at', 'published']
read_only_fields = ['slug', 'created_at']from rest_framework import viewsets, permissions
from .models import Post
from .serializers import PostSerializer
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.filter(published=True)
serializer_class = PostSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save(author=self.request.user)from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('posts', views.PostViewSet)
urlpatterns = router.urls
# Registers: GET /posts/, POST /posts/, GET /posts/{id}/, PUT, PATCH, DELETE# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
INSTALLED_APPS += ['rest_framework.authtoken']
# python manage.py migrate
# POST /api-token-auth/ with username/password → returns token
# Client sends: Authorization: Token ModelSerializer auto-generates fields from the model.ModelViewSet provides all 5 CRUD endpoints (list, create, retrieve, update, destroy) with minimal code.IsAuthenticatedOrReadOnly = public reads, auth required for writes. The right default for most APIs.