or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication-permissions.mdexceptions-status.mdfields-relations.mdindex.mdpagination-filtering.mdrequests-responses.mdrouters-urls.mdserializers.mdviews-viewsets.md

index.mddocs/

0

# Django REST Framework Stubs

1

2

Django REST Framework Stubs provides comprehensive type definitions for Django REST Framework (DRF), enabling full type checking support for DRF applications without requiring access to the source code. This package includes PEP 484 type stubs for all major DRF components plus a mypy plugin for enhanced static analysis.

3

4

## Package Information

5

6

**Package Name**: `djangorestframework-stubs`

7

**Version**: 3.16.2

8

**Language**: Python

9

**Purpose**: PEP 484 type stubs for Django REST Framework

10

**Python Support**: 3.10+

11

**Installation**: `pip install djangorestframework-stubs[compatible-mypy]`

12

13

## Quick Start

14

15

### Installation and Configuration

16

17

Install the package with mypy support:

18

19

```bash

20

pip install djangorestframework-stubs[compatible-mypy]

21

```

22

23

Configure mypy in `mypy.ini`:

24

25

```ini

26

[mypy]

27

plugins = mypy_drf_plugin.main

28

```

29

30

### Basic Usage Example

31

32

```python

33

from rest_framework import serializers, views, generics

34

from rest_framework.decorators import api_view

35

from rest_framework.response import Response

36

from rest_framework.permissions import IsAuthenticated

37

from rest_framework import status

38

from django.contrib.auth.models import User

39

from myapp.models import Book

40

41

# Typed serializer with automatic field inference

42

class BookSerializer(serializers.ModelSerializer[Book]):

43

class Meta:

44

model = Book

45

fields = ['id', 'title', 'author', 'published_date']

46

47

# Typed API view with proper request/response types

48

class BookListCreateView(generics.ListCreateAPIView[Book]):

49

queryset = Book.objects.all()

50

serializer_class = BookSerializer

51

permission_classes = [IsAuthenticated]

52

53

# Typed function-based view

54

@api_view(['GET', 'POST'])

55

def book_list(request) -> Response:

56

if request.method == 'GET':

57

books = Book.objects.all()

58

serializer = BookSerializer(books, many=True)

59

return Response(serializer.data)

60

61

elif request.method == 'POST':

62

serializer = BookSerializer(data=request.data)

63

if serializer.is_valid():

64

serializer.save()

65

return Response(serializer.data, status=status.HTTP_201_CREATED)

66

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

67

```

68

69

## Core Imports

70

71

```python { .api }

72

# Essential DRF components

73

from rest_framework import serializers

74

from rest_framework import views

75

from rest_framework import generics

76

from rest_framework import viewsets

77

from rest_framework import mixins

78

from rest_framework.decorators import api_view, permission_classes

79

from rest_framework.response import Response

80

from rest_framework.request import Request

81

from rest_framework import status

82

from rest_framework import permissions

83

from rest_framework import authentication

84

from rest_framework.routers import DefaultRouter

85

from rest_framework import exceptions

86

```

87

88

## Architecture

89

90

### Type Stub Structure

91

92

The package provides type stubs in the `rest_framework-stubs/` directory that mirror the actual DRF package structure:

93

94

- **Core modules**: `serializers.pyi`, `views.pyi`, `generics.pyi`, `viewsets.pyi`

95

- **Authentication**: `authentication.pyi`, `permissions.pyi`

96

- **Data handling**: `fields.pyi`, `relations.pyi`, `parsers.pyi`, `renderers.pyi`

97

- **Utilities**: `routers.pyi`, `decorators.pyi`, `pagination.pyi`, `filters.pyi`

98

- **Subpackages**: `authtoken/`, `schemas/`, `utils/`

99

100

### Mypy Plugin Enhancement

101

102

The `mypy_drf_plugin` provides additional type checking capabilities:

103

104

```python { .api }

105

# Plugin configuration in mypy.ini

106

[mypy]

107

plugins = mypy_drf_plugin.main

108

109

# Enhanced typing for serializers

110

class UserSerializer(serializers.ModelSerializer[User]):

111

class Meta:

112

model = User

113

fields = '__all__'

114

115

# Plugin automatically infers field types from model

116

# and provides enhanced validation

117

```

118

119

## Key Capabilities

120

121

### Serializer Type Safety

122

123

