Django REST Framework Type Stubs

3.16.9 · active · verified Thu Apr 09

djangorestframework-stubs provides PEP-484 type stubs for the Django REST Framework (DRF) library, enabling static type checking with tools like MyPy. It ensures type correctness for DRF components, improving code quality and maintainability. The current version is 3.16.9, with new releases often accompanying updates to DRF, Django, or MyPy.

Warnings

Install

Imports

Quickstart

This example showcases type-hinted Django REST Framework components. When `djangorestframework-stubs` is installed alongside `django-stubs` and `mypy` with the respective plugins configured, your static type checker will enforce type correctness for DRF-specific constructs like `serializers`, `views`, and `requests` at development time.

import os
from django.db import models
from rest_framework import serializers, viewsets
from rest_framework.response import Response
from rest_framework.request import Request # For type hinting

# A minimal Django model (assuming Django and django-stubs are installed)
class MyModel(models.Model):
    name: models.CharField = models.CharField(max_length=100)
    value: models.IntegerField = models.IntegerField()

    def __str__(self) -> str:
        return self.name

# A DRF ModelSerializer for MyModel
class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ['id', 'name', 'value']

# A DRF ViewSet for MyModel
class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

    # Example of a custom action with type hints
    def list(self, request: Request, *args, **kwargs) -> Response:
        # With djangorestframework-stubs installed, MyPy can check types here.
        # For instance, ensuring 'request.user' (if present) is accessed correctly.
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

# To utilize these stubs, configure MyPy (e.g., in pyproject.toml or mypy.ini):
# [tool.mypy]
# plugins = [
#     "mypy_django_plugin.main",
#     "mypy_drf_plugin.main"
# ]
# strict = true

# Then run: `mypy your_app_name/`

# This code focuses on demonstrating type hinting for DRF components,
# not on running a live Django/DRF application.

view raw JSON →