0
# Application Framework
1
2
Core WSGI and ASGI application classes that serve as the foundation for building Falcon web APIs. These classes handle request routing, middleware processing, and application-level configuration.
3
4
## Capabilities
5
6
### WSGI Application
7
8
The main WSGI application class that serves as the entry point for traditional synchronous web applications.
9
10
```python { .api }
11
class App:
12
def __init__(
13
self,
14
media_type: str = 'application/json',
15
request_type: type = None,
16
response_type: type = None,
17
middleware: object = None,
18
router: object = None,
19
independent_middleware: bool = True,
20
cors_enable: bool = False,
21
sink_before_static_route: bool = True
22
):
23
"""
24
Create a WSGI application.
25
26
Args:
27
media_type: Default media type for responses
28
request_type: Custom Request class to use (default: falcon.Request)
29
response_type: Custom Response class to use (default: falcon.Response)
30
middleware: Single middleware component or iterable of components
31
router: Custom router instance (default: CompiledRouter)
32
independent_middleware: Process middleware independently
33
cors_enable: Enable built-in CORS middleware
34
sink_before_static_route: Process sinks before static routes
35
"""
36
37
def __call__(self, env: dict, start_response: callable):
38
"""
39
WSGI callable interface.
40
41
Args:
42
env: WSGI environment dictionary
43
start_response: WSGI start_response callable
44
45
Returns:
46
Iterable of response body bytes
47
"""
48
49
def add_route(self, uri_template: str, resource: object, **kwargs):
50
"""
51
Add a route to the application.
52
53
Args:
54
uri_template: URI template with optional parameters (e.g., '/users/{user_id}')
55
resource: Resource object with HTTP method handlers
56
suffix: Optional route suffix for method-based routing
57
"""
58
59
def add_static_route(self, prefix: str, directory: str, **kwargs):
60
"""
61
Add a route for serving static files.
62
63
Args:
64
prefix: URI prefix for static files
65
directory: Directory path containing static files
66
downloadable: Set Content-Disposition header for downloads
67
fallback_filename: Fallback file for missing resources
68
"""
69
70
def add_sink(self, sink: callable, prefix: str = '/'):
71
"""
72
Add a sink function to handle unmatched routes.
73
74
Args:
75
sink: Callable that accepts (req, resp) parameters
76
prefix: URI prefix to match against
77
"""
78
79
def add_middleware(self, middleware: object):
80
"""
81
Add middleware component to the application.
82
83
Args:
84
middleware: Middleware object with process_request/process_response methods
85
"""
86
87
def add_error_handler(self, exception_type: type, handler: callable):
88
"""
89
Register custom error handler for specific exception types.
90
91
Args:
92
exception_type: Exception class to handle
93
handler: Function that accepts (req, resp, ex, params)
94
"""
95
96
def set_error_serializer(self, serializer: callable):
97
"""
98
Set custom error serialization function.
99
100
Args:
101
serializer: Function that serializes HTTPError to response media
102
"""
103
104
# Properties
105
req_options: RequestOptions # Request processing options (instance attribute)
106
resp_options: ResponseOptions # Response processing options (instance attribute)
107
router_options: object # Router configuration options
108
```
109
110
#### Usage Example
111
112
```python
113
import falcon
114
115
class HealthCheckResource:
116
def on_get(self, req, resp):
117
resp.media = {'status': 'healthy'}
118
119
class UsersResource:
120
def on_get(self, req, resp, user_id=None):
121
if user_id:
122
resp.media = {'user_id': user_id}
123
else:
124
resp.media = {'users': []}
125
126
def on_post(self, req, resp):
127
user_data = req.media
128
# Process user creation
129
resp.status = falcon.HTTP_201
130
resp.media = {'created': True}
131
132
# Create application
133
app = falcon.App(
134
cors_enable=True,
135
media_type='application/json'
136
)
137
138
# Add routes
139
app.add_route('/health', HealthCheckResource())
140
app.add_route('/users', UsersResource())
141
app.add_route('/users/{user_id}', UsersResource())
142
143
# Add static file serving
144
app.add_static_route('/static', './public')
145
146
# Custom error handling
147
def handle_validation_error(req, resp, ex, params):
148
resp.status = falcon.HTTP_400
149
resp.media = {'error': 'Validation failed', 'details': str(ex)}
150
151
app.add_error_handler(ValueError, handle_validation_error)
152
```
153
154
### ASGI Application
155
156
The ASGI application class for building modern asynchronous web applications with WebSocket support.
157
158
```python { .api }
159
class falcon.asgi.App:
160
def __init__(
161
self,
162
media_type: str = 'application/json',
163
request_type: type = None,
164
response_type: type = None,
165
middleware: list = None,
166
router: object = None,
167
cors_enable: bool = False,
168
req_options: RequestOptions = None,
169
resp_options: ResponseOptions = None,
170
secure_cookies_by_default: bool = None
171
):
172
"""
173
Create an ASGI application.
174
175
Args: Same as WSGI App constructor
176
"""
177
178
async def __call__(self, scope: dict, receive: callable, send: callable):
179
"""
180
ASGI callable interface.
181
182
Args:
183
scope: ASGI scope dictionary
184
receive: ASGI receive callable
185
send: ASGI send callable
186
"""
187
188
# Same methods as WSGI App:
189
# add_route, add_static_route, add_sink, add_middleware,
190
# add_error_handler, set_error_serializer
191
```
192
193
#### ASGI Usage Example
194
195
```python
196
import falcon.asgi
197
198
class AsyncUsersResource:
199
async def on_get(self, req, resp, user_id=None):
200
# Async database operation
201
if user_id:
202
user = await fetch_user(user_id)
203
resp.media = user
204
else:
205
users = await fetch_all_users()
206
resp.media = {'users': users}
207
208
async def on_post(self, req, resp):
209
user_data = req.media
210
new_user = await create_user(user_data)
211
resp.status = falcon.HTTP_201
212
resp.media = new_user
213
214
class WebSocketResource:
215
async def on_websocket(self, req, ws):
216
await ws.accept()
217
while True:
218
try:
219
message = await ws.receive_text()
220
await ws.send_text(f"Echo: {message}")
221
except falcon.WebSocketDisconnected:
222
break
223
224
# Create ASGI application
225
app = falcon.asgi.App()
226
227
# Add routes
228
app.add_route('/users', AsyncUsersResource())
229
app.add_route('/users/{user_id}', AsyncUsersResource())
230
app.add_route('/ws', WebSocketResource())
231
```
232
233
### Application Configuration Options
234
235
Configuration classes for customizing request and response processing behavior.
236
237
```python { .api }
238
class RequestOptions:
239
def __init__(
240
self,
241
auto_parse_form_urlencoded: bool = True,
242
auto_parse_qs_csv: bool = True,
243
default_media_type: str = 'application/json',
244
media_handlers: object = None,
245
strip_url_path_trailing_slash: bool = True
246
):
247
"""
248
Request processing configuration.
249
250
Args:
251
auto_parse_form_urlencoded: Auto-parse URL-encoded form data
252
auto_parse_qs_csv: Parse comma-separated query parameters
253
default_media_type: Default request media type
254
media_handlers: Custom media handler registry
255
strip_url_path_trailing_slash: Strip trailing slashes from paths
256
"""
257
258
class ResponseOptions:
259
def __init__(
260
self,
261
default_media_type: str = 'application/json',
262
media_handlers: object = None,
263
secure_cookies_by_default: bool = None,
264
static_media_types: dict = None
265
):
266
"""
267
Response processing configuration.
268
269
Args:
270
default_media_type: Default response media type
271
media_handlers: Custom media handler registry
272
secure_cookies_by_default: Set secure flag on cookies
273
static_media_types: Media type mappings for static files
274
"""
275
```
276
277
#### Configuration Example
278
279
```python
280
import falcon
281
282
# Create app first
283
app = falcon.App(cors_enable=True)
284
285
# Configure request/response options after creation
286
app.req_options.auto_parse_form_urlencoded = True
287
app.req_options.strip_url_path_trailing_slash = False
288
289
app.resp_options.secure_cookies_by_default = True
290
app.resp_options.default_media_type = 'application/json'
291
292
# Or create custom options and assign them
293
req_options = falcon.RequestOptions(
294
auto_parse_form_urlencoded=True,
295
strip_url_path_trailing_slash=False
296
)
297
app.req_options = req_options
298
```
299
300
## Types
301
302
```python { .api }
303
# Application types are the main App classes themselves
304
App: type # WSGI application class
305
falcon.asgi.App: type # ASGI application class
306
307
# Configuration option types
308
RequestOptions: type
309
ResponseOptions: type
310
```