CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-djangorestframework

Web APIs for Django, made easy.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Django REST Framework

A 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.

Package Information

  • Package Name: djangorestframework
  • Language: Python
  • Installation: pip install djangorestframework
  • Dependencies: django>=4.2
  • Python Requirements: >=3.9

Core Imports

import 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 APIView

Basic Usage

from 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)

Architecture

Django REST Framework follows a layered architecture designed around Django's philosophy:

  • Serializers: Convert between Python objects and JSON/XML data formats
  • Views/ViewSets: Handle HTTP requests and coordinate with serializers
  • Permissions: Control access to API endpoints
  • Authentication: Identify users making requests
  • Parsers/Renderers: Handle content negotiation for different formats
  • Routers: Generate URL patterns for ViewSets automatically

The framework emphasizes flexibility through class-based views and mixins, enabling everything from simple function-based views to complex ViewSets with automatic URL routing.

Capabilities

Serializers

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 = None

Serializers

Views and ViewSets

Class-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 = None

Views and ViewSets

Authentication and Permissions

Security 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

Fields and Validation

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): ...

Fields and Validation

Generic Views and Mixins

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): ...

Generic Views and Mixins

Request and Response

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): ...

Request and Response

Pagination and Filtering

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): ...

Pagination and Filtering

Routers and URL Patterns

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 = True

Routers and URL Patterns

Status Codes and Exceptions

Complete 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): ...

Status Codes and Exceptions

Testing Utilities

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 = APIClient

Testing Utilities

Decorators and Function-Based Views

Essential 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

Content Negotiation

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): ...

Content Negotiation

Types

# 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): ...
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/djangorestframework@3.16.x
Publish Source
CLI
Badge
tessl/pypi-djangorestframework badge