Django REST Framework (DRF) is the standard for building APIs with Django.

Installation

  pip install djangorestframework
  

Add to INSTALLED_APPS:

  INSTALLED_APPS = [
    ...
    'rest_framework',
    'blog',
]
  

Serializers

Convert model instances to JSON and back:

  # blog/serializers.py
from rest_framework import serializers
from .models import Post, Comment

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = ['id', 'author', 'text', 'created_at']

class PostSerializer(serializers.ModelSerializer):
    comments = CommentSerializer(many=True, read_only=True)

    class Meta:
        model = Post
        fields = ['id', 'title', 'content', 'published', 'created_at', 'comments']
  

API Views

  # blog/views.py
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]
  

URL Configuration

  # blog/urls.py
from rest_framework.routers import DefaultRouter
from .views import PostViewSet

router = DefaultRouter()
router.register('posts', PostViewSet)

urlpatterns = router.urls
  
  # mysite/urls.py
urlpatterns = [
    path('api/', include('blog.urls')),
]
  

API Endpoints

Method URL Action
GET /api/posts/ List all posts
POST /api/posts/ Create a post
GET /api/posts/1/ Retrieve post #1
PUT /api/posts/1/ Update post #1
DELETE /api/posts/1/ Delete post #1

Authentication

  # settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20,
}
  

Generate tokens:

  pip install djangorestframework-simplejwt
  

Testing API Endpoints

  from rest_framework.test import APITestCase
from rest_framework import status

class PostAPITest(APITestCase):
    def test_list_posts(self):
        response = self.client.get('/api/posts/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_create_post(self):
        data = {'title': 'Test', 'content': 'Body', 'published': True}
        response = self.client.post('/api/posts/', data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
  

DRF makes it straightforward to expose your Django models as a fully-featured REST API.