Django REST Framework
Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs with Django. It simplifies the creation of RESTful services by providing robust serialization, authentication, permission management, and browsable API features. The library is actively maintained, with frequent minor and patch releases, currently at version 3.17.1.
Warnings
- breaking Support for Python 3.9 was dropped in DRF 3.17.0.
- breaking Deprecated `coreapi` support was entirely removed in DRF 3.17.0. If you were using `coreapi` for schema generation, you must migrate to a different solution, such as `drf-yasg` for OpenAPI/Swagger.
- breaking Support for Django 2.2 was dropped in DRF 3.14.0. Users on older Django versions must upgrade Django or pin DRF to an earlier compatible version.
- gotcha The `raise_exception` argument for serializer's `is_valid()` method became keyword-only in DRF 3.14.0.
- gotcha By default, DRF's global permission policy is `AllowAny`, meaning all incoming requests are allowed without authentication. This is often a security risk for production APIs.
- gotcha When dealing with writable nested serializers, `ModelSerializer`'s default `create()` and `update()` methods do not automatically handle saving related (nested) instances. You often need to override these methods.
- gotcha Django REST Framework's ViewSets implicitly define many endpoints (e.g., `list`, `create`, `retrieve`, `update`, `destroy`). This abstraction can make debugging or understanding request flow challenging compared to explicitly defined function-based views or traditional controllers.
Install
-
pip install djangorestframework
Imports
- APIView
from rest_framework.views import APIView
- serializers
from rest_framework import serializers
- ModelViewSet
from rest_framework import viewsets
- DefaultRouter
from rest_framework.routers import DefaultRouter
- permissions
from rest_framework import permissions
Quickstart
import os
import django
from django.conf import settings
from django.urls import path, include
from django.db import models
# Minimal Django settings for DRF
settings.configure(
DEBUG=True,
SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'django-insecure-DRF-quickstart-secret-key-for-testing'),
ROOT_URLCONF=__name__,
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'rest_framework',
],
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
)
django.setup()
from rest_framework import routers, serializers, viewsets
# 1. Define a simple Django Model
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
# 2. Define a Serializer for the Model
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = '__all__'
# 3. Define a ViewSet for CRUD operations
class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all().order_by('-created_at')
serializer_class = ItemSerializer
# 4. Set up a Router for automatic URL configuration
router = routers.DefaultRouter()
router.register(r'items', ItemViewSet)
# 5. Define URL patterns (mimicking a Django urls.py)
urlpatterns = [
path('api/', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
# Example usage (run in a Django shell or a test setup)
if __name__ == '__main__':
# This part would typically be handled by Django's manage.py runserver
# For demonstration, we'll manually interact.
# In a real app, you'd run migrations and have a Django server.
print("DRF Quickstart Example Setup Complete.")
print("To interact, define URLs and run a Django development server.")
# Example: Accessing router URLs
# for url_pattern in router.urls:
# print(url_pattern)
# Note: To run this code interactively outside a full Django project,
# you'd need a more involved setup to serve the API, e.g., using a test client.
# For a minimal runnable example that doesn't require a full Django project setup:
# This code snippet focuses on the DRF component definitions.
pass