0
# Application and Routing
1
2
Core application setup, routing configuration, and request handling. This module provides the foundation classes for building Litestar applications, organizing routes, and managing application lifecycle.
3
4
## Capabilities
5
6
### Litestar Application
7
8
The main ASGI application class that serves as the entry point for Litestar applications. Manages routing, middleware, dependencies, exception handling, and application configuration.
9
10
```python { .api }
11
class Litestar:
12
def __init__(
13
self,
14
route_handlers: Sequence[ControllerRouterHandler] | None = None,
15
*,
16
middleware: Sequence[Middleware] | None = None,
17
dependencies: Dependencies | None = None,
18
exception_handlers: ExceptionHandlersMap | None = None,
19
on_app_init: Sequence[OnAppInitHandler] | None = None,
20
listeners: Sequence[EventListener] | None = None,
21
lifespan: Sequence[Callable[[], AsyncContextManager | ContextManager]] | None = None,
22
after_exception: Sequence[AfterExceptionHookHandler] | None = None,
23
after_request: AfterRequestHookHandler | None = None,
24
after_response: AfterResponseHookHandler | None = None,
25
before_request: BeforeRequestHookHandler | None = None,
26
before_send: Sequence[BeforeMessageSendHookHandler] | None = None,
27
cors_config: CORSConfig | None = None,
28
csrf_config: CSRFConfig | None = None,
29
allowed_hosts: AllowedHostsConfig | None = None,
30
compression_config: CompressionConfig | None = None,
31
cache_config: CacheConfig | None = None,
32
etag: ETagConfig | None = None,
33
static_files_config: Sequence[StaticFilesConfig] | None = None,
34
template_config: TemplateConfig | None = None,
35
openapi_config: OpenAPIConfig | None = None,
36
logging_config: BaseLoggingConfig | None = None,
37
state: State | None = None,
38
debug: bool = False,
39
pdb_on_exception: bool = False,
40
plugins: Sequence[PluginProtocol] | None = None,
41
request_class: type[Request] | None = None,
42
response_class: type[Response] | None = None,
43
websocket_class: type[WebSocket] | None = None,
44
dto: type[AbstractDTO] | None = None,
45
return_dto: type[AbstractDTO] | None = None,
46
signature_namespace: dict[str, Any] | None = None,
47
type_encoders: TypeEncodersMap | None = None,
48
multipart_form_part_limit: int = 1000,
49
experimental_features: list[ExperimentalFeatures] | None = None,
50
):
51
"""
52
Create a Litestar application.
53
54
Parameters:
55
- route_handlers: A sequence containing Router, Controller, or route handler instances
56
- middleware: A sequence of Middleware to apply to the application
57
- dependencies: A dictionary of dependency providers
58
- exception_handlers: A dictionary mapping exception types to handlers
59
- on_app_init: A sequence of callables to invoke during application initialization
60
- listeners: A sequence of event listeners
61
- lifespan: A sequence of lifespan context managers
62
- after_exception: A sequence of hooks called after exceptions
63
- after_request: A hook called after processing requests
64
- after_response: A hook called after sending responses
65
- before_request: A hook called before processing requests
66
- before_send: A sequence of hooks called before sending responses
67
- cors_config: CORS configuration
68
- csrf_config: CSRF protection configuration
69
- allowed_hosts: Allowed hosts configuration
70
- compression_config: Response compression configuration
71
- cache_config: Response caching configuration
72
- etag: ETag configuration
73
- static_files_config: Static files serving configuration
74
- template_config: Template engine configuration
75
- openapi_config: OpenAPI documentation configuration
76
- logging_config: Logging configuration
77
- state: Application state
78
- debug: Enable debug mode
79
- pdb_on_exception: Drop into debugger on exceptions
80
- plugins: A sequence of plugin instances
81
- request_class: Custom Request class
82
- response_class: Custom Response class
83
- websocket_class: Custom WebSocket class
84
- dto: Default DTO for request/response serialization
85
- return_dto: Default DTO for response serialization
86
- signature_namespace: Additional namespace for signature inspection
87
- type_encoders: Custom type encoders
88
- multipart_form_part_limit: Limit for multipart form parts
89
- experimental_features: List of experimental features to enable
90
"""
91
92
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
93
"""ASGI application entry point."""
94
95
@property
96
def routes(self) -> list[ASGIRoute]:
97
"""Get all registered routes."""
98
99
@property
100
def route_map(self) -> dict[str, list[Route]]:
101
"""Get mapping of paths to routes."""
102
103
def url_for(self, name: str, **path_parameters: Any) -> str:
104
"""Generate URL for named route."""
105
106
def url_for_static_asset(self, name: str, file_path: str) -> str:
107
"""Generate URL for static asset."""
108
```
109
110
### Router
111
112
Organizes route handlers under a shared path prefix with common configuration. Routers can be nested to create hierarchical routing structures.
113
114
```python { .api }
115
class Router:
116
def __init__(
117
self,
118
path: str = "",
119
route_handlers: Sequence[ControllerRouterHandler] | None = None,
120
*,
121
dependencies: Dependencies | None = None,
122
middleware: Sequence[Middleware] | None = None,
123
exception_handlers: ExceptionHandlersMap | None = None,
124
after_request: AfterRequestHookHandler | None = None,
125
after_response: AfterResponseHookHandler | None = None,
126
before_request: BeforeRequestHookHandler | None = None,
127
dto: type[AbstractDTO] | None = None,
128
return_dto: type[AbstractDTO] | None = None,
129
signature_namespace: dict[str, Any] | None = None,
130
include_in_schema: bool = True,
131
tags: Sequence[str] | None = None,
132
guards: Sequence[Guard] | None = None,
133
opt: dict[str, Any] | None = None,
134
):
135
"""
136
Create a Router for organizing route handlers.
137
138
Parameters:
139
- path: Base path for all routes in this router
140
- route_handlers: Sequence of route handlers, controllers, or nested routers
141
- dependencies: Dictionary of dependency providers
142
- middleware: Sequence of middleware to apply
143
- exception_handlers: Exception handler mapping
144
- after_request: Hook called after request processing
145
- after_response: Hook called after response sending
146
- before_request: Hook called before request processing
147
- dto: Default DTO for request/response serialization
148
- return_dto: Default DTO for response serialization
149
- signature_namespace: Additional namespace for signature inspection
150
- include_in_schema: Whether to include routes in OpenAPI schema
151
- tags: OpenAPI tags for routes
152
- guards: Route guards for authorization
153
- opt: Arbitrary options dictionary
154
"""
155
156
@property
157
def routes(self) -> list[BaseRoute]:
158
"""Get all routes registered with this router."""
159
160
def register(self, handler: ControllerRouterHandler) -> None:
161
"""Register a route handler, controller, or router."""
162
```
163
164
### Controller
165
166
Base class for organizing related route handlers using object-oriented patterns. Controllers group related functionality with shared configuration and can inherit from other controllers.
167
168
```python { .api }
169
class Controller:
170
path: str = ""
171
dependencies: Dependencies | None = None
172
middleware: Sequence[Middleware] | None = None
173
exception_handlers: ExceptionHandlersMap | None = None
174
after_request: AfterRequestHookHandler | None = None
175
after_response: AfterResponseHookHandler | None = None
176
before_request: BeforeRequestHookHandler | None = None
177
dto: type[AbstractDTO] | None = None
178
return_dto: type[AbstractDTO] | None = None
179
signature_namespace: dict[str, Any] | None = None
180
include_in_schema: bool = True
181
tags: Sequence[str] | None = None
182
guards: Sequence[Guard] | None = None
183
opt: dict[str, Any] | None = None
184
185
def __init_subclass__(cls, **kwargs: Any) -> None:
186
"""Initialize controller subclass and register route handlers."""
187
188
@classmethod
189
def get_route_handlers(cls) -> list[BaseRouteHandler]:
190
"""Get all route handlers defined on this controller."""
191
```
192
193
### Route Registration
194
195
Utility functions for programmatic route registration and inspection.
196
197
```python { .api }
198
def create_route_handler(
199
handler_function: AnyCallable,
200
*,
201
http_method: HttpMethod | str,
202
path: str | None = None,
203
**kwargs: Any,
204
) -> HTTPRouteHandler:
205
"""Create a route handler from a function and HTTP method."""
206
207
def get_route_handlers(obj: Any) -> list[BaseRouteHandler]:
208
"""Extract route handlers from an object (controller, module, etc.)."""
209
```
210
211
## Usage Examples
212
213
### Basic Application Setup
214
215
```python
216
from litestar import Litestar, get
217
218
@get("/health")
219
def health_check() -> dict[str, str]:
220
return {"status": "healthy"}
221
222
app = Litestar(route_handlers=[health_check])
223
```
224
225
### Using Routers
226
227
```python
228
from litestar import Litestar, Router, get
229
230
@get("/users")
231
def list_users() -> list[dict]:
232
return [{"id": 1, "name": "Alice"}]
233
234
@get("/users/{user_id:int}")
235
def get_user(user_id: int) -> dict:
236
return {"id": user_id, "name": "Alice"}
237
238
# Group related routes under a router
239
api_router = Router(
240
path="/api/v1",
241
route_handlers=[list_users, get_user]
242
)
243
244
app = Litestar(route_handlers=[api_router])
245
```
246
247
### Controller-Based Organization
248
249
```python
250
from litestar import Controller, get, post
251
from litestar.dto import DataclassDTO
252
from dataclasses import dataclass
253
254
@dataclass
255
class User:
256
id: int
257
name: str
258
email: str
259
260
class UserController(Controller):
261
path = "/users"
262
tags = ["users"]
263
264
@get("/")
265
async def list_users(self) -> list[User]:
266
return [User(id=1, name="Alice", email="alice@example.com")]
267
268
@get("/{user_id:int}")
269
async def get_user(self, user_id: int) -> User:
270
return User(id=user_id, name="Alice", email="alice@example.com")
271
272
@post("/", dto=DataclassDTO[User])
273
async def create_user(self, data: User) -> User:
274
# Process user creation
275
return data
276
277
app = Litestar(route_handlers=[UserController])
278
```
279
280
### Nested Routing Structure
281
282
```python
283
from litestar import Litestar, Router, Controller, get
284
285
class UserController(Controller):
286
path = "/users"
287
288
@get("/")
289
def list_users(self) -> list[dict]:
290
return []
291
292
class AdminController(Controller):
293
path = "/admin"
294
295
@get("/dashboard")
296
def dashboard(self) -> dict:
297
return {"status": "admin"}
298
299
# Nest controllers under routers
300
api_v1 = Router(path="/api/v1", route_handlers=[UserController])
301
admin_router = Router(path="/admin", route_handlers=[AdminController])
302
303
app = Litestar(route_handlers=[api_v1, admin_router])
304
# Creates routes: /api/v1/users, /admin/admin/dashboard
305
```
306
307
## Types
308
309
```python { .api }
310
# Type aliases for route handlers
311
ControllerRouterHandler = Controller | Router | BaseRouteHandler
312
313
# Dependency injection types
314
Dependencies = dict[str, Provide]
315
316
# Hook handler types
317
OnAppInitHandler = Callable[[AppConfig], AppConfig]
318
AfterRequestHookHandler = Callable[[Request], None]
319
AfterResponseHookHandler = Callable[[Request, Response], None]
320
BeforeRequestHookHandler = Callable[[Request], None]
321
BeforeMessageSendHookHandler = Callable[[Message, Scope], None]
322
AfterExceptionHookHandler = Callable[[Request, Exception], None]
323
324
# Exception handling
325
ExceptionHandlersMap = dict[type[Exception], ExceptionHandler]
326
ExceptionHandler = Callable[[Request, Exception], Response]
327
328
# Middleware
329
Middleware = Callable | DefineMiddleware | type[AbstractMiddleware]
330
```