Complete type definitions for all serializer types with generic support:

124

125

```python { .api }

126

# Generic serializer with type parameters

127

class BaseSerializer(Field[_VT, _DT, _RP, _IN]):

128

partial: bool

129

many: bool

130

instance: _IN | None

131

132

def is_valid(*, raise_exception: bool = False) -> bool: ...

133

def save(**kwargs: Any) -> _IN: ...

134

def create(validated_data: Any) -> _IN: ...

135

def update(instance: _IN, validated_data: Any) -> _IN: ...

136

137

# Model serializer with model type binding

138

class ModelSerializer(Serializer[_MT]):

139

class Meta:

140

model: type[_MT]

141

fields: str | Sequence[str]

142

exclude: Sequence[str] | None

143

```

144

145

**[→ Complete Serializer Documentation](serializers.md)**

146

147

### View and ViewSet Types

148

149

Comprehensive typing for all view classes and mixins:

150

151

```python { .api }

152

# Generic API view with model type support

153

class GenericAPIView(APIView, Generic[_MT]):

154

queryset: QuerySet[_MT] | Manager[_MT] | None

155

serializer_class: type[BaseSerializer[_MT]] | None

156

157

def get_object() -> _MT: ...

158

def get_serializer() -> BaseSerializer[_MT]: ...

159

160

# ViewSet with proper action typing

161

class ModelViewSet(mixins.CreateModelMixin,

162

mixins.RetrieveModelMixin,

163

mixins.UpdateModelMixin,

164

mixins.DestroyModelMixin,

165

mixins.ListModelMixin,

166

GenericViewSet[_MT]): ...

167

```

168

169

**[→ Complete Views & ViewSets Documentation](views-viewsets.md)**

170

171

### Authentication & Permissions

172

173

Type-safe authentication and permission classes:

174

175

```python { .api }

176

# Base authentication interface

177

class BaseAuthentication:

178

def authenticate(request: Request) -> tuple[Any, Any] | None: ...

179

def authenticate_header(request: Request) -> str | None: ...

180

181

# Permission system with logical operators

182

class BasePermission:

183

def has_permission(request: Request, view: APIView) -> bool: ...

184

def has_object_permission(request: Request, view: APIView, obj: Any) -> bool: ...

185

186

# Permission composition

187

permission_classes = [IsAuthenticated & (IsOwner | IsAdmin)]

188

```

189

190

**[→ Complete Authentication & Permissions Documentation](authentication-permissions.md)**

191

192

### Request & Response Handling

193

194

Typed request and response objects:

195

196

```python { .api }

197

# Enhanced request object

198

class Request(HttpRequest):

199

data: dict[str, Any]

200

query_params: QueryDict

201

user: AbstractUser | AnonymousUser

202

auth: Any

203

204

# Typed response

205

class Response(SimpleTemplateResponse):

206

data: Any

207

status_code: int

208

exception: bool

209

```

210

211

**[→ Complete Request & Response Documentation](requests-responses.md)**

212

213

### Field Types & Relations

214

215

Complete field type system with generic support:

216

217

```python { .api }

218

# Generic field base class

219

class Field(Generic[_VT, _DT, _RP, _IN]):

220

required: bool

221

allow_null: bool

222

default: Any

223

224

# Specific field types

225

class CharField(Field[str, str, str, Any]): ...

226

class IntegerField(Field[int, int | str, int, Any]): ...

227

class DateTimeField(Field[datetime, datetime | str, str, Any]): ...

228

229

# Relational fields

230

class PrimaryKeyRelatedField(RelatedField[_MT, _MT, Any]): ...

231

class HyperlinkedRelatedField(RelatedField[_MT, str, Hyperlink]): ...

232

```

233

234

**[→ Complete Fields & Relations Documentation](fields-relations.md)**

235

236

### Routing & URL Configuration

237

238

Type-safe router and URL pattern configuration:

239

240

```python { .api }

241

# Router with viewset registration

242

class DefaultRouter(BaseRouter):

243

def register(prefix: str, viewset: type[ViewSetMixin], basename: str | None = None) -> None: ...

244

def get_urls() -> list[URLPattern]: ...

245

246

# Route configuration

247

class Route(NamedTuple):

248

url: str

249

mapping: dict[str, str]

250

name: str

251

detail: bool

252

```

253

254

**[→ Complete Routing & URLs Documentation](routers-urls.md)**

