0
# Litestar
1
2
Litestar is a powerful, flexible yet opinionated ASGI web framework specifically focused on building high-performance APIs. It provides comprehensive features including high-performance data validation, dependency injection system, first-class ORM integration, authorization primitives, rich plugin API, and middleware support.
3
4
## Package Information
5
6
- **Package Name**: litestar
7
- **Language**: Python
8
- **Installation**: `pip install litestar`
9
10
## Core Imports
11
12
```python
13
from litestar import Litestar
14
```
15
16
For building applications:
17
18
```python
19
from litestar import Litestar, get, post, put, delete, patch
20
from litestar import Request, Response
21
from litestar import Controller, Router
22
```
23
24
## Basic Usage
25
26
```python
27
from litestar import Litestar, get
28
29
@get("/")
30
def hello_world() -> dict[str, str]:
31
return {"hello": "world"}
32
33
@get("/users/{user_id:int}")
34
def get_user(user_id: int) -> dict[str, int]:
35
return {"user_id": user_id}
36
37
app = Litestar(route_handlers=[hello_world, get_user])
38
39
# Run with uvicorn app:app
40
```
41
42
## Architecture
43
44
Litestar follows a layered architecture built on ASGI:
45
46
- **Application (Litestar)**: The main ASGI application that manages routing, middleware, and configuration
47
- **Routing**: Router and Controller classes organize route handlers with path prefixes and shared configuration
48
- **Handlers**: Route handler functions/methods decorated with HTTP method decorators (get, post, etc.)
49
- **Middleware**: Request/response processing pipeline with authentication, CORS, compression, etc.
50
- **Connection Objects**: Request and WebSocket objects provide access to ASGI scope, headers, body, etc.
51
- **Response Objects**: Structured response objects for different content types (JSON, files, templates, etc.)
52
- **Dependency Injection**: Powerful DI system for managing dependencies across handlers
53
- **Plugins**: Extensible plugin system for integrating with external libraries
54
55
## Capabilities
56
57
### Application and Routing
58
59
Core application setup, routing configuration, and request handling. Includes the main Litestar application class, routers for organizing routes, and controllers for OOP-style route organization.
60
61
```python { .api }
62
class Litestar:
63
def __init__(
64
self,
65
route_handlers: Sequence[ControllerRouterHandler] | None = None,
66
*,
67
middleware: Sequence[Middleware] | None = None,
68
dependencies: Dependencies | None = None,
69
exception_handlers: ExceptionHandlersMap | None = None,
70
# ... many more configuration options
71
): ...
72
73
class Router:
74
def __init__(
75
self,
76
path: str = "",
77
route_handlers: Sequence[ControllerRouterHandler] | None = None,
78
*,
79
dependencies: Dependencies | None = None,
80
middleware: Sequence[Middleware] | None = None,
81
# ... more options
82
): ...
83
84
class Controller:
85
path: str = ""
86
dependencies: Dependencies | None = None
87
middleware: Sequence[Middleware] | None = None
88
# ... controller configuration
89
```
90
91
[Application and Routing](./application-routing.md)
92
93
### HTTP Route Handlers
94
95
Decorators and classes for handling HTTP requests including GET, POST, PUT, DELETE, PATCH, and generic route handlers. Supports path parameters, query parameters, request body parsing, and response generation.
96
97
```python { .api }
98
def get(
99
path: str | Sequence[str] | None = None,
100
*,
101
dependencies: Dependencies | None = None,
102
middleware: Sequence[Middleware] | None = None,
103
name: str | None = None,
104
# ... more options
105
) -> Callable[[AnyCallable], HTTPRouteHandler]: ...
106
107
def post(path: str | Sequence[str] | None = None, **kwargs) -> Callable: ...
108
def put(path: str | Sequence[str] | None = None, **kwargs) -> Callable: ...
109
def patch(path: str | Sequence[str] | None = None, **kwargs) -> Callable: ...
110
def delete(path: str | Sequence[str] | None = None, **kwargs) -> Callable: ...
111
```
112
113
[HTTP Route Handlers](./http-handlers.md)
114
115
### Request and Response Objects
116
117
Connection objects for accessing request data including headers, body, query parameters, and path parameters. Response objects for returning different content types and status codes.
118
119
```python { .api }
120
class Request(ASGIConnection):
121
async def json(self) -> Any: ...
122
async def body(self) -> bytes: ...
123
async def form(self) -> dict[str, Any]: ...
124
def query_params(self) -> dict[str, Any]: ...
125
def path_params(self) -> dict[str, Any]: ...
126
def headers(self) -> Headers: ...
127
def cookies(self) -> dict[str, str]: ...
128
129
class Response:
130
def __init__(
131
self,
132
content: Any = None,
133
*,
134
status_code: int = 200,
135
headers: ResponseHeaders | None = None,
136
media_type: MediaType | str | None = None,
137
# ... more options
138
): ...
139
```
140
141
[Request and Response](./request-response.md)
142
143
### WebSocket Support
144
145
WebSocket connection handling with decorators for WebSocket routes, listeners, and streaming. Supports real-time bidirectional communication between client and server.
146
147
```python { .api }
148
def websocket(
149
path: str | Sequence[str] | None = None,
150
*,
151
dependencies: Dependencies | None = None,
152
middleware: Sequence[Middleware] | None = None,
153
# ... more options
154
) -> Callable: ...
155
156
def websocket_listener(
157
path: str | Sequence[str] | None = None,
158
**kwargs
159
) -> Callable: ...
160
161
class WebSocket(ASGIConnection):
162
async def accept(self, subprotocols: str | None = None) -> None: ...
163
async def send_text(self, data: str) -> None: ...
164
async def send_bytes(self, data: bytes) -> None: ...
165
async def send_json(self, data: Any) -> None: ...
166
async def receive_text(self) -> str: ...
167
async def receive_bytes(self) -> bytes: ...
168
async def receive_json(self) -> Any: ...
169
async def close(self, code: int = 1000, reason: str | None = None) -> None: ...
170
```
171
172
[WebSocket Support](./websocket.md)
173
174
### Middleware System
175
176
Middleware components for request/response processing including authentication, CORS, compression, rate limiting, and custom middleware. Supports both function-based and class-based middleware.
177
178
```python { .api }
179
class AbstractMiddleware:
180
def __init__(self, app: ASGIApp): ...
181
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: ...
182
183
def DefineMiddleware(
184
middleware: type[AbstractMiddleware] | Callable,
185
*args: Any,
186
**kwargs: Any,
187
) -> DefineMiddleware: ...
188
189
class AbstractAuthenticationMiddleware(AbstractMiddleware):
190
async def authenticate_request(self, connection: ASGIConnection) -> AuthenticationResult: ...
191
```
192
193
[Middleware](./middleware.md)
194
195
### Security and Authentication
196
197
Authentication and authorization systems including JWT authentication, session-based auth, and OAuth2 support. Provides security primitives for protecting routes and managing user sessions.
198
199
```python { .api }
200
class JWTAuth(BaseJWTAuth):
201
def __init__(
202
self,
203
token_secret: str,
204
retrieve_user_handler: UserHandlerProtocol,
205
*,
206
algorithm: str = "HS256",
207
auth_header: str = "Authorization",
208
# ... more options
209
): ...
210
211
class SessionAuth:
212
def __init__(
213
self,
214
retrieve_user_handler: UserHandlerProtocol,
215
session_backend: BaseSessionBackend,
216
*,
217
exclude: str | list[str] | None = None,
218
# ... more options
219
): ...
220
```
221
222
[Security and Authentication](./security.md)
223
224
### Data Transfer Objects (DTOs)
225
226
Serialization and validation system using DTOs for request/response data transformation. Supports dataclasses, Pydantic models, and msgspec structs with automatic validation and conversion.
227
228
```python { .api }
229
class AbstractDTO:
230
config: DTOConfig
231
232
class DataclassDTO(AbstractDTO):
233
@classmethod
234
def create_for_field_definition(
235
cls, field_definition: FieldDefinition, config: DTOConfig | None = None
236
) -> type[AbstractDTO]: ...
237
238
class DTOConfig:
239
def __init__(
240
self,
241
*,
242
exclude: set[str] | None = None,
243
include: set[str] | None = None,
244
rename_fields: dict[str, str] | None = None,
245
# ... more options
246
): ...
247
```
248
249
[Data Transfer Objects](./dto.md)
250
251
### Exception Handling
252
253
Framework-specific exceptions and error handling including HTTP exceptions, validation errors, and custom exception handlers. Provides structured error responses and debugging support.
254
255
```python { .api }
256
class HTTPException(Exception):
257
def __init__(
258
self,
259
detail: str = "",
260
*,
261
status_code: int = 500,
262
headers: dict[str, str] | None = None,
263
extra: dict[str, Any] | None = None,
264
): ...
265
266
class ValidationException(HTTPException): ...
267
class NotAuthorizedException(HTTPException): ...
268
class PermissionDeniedException(HTTPException): ...
269
class NotFoundException(HTTPException): ...
270
```
271
272
[Exception Handling](./exceptions.md)
273
274
### Testing Utilities
275
276
Test client implementations for testing Litestar applications. Includes synchronous and asynchronous test clients with support for HTTP requests, WebSocket connections, and integration testing.
277
278
```python { .api }
279
class TestClient:
280
def __init__(self, app: Litestar, **kwargs): ...
281
def get(self, url: str, **kwargs) -> httpx.Response: ...
282
def post(self, url: str, **kwargs) -> httpx.Response: ...
283
def put(self, url: str, **kwargs) -> httpx.Response: ...
284
def delete(self, url: str, **kwargs) -> httpx.Response: ...
285
286
class AsyncTestClient:
287
def __init__(self, app: Litestar, **kwargs): ...
288
async def get(self, url: str, **kwargs) -> httpx.Response: ...
289
async def post(self, url: str, **kwargs) -> httpx.Response: ...
290
```
291
292
[Testing](./testing.md)
293
294
### Configuration System
295
296
Configuration classes for various framework features including CORS, compression, static files, templates, and application settings. Provides type-safe configuration with validation.
297
298
```python { .api }
299
class CORSConfig:
300
def __init__(
301
self,
302
*,
303
allow_origins: Sequence[str] | None = None,
304
allow_methods: Sequence[str] | None = None,
305
allow_headers: Sequence[str] | None = None,
306
# ... more options
307
): ...
308
309
class CompressionConfig:
310
def __init__(
311
self,
312
backend: Literal["gzip", "brotli"] = "gzip",
313
minimum_size: int = 500,
314
# ... more options
315
): ...
316
```
317
318
[Configuration](./configuration.md)
319
320
### Plugin System
321
322
Extensible plugin architecture for integrating with external libraries and extending framework functionality. Includes core plugins and protocols for custom plugin development.
323
324
```python { .api }
325
class PluginProtocol(Protocol):
326
def on_app_init(self, app_config: AppConfig) -> AppConfig: ...
327
328
class SerializationPluginProtocol(PluginProtocol):
329
def supports_type(self, field_definition: FieldDefinition) -> bool: ...
330
def create_dto_for_type(self, field_definition: FieldDefinition) -> type[AbstractDTO]: ...
331
```
332
333
[Plugins](./plugins.md)
334
335
### OpenAPI Documentation
336
337
Automatic OpenAPI 3.1 specification generation with customizable documentation, schemas, and interactive API exploration. Supports custom response specifications and parameter documentation.
338
339
```python { .api }
340
class OpenAPIConfig:
341
def __init__(
342
self,
343
*,
344
title: str = "Litestar API",
345
version: str = "1.0.0",
346
description: str | None = None,
347
servers: list[Server] | None = None,
348
# ... more options
349
): ...
350
351
class OpenAPIController(Controller):
352
path: str = "/schema"
353
```
354
355
[OpenAPI Documentation](./openapi.md)
356
357
## Types
358
359
Core types used throughout the framework:
360
361
```python { .api }
362
# HTTP Methods
363
class HttpMethod(str, Enum):
364
GET = "GET"
365
POST = "POST"
366
PUT = "PUT"
367
PATCH = "PATCH"
368
DELETE = "DELETE"
369
HEAD = "HEAD"
370
OPTIONS = "OPTIONS"
371
TRACE = "TRACE"
372
373
# Media Types
374
class MediaType(str, Enum):
375
JSON = "application/json"
376
HTML = "text/html"
377
TEXT = "text/plain"
378
XML = "application/xml"
379
# ... more media types
380
381
# Handler types
382
ControllerRouterHandler = Controller | Router | BaseRouteHandler
383
Middleware = Callable | DefineMiddleware | type[AbstractMiddleware]
384
Dependencies = dict[str, Provide]
385
ExceptionHandlersMap = dict[type[Exception], ExceptionHandler]
386
```