0
# FastHTML
1
2
A next-generation Python web framework for building fast, scalable web applications with minimal code. FastHTML provides a powerful and expressive API that maps directly to HTML and HTTP, allowing developers to create advanced interactive web applications using pure Python.
3
4
## Package Information
5
6
- **Package Name**: python-fasthtml
7
- **Language**: Python
8
- **Installation**: `pip install python-fasthtml`
9
- **Version**: 0.12.25
10
11
## Core Imports
12
13
```python
14
from fasthtml.common import *
15
```
16
17
This single import provides access to all core FastHTML functionality including:
18
- Application creation and routing
19
- All HTML elements as Python functions
20
- HTMX integration for dynamic interactions
21
- Form handling and data processing
22
- Authentication and middleware
23
- JavaScript library integration
24
25
For advanced usage, import specific modules:
26
27
```python
28
from fasthtml.core import FastHTML, APIRouter, HtmxHeaders
29
from fasthtml.components import Div, P, H1, Form, Input
30
from fasthtml.xtend import AX, CheckboxX, Titled, Socials
31
from fasthtml.oauth import OAuth, GoogleAppClient, GitHubAppClient
32
from fasthtml.pico import Card, Grid, Container, picolink
33
from fasthtml.js import MarkdownJS, HighlightJS, SortableJS
34
from fasthtml.svg import Svg, Circle, Rect, Path, PathFT
35
from fasthtml.toaster import Toast, add_toast, setup_toasts
36
from fasthtml.jupyter import show, nb_serve, HTMX
37
```
38
39
## Basic Usage
40
41
```python
42
from fasthtml.common import *
43
44
# Create FastHTML app and router
45
app, rt = fast_app()
46
47
# Define routes using decorators
48
@rt('/')
49
def get():
50
return Div(
51
H1('Welcome to FastHTML'),
52
P('Hello World!', hx_get="/change")
53
)
54
55
@rt('/change')
56
def get():
57
return P('Content changed!', style="color: green;")
58
59
# Start development server
60
serve()
61
```
62
63
## Architecture
64
65
FastHTML is built on modern web development principles:
66
67
- **HTML as Code**: Every HTML element is available as a Python function with the same name
68
- **HTMX Integration**: Built-in support for dynamic web interactions without JavaScript
69
- **Starlette Foundation**: Based on the fast, lightweight Starlette ASGI framework
70
- **Component System**: Reusable UI components with enhanced functionality
71
- **Minimal Dependencies**: Focused on essential web development tools
72
73
The framework emphasizes simplicity and speed, offering a lightweight solution that leverages the full Python ecosystem while maintaining intuitive syntax for rapid development.
74
75
## Capabilities
76
77
### Application Creation and Routing
78
79
Core functionality for creating FastHTML applications, defining routes, and handling HTTP requests. Includes the main FastHTML class, routing decorators, and development server.
80
81
```python { .api }
82
def fast_app(
83
db=None,
84
render=None,
85
hdrs=None,
86
ftrs=None,
87
tbls=None,
88
before=None,
89
middleware=None,
90
live=False,
91
debug=False,
92
routes=None,
93
exception_handlers=None,
94
on_startup=None,
95
on_shutdown=None,
96
lifespan=None,
97
default_hdrs=True,
98
pico=True,
99
surreal=True,
100
htmx=True,
101
ws_hdr=False,
102
secret_key=None,
103
key_fname='.sesskey',
104
session_cookie='session',
105
max_age=365*24*3600,
106
sess_path='/',
107
same_site='lax',
108
sess_https_only=False,
109
sess_domain=None,
110
htmlkw=None,
111
**bodykw
112
) -> tuple[FastHTML, RouteFuncs]:
113
"""
114
Create FastHTML app with sensible defaults and optional database integration.
115
116
Returns:
117
tuple: (FastHTML app instance, RouteFuncs for routing)
118
"""
119
120
def serve(
121
appname=None,
122
app='app',
123
host='0.0.0.0',
124
port=None,
125
reload=True,
126
reload_includes=None,
127
reload_excludes=None
128
):
129
"""Start development server with hot reload."""
130
131
class FastHTML:
132
"""Main FastHTML application class (extends Starlette)."""
133
134
class RouteFuncs:
135
"""Dynamic route function container for HTTP methods."""
136
```
137
138
[Application and Routing](./application-routing.md)
139
140
### HTML Components and Elements
141
142
Complete HTML element generation system with Python functions for every HTML tag. Includes enhanced components with HTMX integration and form handling capabilities.
143
144
```python { .api }
145
def Div(*c, **kw):
146
"""Create HTML div element."""
147
148
def P(*c, **kw):
149
"""Create HTML paragraph element."""
150
151
def H1(*c, **kw):
152
"""Create HTML h1 heading element."""
153
154
def Form(*c, **kw):
155
"""Create HTML form element with enhanced functionality."""
156
157
def Input(*c, **kw):
158
"""Create HTML input element."""
159
160
def Button(*c, **kw):
161
"""Create HTML button element."""
162
```
163
164
[HTML Components](./html-components.md)
165
166
### HTMX Integration and Dynamic Interactions
167
168
Built-in HTMX support for creating dynamic, interactive web applications without writing JavaScript. Includes HTMX attributes, response handling, and event management.
169
170
```python { .api }
171
class HtmxHeaders:
172
"""HTMX request headers dataclass."""
173
hx_request: str
174
hx_target: str
175
hx_trigger: str
176
hx_trigger_name: str
177
hx_current_url: str
178
179
def ft_hx(tag, *c, **kw):
180
"""Create HTML element with HTMX support."""
181
```
182
183
[HTMX Integration](./htmx-integration.md)
184
185
### Form Handling and Data Processing
186
187
Comprehensive form handling including data conversion, validation, file uploads, and dataclass integration.
188
189
```python { .api }
190
def form2dict(form) -> dict:
191
"""Convert FormData to dictionary."""
192
193
def fill_form(form, obj):
194
"""Fill form with data object."""
195
196
def File(*c, **kw):
197
"""Handle file uploads."""
198
```
199
200
[Form Handling](./form-handling.md)
201
202
### Authentication and Security
203
204
OAuth integration with multiple providers, basic authentication middleware, and session management.
205
206
```python { .api }
207
class OAuth:
208
"""Main OAuth handler class."""
209
210
class BasicAuthMiddleware:
211
"""HTTP Basic authentication middleware."""
212
213
class GoogleAppClient:
214
"""Google OAuth integration."""
215
```
216
217
[Authentication](./authentication.md)
218
219
### CSS Framework Integration
220
221
Built-in PicoCSS integration with enhanced components and styling utilities for rapid UI development.
222
223
```python { .api }
224
def Card(*c, **kw):
225
"""PicoCSS card component."""
226
227
def Grid(*c, **kw):
228
"""PicoCSS grid container."""
229
230
def Container(*c, **kw):
231
"""PicoCSS container."""
232
```
233
234
[CSS and Styling](./css-styling.md)
235
236
### JavaScript Integration
237
238
Integration with popular JavaScript libraries including Markdown rendering, syntax highlighting, and interactive components.
239
240
```python { .api }
241
def MarkdownJS(*c, **kw):
242
"""Markdown parsing and rendering."""
243
244
def HighlightJS(*c, **kw):
245
"""Syntax highlighting."""
246
247
def SortableJS(*c, **kw):
248
"""Drag-and-drop sorting."""
249
```
250
251
[JavaScript Integration](./javascript-integration.md)
252
253
### SVG Components and Graphics
254
255
Comprehensive SVG element generation system for creating scalable vector graphics, charts, diagrams, and interactive visualizations.
256
257
```python { .api }
258
def Svg(*args, viewBox=None, xmlns="http://www.w3.org/2000/svg", **kwargs):
259
"""SVG root element with automatic xmlns namespace."""
260
261
def Rect(width, height, x=0, y=0, fill=None, stroke=None, **kwargs):
262
"""SVG rectangle element."""
263
264
def Circle(r, cx=0, cy=0, fill=None, stroke=None, **kwargs):
265
"""SVG circle element."""
266
267
def Path(d='', fill=None, stroke=None, **kwargs):
268
"""SVG path element for complex shapes."""
269
```
270
271
[SVG Components](./svg-components.md)
272
273
### Notifications and Toast Messages
274
275
User notification system with toast messages, flash messages, and session-based notification management for enhanced user experience.
276
277
```python { .api }
278
def Toast(message: str, typ: str = "info", dismiss: bool = False, duration: int = 5000):
279
"""Create toast notification message."""
280
281
def add_toast(sess, message: str, typ: str = "info", dismiss: bool = False):
282
"""Add toast notification to user session."""
283
284
def setup_toasts(app, duration: int = 5000):
285
"""Set up toast notification system in FastHTML app."""
286
```
287
288
[Notifications](./notifications.md)
289
290
### Development Tools
291
292
Development server with live reload, Jupyter notebook integration, testing utilities, and deployment tools.
293
294
```python { .api }
295
def show(ft):
296
"""Display FastHTML elements in Jupyter."""
297
298
class Client:
299
"""HTTP client for testing FastHTML apps."""
300
301
def nb_serve():
302
"""Start Jupyter-compatible server."""
303
```
304
305
[Development Tools](./development-tools.md)