0
# Falcon
1
2
A minimalist Python web framework specifically designed for building high-performance REST APIs and microservices at scale. Falcon supports both ASGI and WSGI protocols, making it suitable for modern asynchronous applications as well as traditional synchronous web services.
3
4
## Package Information
5
6
- **Package Name**: falcon
7
- **Language**: Python
8
- **Installation**: `pip install falcon`
9
10
## Core Imports
11
12
```python
13
import falcon
14
```
15
16
For ASGI applications:
17
18
```python
19
import falcon.asgi
20
```
21
22
## Basic Usage
23
24
```python
25
import falcon
26
27
class ThingsResource:
28
def on_get(self, req, resp):
29
"""Handles GET requests"""
30
resp.status = falcon.HTTP_200
31
resp.content_type = falcon.MEDIA_JSON
32
resp.media = {'message': 'Hello, World!'}
33
34
def on_post(self, req, resp):
35
"""Handles POST requests"""
36
try:
37
data = req.media
38
# Process the data
39
resp.status = falcon.HTTP_201
40
resp.media = {'created': True, 'data': data}
41
except Exception as e:
42
raise falcon.HTTPBadRequest(
43
title='Invalid request',
44
description=str(e)
45
)
46
47
# Create WSGI application
48
app = falcon.App()
49
app.add_route('/things', ThingsResource())
50
51
# Or create ASGI application
52
# app = falcon.asgi.App()
53
# app.add_route('/things', ThingsResource())
54
```
55
56
## Architecture
57
58
Falcon's architecture emphasizes performance and simplicity:
59
60
- **App**: Central WSGI/ASGI application that routes requests to resources
61
- **Resources**: Classes that handle HTTP methods (on_get, on_post, etc.)
62
- **Request/Response**: Objects representing HTTP request and response
63
- **Middleware**: Components for cross-cutting concerns (authentication, CORS, etc.)
64
- **Routing**: Fast compiled routing system with URI templates and converters
65
- **Media Handlers**: Pluggable serialization for JSON, MessagePack, multipart forms
66
- **Error Handling**: Comprehensive HTTP exception hierarchy
67
68
This design provides minimal abstractions over HTTP while maintaining excellent performance, making it ideal for building data plane APIs and microservices.
69
70
## Capabilities
71
72
### Application Framework
73
74
Core WSGI and ASGI application classes for building web APIs, with routing, middleware support, and comprehensive configuration options.
75
76
```python { .api }
77
class App:
78
def __init__(
79
self,
80
media_type: str = 'application/json',
81
request_type: type = None,
82
response_type: type = None,
83
middleware: object = None,
84
router: object = None,
85
independent_middleware: bool = True,
86
cors_enable: bool = False,
87
sink_before_static_route: bool = True
88
): ...
89
90
def add_route(self, uri_template: str, resource: object, **kwargs): ...
91
def add_static_route(self, prefix: str, directory: str, **kwargs): ...
92
def add_sink(self, sink: callable, prefix: str = '/'): ...
93
def add_middleware(self, middleware: object): ...
94
def add_error_handler(self, exception_type: type, handler: callable): ...
95
```
96
97
```python { .api }
98
# ASGI Application
99
class falcon.asgi.App:
100
def __init__(self, **kwargs): ...
101
# Same methods as WSGI App
102
```
103
104
[Application Framework](./application.md)
105
106
### Request and Response Handling
107
108
Comprehensive HTTP request and response objects with extensive properties and methods for headers, parameters, media processing, and content negotiation.
109
110
```python { .api }
111
class Request:
112
# Core properties
113
method: str
114
uri: str
115
relative_uri: str
116
headers: dict
117
params: dict
118
cookies: dict
119
media: object # Parsed request body
120
context: object # User data storage
121
122
# Methods
123
def get_header(self, name: str, default: str = None) -> str: ...
124
def get_param(self, name: str, default: str = None) -> str: ...
125
def client_accepts_json(self) -> bool: ...
126
def client_accepts_msgpack(self) -> bool: ...
127
```
128
129
```python { .api }
130
class Response:
131
# Core properties
132
status: str
133
headers: dict
134
media: object # Auto-serialized response data
135
data: bytes # Raw response body
136
content_type: str
137
context: object
138
139
# Methods
140
def set_header(self, name: str, value: str): ...
141
def set_cookie(self, name: str, value: str, **kwargs): ...
142
def set_stream(self, stream: object, content_length: int, content_type: str = None): ...
143
```
144
145
[Request and Response Handling](./request-response.md)
146
147
### Error Handling
148
149
Comprehensive HTTP exception hierarchy and error handling mechanisms for building robust APIs with proper status codes and error responses.
150
151
```python { .api }
152
class HTTPError(Exception):
153
def __init__(
154
self,
155
status: str,
156
title: str = None,
157
description: str = None,
158
headers: dict = None,
159
href: str = None,
160
href_text: str = None,
161
code: int = None
162
): ...
163
164
def to_dict(self) -> dict: ...
165
def to_json(self) -> str: ...
166
167
# Common HTTP exceptions
168
class HTTPBadRequest(HTTPError): ...
169
class HTTPUnauthorized(HTTPError): ...
170
class HTTPForbidden(HTTPError): ...
171
class HTTPNotFound(HTTPError): ...
172
class HTTPMethodNotAllowed(HTTPError): ...
173
class HTTPInternalServerError(HTTPError): ...
174
```
175
176
[Error Handling](./error-handling.md)
177
178
### Routing System
179
180
Advanced routing capabilities with URI templates, path converters, static file serving, and high-performance compiled routing.
181
182
```python { .api }
183
# Route converters for path parameters
184
class IntConverter: ...
185
class FloatConverter: ...
186
class DateTimeConverter: ...
187
class UUIDConverter: ...
188
class PathConverter: ...
189
190
# Static file serving
191
class StaticRoute:
192
def __init__(self, prefix: str, directory: str, **kwargs): ...
193
194
class StaticRouteAsync: # ASGI version
195
def __init__(self, prefix: str, directory: str, **kwargs): ...
196
```
197
198
[Routing System](./routing.md)
199
200
### ASGI and WebSocket Support
201
202
Modern asynchronous application support with WebSocket handling, Server-Sent Events, and full ASGI 3.0 compatibility.
203
204
```python { .api }
205
class WebSocket:
206
# Properties
207
ready_state: int
208
client_address: tuple
209
context: object
210
211
# Methods
212
async def accept(self, subprotocol: str = None, headers: dict = None): ...
213
async def receive_text(self) -> str: ...
214
async def receive_data(self) -> bytes: ...
215
async def send_text(self, payload: str): ...
216
async def send_data(self, payload: bytes): ...
217
async def close(self, code: int = 1000, reason: str = None): ...
218
219
class SSEvent:
220
def __init__(self, data: str, event_type: str = None, event_id: str = None, retry: int = None): ...
221
```
222
223
[ASGI and WebSocket Support](./asgi-websocket.md)
224
225
### Media Processing
226
227
Pluggable media handling system supporting JSON, MessagePack, multipart forms, URL-encoded data, and custom media types.
228
229
```python { .api }
230
class BaseHandler:
231
def serialize(self, media: object, content_type: str) -> bytes: ...
232
def deserialize(self, stream: object, content_type: str, content_length: int) -> object: ...
233
234
class JSONHandler(BaseHandler): ...
235
class MessagePackHandler(BaseHandler): ...
236
class MultipartFormHandler(BaseHandler): ...
237
class URLEncodedFormHandler(BaseHandler): ...
238
239
class Handlers:
240
def __init__(self, initial: dict = None): ...
241
def find_by_media_type(self, media_type: str, default: object = None) -> BaseHandler: ...
242
```
243
244
[Media Processing](./media.md)
245
246
### Testing Framework
247
248
Comprehensive testing utilities with request simulation, ASGI testing support, and mock objects for building robust test suites.
249
250
```python { .api }
251
class TestClient:
252
def __init__(self, app: object, headers: dict = None): ...
253
254
def simulate_get(self, path: str, **kwargs) -> Result: ...
255
def simulate_post(self, path: str, **kwargs) -> Result: ...
256
def simulate_put(self, path: str, **kwargs) -> Result: ...
257
def simulate_delete(self, path: str, **kwargs) -> Result: ...
258
259
class Result:
260
status: str
261
headers: dict
262
text: str
263
json: object
264
cookies: list
265
```
266
267
[Testing Framework](./testing.md)
268
269
### Middleware and Hooks
270
271
Middleware system for cross-cutting concerns and hook decorators for before/after request processing.
272
273
```python { .api }
274
class CORSMiddleware:
275
def __init__(
276
self,
277
allow_origins: str = '*',
278
expose_headers: list = None,
279
allow_credentials: bool = None,
280
allow_private_network: bool = False
281
): ...
282
283
# Hook decorators
284
def before(action: callable, *args, **kwargs): ...
285
def after(action: callable, *args, **kwargs): ...
286
```
287
288
[Middleware and Hooks](./middleware-hooks.md)
289
290
### Utilities
291
292
Extensive utility functions for HTTP dates, URI handling, async/sync conversion, data structures, and common web development tasks.
293
294
```python { .api }
295
# HTTP utilities
296
def http_now() -> str: ...
297
def http_date_to_dt(http_date: str) -> datetime: ...
298
def dt_to_http(dt: datetime) -> str: ...
299
def secure_filename(filename: str) -> str: ...
300
301
# Async utilities
302
def async_to_sync(coroutine_func: callable) -> callable: ...
303
def sync_to_async(sync_func: callable) -> callable: ...
304
305
# Data structures
306
class CaseInsensitiveDict(dict): ...
307
class Context: ...
308
class ETag: ...
309
```
310
311
[Utilities](./utilities.md)
312
313
## Types
314
315
```python { .api }
316
# Request/Response Options
317
class RequestOptions:
318
auto_parse_form_urlencoded: bool
319
auto_parse_qs_csv: bool
320
default_media_type: str
321
media_handlers: Handlers
322
strip_url_path_trailing_slash: bool
323
324
class ResponseOptions:
325
default_media_type: str
326
media_handlers: Handlers
327
secure_cookies_by_default: bool
328
static_media_types: dict
329
330
# WebSocket payload types
331
class WebSocketPayloadType:
332
TEXT: int
333
BINARY: int
334
```
335
336
## Constants
337
338
```python { .api }
339
# HTTP Methods
340
HTTP_METHODS: list # Standard HTTP methods
341
WEBDAV_METHODS: list # WebDAV methods
342
COMBINED_METHODS: list # All supported methods
343
344
# Media Types
345
DEFAULT_MEDIA_TYPE: str # 'application/json'
346
MEDIA_JSON: str # 'application/json'
347
MEDIA_XML: str # 'application/xml'
348
MEDIA_HTML: str # 'text/html'
349
MEDIA_TEXT: str # 'text/plain'
350
MEDIA_URLENCODED: str # 'application/x-www-form-urlencoded'
351
MEDIA_MULTIPART: str # 'multipart/form-data'
352
MEDIA_MSGPACK: str # 'application/msgpack'
353
354
# HTTP Status Codes
355
356
## Numeric Status Codes
357
358
### 1xx Informational
359
HTTP_100: str # '100 Continue'
360
HTTP_101: str # '101 Switching Protocols'
361
HTTP_102: str # '102 Processing'
362
HTTP_103: str # '103 Early Hints'
363
364
### 2xx Success
365
HTTP_200: str # '200 OK'
366
HTTP_201: str # '201 Created'
367
HTTP_202: str # '202 Accepted'
368
HTTP_203: str # '203 Non-Authoritative Information'
369
HTTP_204: str # '204 No Content'
370
HTTP_205: str # '205 Reset Content'
371
HTTP_206: str # '206 Partial Content'
372
HTTP_207: str # '207 Multi-Status'
373
HTTP_208: str # '208 Already Reported'
374
HTTP_226: str # '226 IM Used'
375
376
### 3xx Redirection
377
HTTP_300: str # '300 Multiple Choices'
378
HTTP_301: str # '301 Moved Permanently'
379
HTTP_302: str # '302 Found'
380
HTTP_303: str # '303 See Other'
381
HTTP_304: str # '304 Not Modified'
382
HTTP_305: str # '305 Use Proxy'
383
HTTP_307: str # '307 Temporary Redirect'
384
HTTP_308: str # '308 Permanent Redirect'
385
386
### 4xx Client Error
387
HTTP_400: str # '400 Bad Request'
388
HTTP_401: str # '401 Unauthorized'
389
HTTP_402: str # '402 Payment Required'
390
HTTP_403: str # '403 Forbidden'
391
HTTP_404: str # '404 Not Found'
392
HTTP_405: str # '405 Method Not Allowed'
393
HTTP_406: str # '406 Not Acceptable'
394
HTTP_407: str # '407 Proxy Authentication Required'
395
HTTP_408: str # '408 Request Timeout'
396
HTTP_409: str # '409 Conflict'
397
HTTP_410: str # '410 Gone'
398
HTTP_411: str # '411 Length Required'
399
HTTP_412: str # '412 Precondition Failed'
400
HTTP_413: str # '413 Content Too Large'
401
HTTP_414: str # '414 URI Too Long'
402
HTTP_415: str # '415 Unsupported Media Type'
403
HTTP_416: str # '416 Range Not Satisfiable'
404
HTTP_417: str # '417 Expectation Failed'
405
HTTP_418: str # '418 I\'m a Teapot'
406
HTTP_421: str # '421 Misdirected Request'
407
HTTP_422: str # '422 Unprocessable Entity'
408
HTTP_423: str # '423 Locked'
409
HTTP_424: str # '424 Failed Dependency'
410
HTTP_425: str # '425 Too Early'
411
HTTP_426: str # '426 Upgrade Required'
412
HTTP_428: str # '428 Precondition Required'
413
HTTP_429: str # '429 Too Many Requests'
414
HTTP_431: str # '431 Request Header Fields Too Large'
415
HTTP_451: str # '451 Unavailable For Legal Reasons'
416
417
### 5xx Server Error
418
HTTP_500: str # '500 Internal Server Error'
419
HTTP_501: str # '501 Not Implemented'
420
HTTP_502: str # '502 Bad Gateway'
421
HTTP_503: str # '503 Service Unavailable'
422
HTTP_504: str # '504 Gateway Timeout'
423
HTTP_505: str # '505 HTTP Version Not Supported'
424
HTTP_506: str # '506 Variant Also Negotiates'
425
HTTP_507: str # '507 Insufficient Storage'
426
HTTP_508: str # '508 Loop Detected'
427
HTTP_510: str # '510 Not Extended'
428
HTTP_511: str # '511 Network Authentication Required'
429
430
### 7xx Custom Error Codes (Falcon Extensions)
431
HTTP_701: str # '701 Meh'
432
HTTP_702: str # '702 Emacs'
433
HTTP_703: str # '703 Explosion'
434
HTTP_710: str # '710 PHP'
435
HTTP_711: str # '711 Convenience Store'
436
HTTP_712: str # '712 NoSQL'
437
HTTP_719: str # '719 I am not a teapot'
438
HTTP_720: str # '720 Unpossible'
439
HTTP_721: str # '721 Known Unknowns'
440
HTTP_722: str # '722 Unknown Unknowns'
441
HTTP_723: str # '723 Tricky'
442
HTTP_724: str # '724 This line should be unreachable'
443
HTTP_725: str # '725 It works on my machine'
444
HTTP_726: str # '726 It\'s a feature, not a bug'
445
HTTP_727: str # '727 32 bits is plenty'
446
HTTP_740: str # '740 Computer says no'
447
HTTP_741: str # '741 Compiling'
448
HTTP_742: str # '742 A kitten dies'
449
HTTP_743: str # '743 RTFM'
450
HTTP_744: str # '744 Nothing to see here'
451
HTTP_745: str # '745 Not implemented'
452
HTTP_748: str # '748 Confounded by ponies'
453
HTTP_749: str # '749 Reserved for Chuck Norris'
454
HTTP_750: str # '750 Didn\'t bother to compile it'
455
HTTP_753: str # '753 Syntax Error'
456
HTTP_754: str # '754 Too many semi-colons'
457
HTTP_755: str # '755 Not enough cowbell'
458
HTTP_759: str # '759 Unexpected T_PAAMAYIM_NEKUDOTAYIM'
459
HTTP_771: str # '771 Version mismatch'
460
HTTP_772: str # '772 Incompatible dependencies'
461
HTTP_773: str # '773 Missing dependency'
462
HTTP_774: str # '774 Shit happens'
463
HTTP_776: str # '776 Coincidence'
464
HTTP_777: str # '777 Coincidence'
465
HTTP_778: str # '778 Coincidence'
466
HTTP_779: str # '779 Off by one error'
467
HTTP_780: str # '780 Project owner not responding'
468
HTTP_781: str # '781 Operations'
469
HTTP_782: str # '782 QA'
470
HTTP_783: str # '783 It was DNS'
471
HTTP_784: str # '784 It was a race condition'
472
HTTP_785: str # '785 It was a cache issue'
473
HTTP_786: str # '786 Cached for too long'
474
HTTP_791: str # '791 The Internet shut down due to copyright restrictions'
475
HTTP_792: str # '792 Climate change driven catastrophic weather event'
476
HTTP_797: str # '797 We are no longer Amazon\'s ELB'
477
HTTP_799: str # '799 End of the world'
478
479
## Named Status Codes (Aliases)
480
HTTP_ACCEPTED: str # Alias for HTTP_202
481
HTTP_ALREADY_REPORTED: str # Alias for HTTP_208
482
HTTP_BAD_GATEWAY: str # Alias for HTTP_502
483
HTTP_BAD_REQUEST: str # Alias for HTTP_400
484
HTTP_CONFLICT: str # Alias for HTTP_409
485
HTTP_CONTENT_TOO_LARGE: str # Alias for HTTP_413
486
HTTP_CONTINUE: str # Alias for HTTP_100
487
HTTP_CREATED: str # Alias for HTTP_201
488
HTTP_EARLY_HINTS: str # Alias for HTTP_103
489
HTTP_EXPECTATION_FAILED: str # Alias for HTTP_417
490
HTTP_FAILED_DEPENDENCY: str # Alias for HTTP_424
491
HTTP_FORBIDDEN: str # Alias for HTTP_403
492
HTTP_FOUND: str # Alias for HTTP_302
493
HTTP_GATEWAY_TIMEOUT: str # Alias for HTTP_504
494
HTTP_GONE: str # Alias for HTTP_410
495
HTTP_HTTP_VERSION_NOT_SUPPORTED: str # Alias for HTTP_505
496
HTTP_IM_A_TEAPOT: str # Alias for HTTP_418
497
HTTP_IM_USED: str # Alias for HTTP_226
498
HTTP_INSUFFICIENT_STORAGE: str # Alias for HTTP_507
499
HTTP_INTERNAL_SERVER_ERROR: str # Alias for HTTP_500
500
HTTP_LENGTH_REQUIRED: str # Alias for HTTP_411
501
HTTP_LOCKED: str # Alias for HTTP_423
502
HTTP_LOOP_DETECTED: str # Alias for HTTP_508
503
HTTP_METHOD_NOT_ALLOWED: str # Alias for HTTP_405
504
HTTP_MISDIRECTED_REQUEST: str # Alias for HTTP_421
505
HTTP_MOVED_PERMANENTLY: str # Alias for HTTP_301
506
HTTP_MULTI_STATUS: str # Alias for HTTP_207
507
HTTP_MULTIPLE_CHOICES: str # Alias for HTTP_300
508
HTTP_NETWORK_AUTHENTICATION_REQUIRED: str # Alias for HTTP_511
509
HTTP_NON_AUTHORITATIVE_INFORMATION: str # Alias for HTTP_203
510
HTTP_NOT_ACCEPTABLE: str # Alias for HTTP_406
511
HTTP_NOT_EXTENDED: str # Alias for HTTP_510
512
HTTP_NOT_FOUND: str # Alias for HTTP_404
513
HTTP_NOT_IMPLEMENTED: str # Alias for HTTP_501
514
HTTP_NOT_MODIFIED: str # Alias for HTTP_304
515
HTTP_NO_CONTENT: str # Alias for HTTP_204
516
HTTP_OK: str # Alias for HTTP_200
517
HTTP_PARTIAL_CONTENT: str # Alias for HTTP_206
518
HTTP_PAYMENT_REQUIRED: str # Alias for HTTP_402
519
HTTP_PERMANENT_REDIRECT: str # Alias for HTTP_308
520
HTTP_PRECONDITION_FAILED: str # Alias for HTTP_412
521
HTTP_PRECONDITION_REQUIRED: str # Alias for HTTP_428
522
HTTP_PROCESSING: str # Alias for HTTP_102
523
HTTP_PROXY_AUTHENTICATION_REQUIRED: str # Alias for HTTP_407
524
HTTP_REQUESTED_RANGE_NOT_SATISFIABLE: str # Alias for HTTP_416
525
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: str # Alias for HTTP_431
526
HTTP_REQUEST_TIMEOUT: str # Alias for HTTP_408
527
HTTP_REQUEST_URI_TOO_LONG: str # Alias for HTTP_414
528
HTTP_RESET_CONTENT: str # Alias for HTTP_205
529
HTTP_SEE_OTHER: str # Alias for HTTP_303
530
HTTP_SERVICE_UNAVAILABLE: str # Alias for HTTP_503
531
HTTP_SWITCHING_PROTOCOLS: str # Alias for HTTP_101
532
HTTP_TEMPORARY_REDIRECT: str # Alias for HTTP_307
533
HTTP_TOO_EARLY: str # Alias for HTTP_425
534
HTTP_TOO_MANY_REQUESTS: str # Alias for HTTP_429
535
HTTP_UNAUTHORIZED: str # Alias for HTTP_401
536
HTTP_UNAVAILABLE_FOR_LEGAL_REASONS: str # Alias for HTTP_451
537
HTTP_UNPROCESSABLE_ENTITY: str # Alias for HTTP_422
538
HTTP_UNSUPPORTED_MEDIA_TYPE: str # Alias for HTTP_415
539
HTTP_UPGRADE_REQUIRED: str # Alias for HTTP_426
540
HTTP_USE_PROXY: str # Alias for HTTP_305
541
HTTP_VARIANT_ALSO_NEGOTIATES: str # Alias for HTTP_506
542
```