255

256

### Pagination & Filtering

257

258

Typed pagination and filtering systems:

259

260

```python { .api }

261

# Pagination base class

262

class BasePagination:

263

def paginate_queryset(queryset: QuerySet[_MT], request: Request, view: APIView | None = None) -> list[_MT] | None: ...

264

def get_paginated_response(data: Any) -> Response: ...

265

266

# Filter backends

267

class BaseFilterBackend:

268

def filter_queryset(request: Request, queryset: QuerySet[_MT], view: APIView) -> QuerySet[_MT]: ...

269

```

270

271

**[→ Complete Pagination & Filtering Documentation](pagination-filtering.md)**

272

273

### Exception Handling

274

275

Comprehensive exception types with proper error detail handling:

276

277

```python { .api }

278

# Base API exception

279

class APIException(Exception):

280

status_code: int

281

default_detail: str | dict | list

282

default_code: str

283

detail: Any

284

285

def get_codes() -> dict | list | str: ...

286

def get_full_details() -> dict | list: ...

287

288

# Specific exception types

289

class ValidationError(APIException): ...

290

class NotFound(APIException): ...

291

class PermissionDenied(APIException): ...

292

```

293

294

**[→ Complete Exception & Status Documentation](exceptions-status.md)**

295

296

## Type Checking Benefits

297

298

This type stub package enables:

299

300

- **Static Type Checking**: Catch type errors before runtime using mypy

301

- **IDE Intelligence**: Enhanced autocomplete, refactoring, and error detection

302

- **Documentation**: Self-documenting code with precise type annotations

303

- **Refactoring Safety**: Confident code changes with type-guided refactoring

304

- **API Contract Validation**: Ensure API consistency across your application

305

306

## Mypy Plugin Features

307

308

The included mypy plugin (`mypy_drf_plugin.main`) provides:

309

310

- **Automatic Field Inference**: ModelSerializer fields automatically typed from Django models

311

- **Enhanced Validation**: Additional type checking for DRF-specific patterns

312

- **Meta Class Support**: Proper typing for serializer Meta classes

313

- **Generic Support**: Full generic type support for serializers and views

314

315

## Documentation Structure

316

317

- **[Serializers](serializers.md)** - Serializer classes, fields, and validation

318

- **[Views & ViewSets](views-viewsets.md)** - API views, viewsets, and mixins

319

- **[Authentication & Permissions](authentication-permissions.md)** - Security and access control

320

- **[Requests & Responses](requests-responses.md)** - Request handling and response formatting

321

- **[Fields & Relations](fields-relations.md)** - Field types and model relationships

322

- **[Routers & URLs](routers-urls.md)** - URL routing and pattern configuration

323

- **[Pagination & Filtering](pagination-filtering.md)** - Data pagination and filtering

324

- **[Exceptions & Status](exceptions-status.md)** - Error handling and HTTP status codes

325

326

## Integration Example

327

328

Complete example showing type-safe DRF development:

329

330

```python

331

from django.contrib.auth.models import User

332

from rest_framework import serializers, viewsets, permissions

333

from rest_framework.decorators import action

334

from rest_framework.response import Response

335

from myapp.models import Article

336

337

class ArticleSerializer(serializers.ModelSerializer[Article]):

338

author_name = serializers.CharField(source='author.username', read_only=True)

339

340

class Meta:

341

model = Article

342

fields = ['id', 'title', 'content', 'author', 'author_name', 'created_at']

343

read_only_fields = ['author', 'created_at']

344

345

def create(self, validated_data: dict) -> Article:

346

validated_data['author'] = self.context['request'].user

347

return super().create(validated_data)

348

349

class ArticleViewSet(viewsets.ModelViewSet[Article]):

350

queryset = Article.objects.all()

351

serializer_class = ArticleSerializer

352

permission_classes = [permissions.IsAuthenticatedOrReadOnly]

353

354

@action(detail=True, methods=['post'], permission_classes=[permissions.IsAuthenticated])

355

def favorite(self, request, pk: str | None = None) -> Response:

356

article = self.get_object()

357

# Type-safe operations with proper return type

358

article.favorites.add(request.user)

359

return Response({'status': 'favorite added'})

360

```

361

362

This example demonstrates how the type stubs enable full type safety across serializers, views, permissions, and custom actions while maintaining DRF's flexibility and power.