0
# Application Creation and Routing
1
2
Core functionality for creating FastHTML applications, defining routes, and handling HTTP requests and responses.
3
4
## Capabilities
5
6
### Application Creation
7
8
Create FastHTML applications with comprehensive configuration options including database integration, middleware, authentication, and development features.
9
10
```python { .api }
11
def fast_app(
12
db=None,
13
render=None,
14
hdrs=None,
15
ftrs=None,
16
tbls=None,
17
before=None,
18
middleware=None,
19
live=False,
20
debug=False,
21
routes=None,
22
exception_handlers=None,
23
on_startup=None,
24
on_shutdown=None,
25
lifespan=None,
26
default_hdrs=True,
27
pico=True,
28
surreal=True,
29
htmx=True,
30
ws_hdr=False,
31
secret_key=None,
32
key_fname='.sesskey',
33
session_cookie='session',
34
max_age=365*24*3600,
35
sess_path='/',
36
same_site='lax',
37
sess_https_only=False,
38
sess_domain=None,
39
htmlkw=None,
40
**bodykw
41
) -> tuple[FastHTML, RouteFuncs]:
42
"""
43
Create FastHTML app with sensible defaults and optional database integration.
44
45
Args:
46
db: Database connection or path for SQLite
47
render: Custom rendering function
48
hdrs: Additional HTTP headers to include
49
ftrs: Footer elements to include in pages
50
tbls: Database tables to create/manage
51
before: Beforeware middleware functions
52
middleware: ASGI middleware stack
53
live: Enable live reload for development
54
debug: Enable debug mode
55
routes: Additional routes to include
56
exception_handlers: Custom exception handlers
57
on_startup: Startup event handlers
58
on_shutdown: Shutdown event handlers
59
lifespan: Application lifespan manager
60
default_hdrs: Include default headers (HTMX, etc.)
61
pico: Include PicoCSS framework
62
surreal: Include Surreal.js for client-side scripting
63
htmx: Include HTMX for dynamic interactions
64
ws_hdr: Include WebSocket headers
65
secret_key: Session encryption key
66
key_fname: Filename to store session key
67
session_cookie: Session cookie name
68
max_age: Session cookie max age in seconds
69
sess_path: Session cookie path
70
same_site: Session cookie SameSite attribute
71
sess_https_only: Session cookie secure flag
72
sess_domain: Session cookie domain
73
htmlkw: Additional HTML element kwargs
74
**bodykw: Additional body element kwargs
75
76
Returns:
77
tuple: (FastHTML app instance, RouteFuncs for routing)
78
"""
79
80
class FastHTML:
81
"""
82
Main FastHTML application class (extends Starlette).
83
84
Provides ASGI application with FastHTML-specific functionality
85
including HTML generation, HTMX integration, and enhanced routing.
86
"""
87
88
def __init__(
89
self,
90
debug=False,
91
routes=None,
92
middleware=None,
93
exception_handlers=None,
94
on_startup=None,
95
on_shutdown=None,
96
lifespan=None
97
):
98
"""Initialize FastHTML application."""
99
```
100
101
### Development Server
102
103
Start development server with hot reload and configuration options.
104
105
```python { .api }
106
def serve(
107
appname=None,
108
app='app',
109
host='0.0.0.0',
110
port=None,
111
reload=True,
112
reload_includes=None,
113
reload_excludes=None
114
):
115
"""
116
Start development server with hot reload.
117
118
Args:
119
appname: Name of the application module
120
app: Application instance or attribute name
121
host: Host to bind server to
122
port: Port to bind server to (auto-selected if None)
123
reload: Enable hot reload for development
124
reload_includes: Additional file patterns to watch
125
reload_excludes: File patterns to exclude from watching
126
"""
127
```
128
129
### Route Definition
130
131
Define HTTP routes using the RouteFuncs container with method-specific decorators.
132
133
```python { .api }
134
class RouteFuncs:
135
"""
136
Dynamic route function container for HTTP methods.
137
138
Provides decorators for all HTTP methods and path patterns.
139
Routes are defined using method decorators that specify the path.
140
"""
141
142
def __call__(self, path: str, methods=None):
143
"""Generic route decorator for any HTTP method."""
144
145
def get(self, path: str):
146
"""GET route decorator."""
147
148
def post(self, path: str):
149
"""POST route decorator."""
150
151
def put(self, path: str):
152
"""PUT route decorator."""
153
154
def delete(self, path: str):
155
"""DELETE route decorator."""
156
157
def patch(self, path: str):
158
"""PATCH route decorator."""
159
160
def head(self, path: str):
161
"""HEAD route decorator."""
162
163
def options(self, path: str):
164
"""OPTIONS route decorator."""
165
166
def trace(self, path: str):
167
"""TRACE route decorator."""
168
169
def ws(self, path: str):
170
"""WebSocket route decorator."""
171
172
class APIRouter:
173
"""
174
Route organization and modularity system.
175
176
Enables grouping related routes with common prefixes, middleware,
177
and shared configuration for better code organization.
178
"""
179
180
def __init__(self, prefix: str = "", body_wrap=None):
181
"""
182
Initialize API router with optional prefix and configuration.
183
184
Args:
185
prefix: URL prefix for all routes in this router
186
body_wrap: Default body wrapper function for routes
187
"""
188
189
def __call__(self, path: str, methods=None, name=None, include_in_schema=True, body_wrap=None):
190
"""Add route to router."""
191
192
def get(self, path: str, name=None, include_in_schema=True, body_wrap=None):
193
"""GET route decorator."""
194
195
def post(self, path: str, name=None, include_in_schema=True, body_wrap=None):
196
"""POST route decorator."""
197
198
def put(self, path: str, name=None, include_in_schema=True, body_wrap=None):
199
"""PUT route decorator."""
200
201
def delete(self, path: str, name=None, include_in_schema=True, body_wrap=None):
202
"""DELETE route decorator."""
203
204
def patch(self, path: str, name=None, include_in_schema=True, body_wrap=None):
205
"""PATCH route decorator."""
206
207
def head(self, path: str, name=None, include_in_schema=True, body_wrap=None):
208
"""HEAD route decorator."""
209
210
def options(self, path: str, name=None, include_in_schema=True, body_wrap=None):
211
"""OPTIONS route decorator."""
212
213
def trace(self, path: str, name=None, include_in_schema=True, body_wrap=None):
214
"""TRACE route decorator."""
215
216
def ws(self, path: str, conn=None, disconn=None, name=None, middleware=None):
217
"""WebSocket route decorator."""
218
219
def to_app(self, app):
220
"""Apply all router routes to FastHTML app."""
221
```
222
223
### HTTP Response Handling
224
225
Create and manage HTTP responses with FastHTML-specific enhancements.
226
227
```python { .api }
228
class FtResponse:
229
"""FastHTML response wrapper with HTML generation support."""
230
231
def respond(
232
content=None,
233
status_code: int = 200,
234
headers: dict = None,
235
media_type: str = None
236
):
237
"""
238
Create HTTP response.
239
240
Args:
241
content: Response content (HTML, text, or FastHTML elements)
242
status_code: HTTP status code
243
headers: Additional response headers
244
media_type: Content-Type header value
245
246
Returns:
247
Response object
248
"""
249
250
class JSONResponse:
251
"""JSON response class with custom rendering."""
252
253
def __init__(self, content, status_code: int = 200, headers: dict = None):
254
"""Create JSON response."""
255
256
class Redirect:
257
"""Redirect response class."""
258
259
def __init__(self, url: str, status_code: int = 302):
260
"""Create redirect response."""
261
```
262
263
### Request Processing
264
265
Handle HTTP requests with parameter extraction and processing utilities.
266
267
```python { .api }
268
def form2dict(form) -> dict:
269
"""
270
Convert FormData to dictionary.
271
272
Args:
273
form: FormData object from request
274
275
Returns:
276
dict: Converted form data
277
"""
278
279
def qp(**kwargs) -> str:
280
"""
281
Build query parameter string.
282
283
Args:
284
**kwargs: Query parameters as key-value pairs
285
286
Returns:
287
str: URL-encoded query string
288
"""
289
290
def uri(path: str, **kwargs) -> str:
291
"""
292
Build URI with query parameters.
293
294
Args:
295
path: Base path
296
**kwargs: Query parameters
297
298
Returns:
299
str: Complete URI with query string
300
"""
301
302
def decode_uri(uri: str) -> str:
303
"""Decode URI components."""
304
```
305
306
### Middleware and Processing
307
308
Pre-processing middleware and request handling utilities.
309
310
```python { .api }
311
class Beforeware:
312
"""
313
Middleware base for preprocessing.
314
315
Allows modification of requests before route handling.
316
"""
317
318
def __init__(self, f, skip=None):
319
"""Initialize middleware with processing function."""
320
321
class MiddlewareBase:
322
"""Base class for middleware."""
323
324
def __init__(self, app):
325
"""Initialize middleware with application."""
326
```
327
328
### Utility Functions
329
330
Helper functions for application development and request processing.
331
332
```python { .api }
333
def get_key(key_fname: str = '.sesskey') -> str:
334
"""
335
Get session key from file.
336
337
Args:
338
key_fname: Filename containing the session key
339
340
Returns:
341
str: Session encryption key
342
"""
343
344
def signal_shutdown():
345
"""Handle graceful application shutdown."""
346
347
def unqid() -> str:
348
"""Generate unique identifier."""
349
350
def reg_re_param(name: str, pattern: str):
351
"""
352
Register regex route parameter.
353
354
Args:
355
name: Parameter name
356
pattern: Regular expression pattern
357
"""
358
359
def cookie(
360
key: str,
361
value: str = '',
362
max_age: int = None,
363
expires: str = None,
364
path: str = '/',
365
domain: str = None,
366
secure: bool = False,
367
httponly: bool = False,
368
samesite: str = 'lax'
369
):
370
"""
371
Create HTTP cookie.
372
373
Args:
374
key: Cookie name
375
value: Cookie value
376
max_age: Cookie lifetime in seconds
377
expires: Cookie expiration date
378
path: Cookie path
379
domain: Cookie domain
380
secure: Secure flag (HTTPS only)
381
httponly: HTTP-only flag (no JavaScript access)
382
samesite: SameSite attribute ('strict', 'lax', 'none')
383
384
Returns:
385
Cookie object
386
"""
387
```
388
389
## Usage Examples
390
391
### Basic Application Setup
392
393
```python
394
from fasthtml.common import *
395
396
# Create app with database and authentication
397
app, rt = fast_app(
398
db='myapp.db',
399
secret_key='your-secret-key',
400
pico=True,
401
htmx=True
402
)
403
404
# Define routes
405
@rt('/')
406
def homepage():
407
return Titled("My App",
408
Div(
409
H1("Welcome"),
410
P("This is my FastHTML application"),
411
A("Click me", hx_get="/dynamic")
412
)
413
)
414
415
@rt('/dynamic')
416
def dynamic_content():
417
return Div("This content loaded dynamically!", style="color: green;")
418
419
# Start server
420
if __name__ == '__main__':
421
serve()
422
```
423
424
### Advanced Routing with Parameters
425
426
```python
427
from fasthtml.common import *
428
429
app, rt = fast_app()
430
431
# Route with path parameters
432
@rt('/user/{user_id}')
433
def user_profile(user_id: int):
434
return Div(
435
H2(f"User Profile: {user_id}"),
436
P(f"Displaying information for user {user_id}")
437
)
438
439
# Route with query parameters
440
@rt('/search')
441
def search(request):
442
query = request.query_params.get('q', '')
443
return Div(
444
H3("Search Results"),
445
P(f"Searching for: {query}") if query else P("No search query provided")
446
)
447
448
# POST route for form handling
449
@rt('/submit', methods=['POST'])
450
def handle_form(form_data):
451
data = form2dict(form_data)
452
return Div(
453
H3("Form Submitted"),
454
P(f"Received: {data}")
455
)
456
```
457
458
### Middleware and Request Processing
459
460
```python
461
from fasthtml.common import *
462
463
def auth_middleware(req, call_next):
464
# Custom authentication logic
465
if not req.headers.get('authorization'):
466
return Redirect('/login')
467
return call_next(req)
468
469
app, rt = fast_app(
470
before=[auth_middleware],
471
middleware=[],
472
debug=True
473
)
474
475
@rt('/protected')
476
def protected_route():
477
return Div("This is a protected route")
478
```