0
# Routing System
1
2
Advanced routing capabilities with URI templates, path converters, static file serving, and high-performance compiled routing for building scalable web APIs.
3
4
## Capabilities
5
6
### Route Management
7
8
Core routing functionality for mapping URI patterns to resource handlers.
9
10
```python { .api }
11
# Route registration methods (part of App class)
12
def add_route(self, uri_template: str, resource: object, **kwargs):
13
"""
14
Add a route to the application.
15
16
Args:
17
uri_template: URI template with optional parameters (e.g., '/users/{user_id}')
18
resource: Resource object with HTTP method handlers
19
suffix: Optional route suffix for method-based routing
20
"""
21
22
def add_static_route(self, prefix: str, directory: str, **kwargs):
23
"""
24
Add a route for serving static files.
25
26
Args:
27
prefix: URI prefix for static files
28
directory: Directory path containing static files
29
downloadable: Set Content-Disposition header for downloads
30
fallback_filename: Fallback file for missing resources
31
"""
32
33
def add_sink(self, sink: callable, prefix: str = '/'):
34
"""
35
Add a sink function to handle unmatched routes.
36
37
Args:
38
sink: Callable that accepts (req, resp) parameters
39
prefix: URI prefix to match against
40
"""
41
```
42
43
#### Basic Routing Example
44
45
```python
46
import falcon
47
48
class UsersResource:
49
def on_get(self, req, resp, user_id=None):
50
if user_id:
51
resp.media = {'user_id': user_id}
52
else:
53
resp.media = {'users': []}
54
55
def on_post(self, req, resp):
56
resp.status = falcon.HTTP_201
57
resp.media = {'created': True}
58
59
class UserProfileResource:
60
def on_get(self, req, resp, user_id, profile_type='basic'):
61
resp.media = {
62
'user_id': user_id,
63
'profile_type': profile_type
64
}
65
66
app = falcon.App()
67
68
# Simple routes
69
app.add_route('/users', UsersResource())
70
app.add_route('/users/{user_id}', UsersResource())
71
72
# Route with optional parameter
73
app.add_route('/users/{user_id}/profile', UserProfileResource())
74
app.add_route('/users/{user_id}/profile/{profile_type}', UserProfileResource())
75
76
# Static file serving
77
app.add_static_route('/static', './public')
78
app.add_static_route('/downloads', './files', downloadable=True)
79
```
80
81
### Path Converters
82
83
Built-in converters for typed path parameters with automatic validation and conversion.
84
85
```python { .api }
86
class BaseConverter:
87
def convert(self, value: str) -> object:
88
"""
89
Convert string path segment to typed value.
90
91
Args:
92
value: Path segment string
93
94
Returns:
95
Converted value
96
97
Raises:
98
ValueError: If conversion fails
99
"""
100
101
class IntConverter(BaseConverter):
102
"""Convert path segments to integers"""
103
def convert(self, value: str) -> int: ...
104
105
class FloatConverter(BaseConverter):
106
"""Convert path segments to floats"""
107
def convert(self, value: str) -> float: ...
108
109
class DateTimeConverter(BaseConverter):
110
"""Convert path segments to datetime objects"""
111
def __init__(self, format_string: str = '%Y-%m-%dT%H:%M:%SZ'):
112
"""
113
Args:
114
format_string: strptime format string
115
"""
116
def convert(self, value: str) -> datetime: ...
117
118
class UUIDConverter(BaseConverter):
119
"""Convert path segments to UUID objects"""
120
def convert(self, value: str) -> UUID: ...
121
122
class PathConverter(BaseConverter):
123
"""Pass-through converter for path segments"""
124
def convert(self, value: str) -> str: ...
125
```
126
127
#### Path Converter Usage
128
129
```python
130
from uuid import UUID
131
from datetime import datetime
132
133
class OrderResource:
134
def on_get(self, req, resp, order_id: int, created_date: datetime):
135
# order_id is automatically converted to int
136
# created_date is automatically converted to datetime
137
order = get_order(order_id, created_date)
138
resp.media = order
139
140
class FileResource:
141
def on_get(self, req, resp, file_uuid: UUID):
142
# file_uuid is automatically converted to UUID
143
file_data = get_file(file_uuid)
144
resp.stream = file_data
145
146
# Route templates with converters
147
app.add_route('/orders/{order_id:int}', OrderResource())
148
app.add_route('/orders/{order_id:int}/date/{created_date:dt}', OrderResource())
149
app.add_route('/files/{file_uuid:uuid}', FileResource())
150
```
151
152
### Static File Serving
153
154
Built-in static file serving for both WSGI and ASGI applications.
155
156
```python { .api }
157
class StaticRoute:
158
def __init__(
159
self,
160
prefix: str,
161
directory: str,
162
downloadable: bool = False,
163
fallback_filename: str = None
164
):
165
"""
166
WSGI static file route.
167
168
Args:
169
prefix: URI prefix for static files
170
directory: Directory containing static files
171
downloadable: Set Content-Disposition header
172
fallback_filename: Fallback file for missing resources
173
"""
174
175
def __call__(self, req: Request, resp: Response): ...
176
177
class StaticRouteAsync:
178
def __init__(
179
self,
180
prefix: str,
181
directory: str,
182
downloadable: bool = False,
183
fallback_filename: str = None
184
):
185
"""
186
ASGI static file route.
187
188
Args: Same as StaticRoute
189
"""
190
191
async def __call__(self, req: Request, resp: Response): ...
192
```
193
194
#### Static File Examples
195
196
```python
197
# Basic static file serving
198
app.add_static_route('/static', './public')
199
200
# Downloadable files with Content-Disposition
201
app.add_static_route('/downloads', './files', downloadable=True)
202
203
# SPA fallback to index.html
204
app.add_static_route('/app', './dist', fallback_filename='index.html')
205
206
# Multiple static directories
207
app.add_static_route('/css', './assets/css')
208
app.add_static_route('/js', './assets/js')
209
app.add_static_route('/images', './assets/images')
210
```
211
212
### Advanced Routing
213
214
Sink functions and advanced routing patterns for complex applications.
215
216
```python { .api }
217
# Sink function signature
218
def sink_function(req: Request, resp: Response):
219
"""
220
Sink function for handling unmatched routes.
221
222
Args:
223
req: Request object
224
resp: Response object
225
"""
226
```
227
228
#### Sink Usage Examples
229
230
```python
231
def api_version_sink(req, resp):
232
"""Handle API versioning for unmatched routes"""
233
path_parts = req.path.strip('/').split('/')
234
235
if len(path_parts) >= 2 and path_parts[0] == 'api':
236
version = path_parts[1]
237
if version not in ['v1', 'v2']:
238
raise falcon.HTTPNotFound(
239
title='API version not supported',
240
description=f'Version {version} is not available'
241
)
242
243
# Continue processing
244
raise falcon.HTTPNotFound()
245
246
def catch_all_sink(req, resp):
247
"""Catch-all handler for unmatched routes"""
248
resp.status = falcon.HTTP_404
249
resp.media = {
250
'error': 'Not Found',
251
'path': req.path,
252
'method': req.method
253
}
254
255
# Register sinks
256
app.add_sink(api_version_sink, '/api')
257
app.add_sink(catch_all_sink) # Catch everything
258
```
259
260
### Routing Utilities
261
262
Utility functions for advanced routing scenarios.
263
264
```python { .api }
265
def map_http_methods(resource: object, **kwargs) -> dict:
266
"""
267
Map HTTP methods to resource responder methods.
268
269
Args:
270
resource: Resource object
271
**kwargs: Additional mapping options
272
273
Returns:
274
Dictionary mapping methods to responders
275
"""
276
277
def set_default_responders(resource: object, **kwargs):
278
"""
279
Set default responder methods on resource.
280
281
Args:
282
resource: Resource object to modify
283
**kwargs: Default responder options
284
"""
285
```
286
287
### Compiled Router
288
289
High-performance routing engine with compilation optimizations.
290
291
```python { .api }
292
class CompiledRouter:
293
def __init__(self, options: CompiledRouterOptions = None):
294
"""
295
High-performance compiled router.
296
297
Args:
298
options: Router configuration options
299
"""
300
301
def add_route(self, uri_template: str, method_map: dict, resource: object): ...
302
def find(self, uri: str, req: Request = None) -> tuple: ...
303
304
class CompiledRouterOptions:
305
def __init__(
306
self,
307
converters: dict = None,
308
strip_url_path_trailing_slash: bool = True
309
):
310
"""
311
Router configuration options.
312
313
Args:
314
converters: Custom path converters
315
strip_url_path_trailing_slash: Strip trailing slashes
316
"""
317
```
318
319
#### Custom Router Example
320
321
```python
322
from falcon.routing.converters import UUIDConverter, DateTimeConverter
323
324
# Custom router with specific converters
325
router_options = falcon.routing.CompiledRouterOptions(
326
converters={
327
'uuid': UUIDConverter(),
328
'timestamp': DateTimeConverter('%Y-%m-%d_%H:%M:%S')
329
}
330
)
331
332
router = falcon.routing.CompiledRouter(router_options)
333
334
# Create app with custom router
335
app = falcon.App(router=router)
336
```
337
338
## Types
339
340
```python { .api }
341
# Router types
342
CompiledRouter: type # High-performance router
343
CompiledRouterOptions: type # Router configuration
344
345
# Static route types
346
StaticRoute: type # WSGI static route
347
StaticRouteAsync: type # ASGI static route
348
349
# Converter types
350
BaseConverter: type # Base converter class
351
IntConverter: type # Integer converter
352
FloatConverter: type # Float converter
353
DateTimeConverter: type # DateTime converter
354
UUIDConverter: type # UUID converter
355
PathConverter: type # Path converter
356
```