Web APIs for Django, made easy.
npx @tessl/cli install tessl/pypi-djangorestframework@3.16.0A powerful and flexible toolkit for building Web APIs in Django applications. Django REST framework provides comprehensive features for creating RESTful APIs including serialization, authentication, permissions, content negotiation, pagination, filtering, and a browsable API interface.
pip install djangorestframeworkdjango>=4.2>=3.9import rest_framework
from rest_framework import serializers, viewsets, permissions, status
from rest_framework.decorators import api_view, action
from rest_framework.response import Response
from rest_framework.views import APIViewfrom rest_framework import serializers, viewsets, permissions
from rest_framework.response import Response
from django.contrib.auth.models import User
# Create a serializer
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email']
# Create a viewset
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
# Or use function-based views
from rest_framework.decorators import api_view
@api_view(['GET', 'POST'])
def user_list(request):
if request.method == 'GET':
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)Django REST Framework follows a layered architecture designed around Django's philosophy:
The framework emphasizes flexibility through class-based views and mixins, enabling everything from simple function-based views to complex ViewSets with automatic URL routing.
Core serialization framework for converting between Python objects and JSON/XML data. Handles validation, type conversion, and nested relationships with comprehensive field types and custom validation logic.
class Serializer(BaseSerializer):
def __init__(self, instance=None, data=empty, **kwargs): ...
def is_valid(self, raise_exception=False): ...
def save(self): ...
def create(self, validated_data): ...
def update(self, instance, validated_data): ...
class ModelSerializer(Serializer):
class Meta:
model = None
fields = NoneClass-based views and ViewSets for handling HTTP requests. Includes generic views for common patterns, mixins for modular functionality, and ViewSets for automatic URL routing.
class APIView(View):
authentication_classes = []
permission_classes = []
parser_classes = []
renderer_classes = []
def dispatch(self, request, *args, **kwargs): ...
class ViewSet(ViewSetMixin, APIView):
def list(self, request): ...
def create(self, request): ...
class ModelViewSet(GenericViewSet):
queryset = None
serializer_class = NoneSecurity framework providing authentication backends and permission classes. Supports session authentication, token authentication, and custom authentication with granular permission control.
class BaseAuthentication:
def authenticate(self, request): ...
def authenticate_header(self, request): ...
class BasePermission:
def has_permission(self, request, view): ...
def has_object_permission(self, request, view, obj): ...
class TokenAuthentication(BaseAuthentication): ...
class IsAuthenticated(BasePermission): ...Authentication and Permissions
Comprehensive field types for data validation and serialization. Includes basic types, specialized fields for files/images, and relationship fields with custom validation support.
class Field:
def __init__(self, **kwargs): ...
def to_representation(self, value): ...
def to_internal_value(self, data): ...
def validate(self, value): ...
class CharField(Field): ...
class IntegerField(Field): ...
class DateTimeField(Field): ...
class SerializerMethodField(Field): ...Pre-built generic views and mixins for common API patterns. Provides CRUD operations, pagination, and filtering with minimal code.
class GenericAPIView(APIView):
queryset = None
serializer_class = None
def get_queryset(self): ...
def get_object(self): ...
class ListAPIView(GenericAPIView): ...
class CreateAPIView(GenericAPIView): ...
class RetrieveUpdateDestroyAPIView(GenericAPIView): ...Enhanced request and response objects providing consistent data access and content negotiation across different formats.
class Request:
@property
def data(self): ...
@property
def query_params(self): ...
class Response(SimpleTemplateResponse):
def __init__(self, data=None, status=None, template_name=None, headers=None, exception=False, content_type=None): ...Built-in pagination styles and filtering backends for managing large datasets with search and ordering capabilities.
class PageNumberPagination(BasePagination):
page_size = None
page_query_param = 'page'
def paginate_queryset(self, queryset, request, view=None): ...
class SearchFilter(BaseFilterBackend):
search_param = 'search'
def filter_queryset(self, request, queryset, view): ...Automatic URL pattern generation for ViewSets with support for nested routes and custom actions.
class SimpleRouter(BaseRouter):
def register(self, prefix, viewset, basename=None): ...
def get_urls(self): ...
class DefaultRouter(SimpleRouter):
include_root_view = True
include_format_suffixes = TrueComplete HTTP status code constants and structured exception classes for consistent error handling.
# Constants
HTTP_200_OK = 200
HTTP_201_CREATED = 201
HTTP_400_BAD_REQUEST = 400
HTTP_404_NOT_FOUND = 404
# Exception classes
class APIException(Exception):
status_code = None
default_detail = None
class ValidationError(APIException): ...
class NotFound(APIException): ...Comprehensive testing tools including API client, request factory, and test case classes for thorough API testing.
class APIClient(APIRequestFactory, DjangoClient):
def force_authenticate(self, user=None, token=None): ...
def get(self, path, data=None, **extra): ...
def post(self, path, data=None, format=None, **extra): ...
class APITestCase(testcases.TestCase):
client_class = APIClientEssential decorators for function-based views and ViewSet customization, including API view creation, policy settings, and custom action definitions.
def api_view(http_method_names=None):
"""Convert function-based view into APIView subclass."""
def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs):
"""Mark ViewSet method as routable action."""
def permission_classes(permission_classes):
"""Set permission classes for function-based views."""
def authentication_classes(authentication_classes):
"""Set authentication classes for function-based views."""
def throttle_classes(throttle_classes):
"""Set throttle classes for function-based views."""
class MethodMapper(dict):
"""Enables mapping HTTP methods to different ViewSet methods."""Decorators and Function-Based Views
Parser and renderer classes for handling multiple content types with automatic format detection and conversion.
class BaseParser:
media_type = None
def parse(self, stream, media_type=None, parser_context=None): ...
class BaseRenderer:
media_type = None
def render(self, data, accepted_media_type=None, renderer_context=None): ...# Core constants
empty = object() # Sentinel for no data provided
ALL_FIELDS = '__all__' # Include all model fields
# Exception types
class ErrorDetail(str):
def __new__(cls, string, code=None): ...
# Utility types
class ReturnDict(dict):
def __init__(self, *args, **kwargs): ...
class ReturnList(list):
def __init__(self, *args, **kwargs): ...