Django REST Framework Types

0.9.0 · active · verified Thu Apr 16

djangorestframework-types provides essential type stubs for Django REST Framework, enabling robust static type checking with tools like MyPy. As of version 0.9.0, it targets DRF 3.14+ and Python 3.8+, with updates typically released to support new DRF versions and features.

Common errors

Warnings

Install

Imports

Quickstart

To enable type checking for Django REST Framework, you *must* configure your `mypy.ini` file in your project root, adding the `drf_types.plugin.DrfPlugin` (see warnings section for details on `mypy.ini`). The Python example demonstrates how `djangorestframework-types` allows MyPy to correctly infer types for DRF serializers and their validated data, catching potential issues at development time. Save this as a Python file and run `mypy your_file.py` after installation and `mypy.ini` setup.

# mypy.ini (create or update this file in your project root):
# [mypy]
# plugins =
#    drf_types.plugin.DrfPlugin
#
# [drf-types]
# # Optional: List your custom DRF apps for deeper introspection
# # apps =
# #   my_app
# #   another_app


# quickstart_example.py (save this as a Python file):
from rest_framework import serializers
import os # For os.environ.get if needed for real data/auth

class UserSerializer(serializers.Serializer):
    id: serializers.IntegerField = serializers.IntegerField(read_only=True)
    username: serializers.CharField = serializers.CharField(max_length=150)
    email: serializers.EmailField = serializers.EmailField()

    def create(self, validated_data: dict[str, str]) -> dict[str, str]:
        # In a real application, this would create a User model instance.
        # This example just returns the data for demonstration.
        print(f"Creating user: {validated_data.get('username', 'N/A')}")
        return validated_data

    def update(self, instance: dict, validated_data: dict[str, str]) -> dict:
        # In a real application, this would update a User model instance.
        print(f"Updating user: {instance.get('id', 'N/A')}")
        instance['username'] = validated_data.get('username', instance.get('username', ''))
        instance['email'] = validated_data.get('email', instance.get('email', ''))
        return instance

# Example usage with type checking:
initial_data = {
    "username": "testuser_" + os.environ.get('TEST_ID', '1'),
    "email": "test@example.com"
}

serializer = UserSerializer(data=initial_data)
serializer.is_valid(raise_exception=True)

# `validated_data` is now correctly typed thanks to djangorestframework-types
validated_data: dict[str, str] = serializer.validated_data

# MyPy will detect issues like accessing non-existent keys:
# print(validated_data['non_existent_field']) # Mypy would flag this as an error

print(f"Validated username: {validated_data['username']}")

# To run type checking, ensure mypy.ini is configured as above, then:
# mypy quickstart_example.py

view raw JSON →