from fasthtml.common import *
Concise reference
About This Guide
The code examples here use fast.ai style: prefer ternary op, 1-line docstring, minimize vertical space, etc. (Normally fast.ai style uses few if any comments, but they’re added here as documentation.)
Minimal App
A minimal FastHTML app looks something like this:
# Meta-package with all key symbols from FastHTML and Starlette. Import it like this at the start of every FastHTML app.
from fasthtml.common import *
# The FastHTML app object and shortcut to `app.route`
= fast_app()
app,rt
# Enums constrain the values accepted for a route parameter
= str_enum('names', 'Alice', 'Bev', 'Charlie')
name
# Passing a path to `rt` is optional. If not passed (recommended), the function name is the route ('/foo')
# Both GET and POST HTTP methods are handled by default
# Type-annotated params are passed as query params (recommended) unless a path param is defined (which it isn't here)
@rt
def foo(nm: name):
# `Title` and `P` here are FastTags: direct m-expression mappings of HTML tags to Python functions with positional and named parameters. All standard HTML tags are included in the common wildcard import.
# When a tuple is returned, this returns concatenated HTML partials. HTMX by default will use a title HTML partial to set the current page name. HEAD tags (e.g. Meta, Link, etc) in the returned tuple are automatically placed in HEAD; everything else is placed in BODY.
# FastHTML will automatically return a complete HTML document with appropriate headers if a normal HTTP request is received. For an HTMX request, however, just the partials are returned.
return Title("FastHTML"), H1("My web app"), P(f"Hello, {name}!")
# By default `serve` runs uvicorn on port 5001. Never write `if __name__ == "__main__"` since `serve` checks it internally.
serve()
To run this web app:
python main.py # access via localhost:5001
JS
The Script
function allows you to include JavaScript. You can use Python to generate parts of your JS or JSON like this:
# In future snippets this import will not be shown, but is required
from fasthtml.common import *
= fast_app(hdrs=[Script(src="https://cdn.plot.ly/plotly-2.32.0.min.js")])
app,rt # `index` is a special function name which maps to the `/` route.
@rt
def index():
= {'somedata':'fill me in…'}
data # `Titled` returns a title tag and an h1 tag with the 1st param, with remaining params as children in a `Main` parent.
return Titled("Chart Demo", Div(id="myDiv"), Script(f"var data = {data}; Plotly.newPlot('myDiv', data);"))
# In future snippets `serve() will not be shown, but is required
serve()
Prefer Python whenever possible over JS. Never use React or shadcn.
fast_app hdrs
# In future snippets we'll skip showing the `fast_app` call if it has no params
= fast_app(
app, rt =False, # The Pico CSS framework is included by default, so pass `False` to disable it if needed. No other CSS frameworks are included.
pico# These are added to the `head` part of the page for non-HTMX requests.
=(
hdrs='stylesheet', href='assets/normalize.min.css', type='text/css'),
Link(rel='stylesheet', href='assets/sakura.css', type='text/css'),
Link(rel"p {color: red;}"),
Style(# `MarkdownJS` and `HighlightJS` are available via concise functions
=['python', 'javascript', 'html', 'css']),
MarkdownJS(), HighlightJS(langs# by default, all standard static extensions are served statically from the web app dir,
# which can be modified using e.g `static_path='public'`
)
)
@rt
def index(req): return Titled("Markdown rendering example",
# This will be client-side rendered to HTML with highlight-js
"*hi* there",cls="marked"),
Div(# This will be syntax highlighted
"def foo(): pass"))) Pre(Code(
Responses
Routes can return various types:
- FastTags or tuples of FastTags (automatically rendered to HTML)
- Standard Starlette responses (used directly)
- JSON-serializable types (returned as JSON in a plain text response)
@rt("/{fname:path}.{ext:static}")
async def serve_static_file(fname:str, ext:str): return FileResponse(f'public/{fname}.{ext}')
= fast_app(hdrs=(MarkdownJS(), HighlightJS(langs=['python', 'javascript'])))
app, rt @rt
def index():
return Titled("Example",
"*markdown* here", cls="marked"),
Div("def foo(): pass"))) Pre(Code(
Route functions can be used in attributes like href
or action
and will be converted to paths. Use .to()
to generate paths with query parameters.
@rt
def profile(email:str): return fill_form(profile_form, profiles[email])
= Form(action=profile)(
profile_form "Email", Input(name="email")),
Label("Save", type="submit")
Button(
)
= profile.to(email="user@example.com") # '/profile?email=user%40example.com' user_profile_path
from dataclasses import dataclass
= fast_app() app,rt
When a route handler function is used as a fasttag attribute (such as href
, hx_get
, or action
) it is converted to that route’s path. fill_form
is used to copy an object’s matching attrs into matching-name form fields.
@dataclass
class Profile: email:str; phone:str; age:int
= 'john@example.com'
email = {email: Profile(email=email, phone='123456789', age=5)}
profiles @rt
def profile(email:str): return fill_form(profile_form, profiles[email])
= Form(method="post", action=profile)(
profile_form
Fieldset('Email', Input(name="email")),
Label("Phone", Input(name="phone")),
Label("Age", Input(name="age"))),
Label("Save", type="submit")) Button(
Testing
We can use TestClient
for testing.
from starlette.testclient import TestClient
= "/profile?email=john@example.com"
path = TestClient(app)
client = {'HX-Request':'1'}
htmx_req print(client.get(path, headers=htmx_req).text)
<form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="john@example.com">
</label><label>Phone <input name="phone" value="123456789">
</label><label>Age <input name="age" value="5">
</label></fieldset><button type="submit">Save</button></form>
Form Handling and Data Binding
When a dataclass, namedtuple, etc. is used as a type annotation, the form body will be unpacked into matching attribute names automatically.
@rt
def edit_profile(profile: Profile):
=profile
profiles[email]return RedirectResponse(url=path)
= dict(email='john@example.com', phone='7654321', age=25)
new_data print(client.post("/edit_profile", data=new_data, headers=htmx_req).text)
<form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="john@example.com">
</label><label>Phone <input name="phone" value="7654321">
</label><label>Age <input name="age" value="25">
</label></fieldset><button type="submit">Save</button></form>
fasttag Rendering Rules
The general rules for rendering children inside tuples or fasttag children are: - __ft__
method will be called (for default components like P
, H2
, etc. or if you define your own components) - If you pass a string, it will be escaped - On other python objects, str()
will be called
If you want to include plain HTML tags directly into e.g. a Div()
they will get escaped by default (as a security measure to avoid code injections). This can be avoided by using Safe(...)
, e.g to show a data frame use Div(NotStr(df.to_html()))
.
Exceptions
FastHTML allows customization of exception handlers.
def not_found(req, exc): return Titled("404: I don't exist!")
= {404: not_found}
exception_handlers = fast_app(exception_handlers=exception_handlers) app, rt
Request and Session Objects
FastHTML provides access to Starlette’s session middleware automatically using the special session
parameter name (or any prefix of that name).
@rt
def profile(req, sess, user_id: int=None):
= req.client.host
ip 'last_visit'] = datetime.now().isoformat()
sess[= sess.setdefault('visit_count', 0) + 1
visits 'visit_count'] = visits
sess[= get_user(user_id or sess.get('user_id'))
user return Titled(f"Profile: {user.name}",
f"Visits: {visits}"),
P(f"IP: {ip}"),
P("Logout", hx_post=logout)) Button(
Handler functions can return the HtmxResponseHeaders
object to set HTMX-specific response headers.
@rt
def htmlredirect(app): return HtmxResponseHeaders(location="http://example.org")
APIRouter
APIRouter
lets you organize routes across multiple files in a FastHTML app.
# products.py
= APIRouter()
ar
@ar
def details(pid: int): return f"Here are the product details for ID: {pid}"
@ar
def all_products(req):
return Div(
Div("Details",hx_get=details.to(pid=42),hx_target="#products_list",hx_swap="outerHTML",),
Button(id="products_list") ),
# main.py
from products import ar,all_products
= fast_app()
app, rt
ar.to_app(app)
@rt
def index():
return Div(
"Products",
=all_products, hx_swap="outerHTML") hx_get
Toasts
Toasts can be of four types:
- info
- success
- warning
- error
Toasts require the use of the setup_toasts()
function, plus every handler needs:
- The session argument
- Must return FT components
setup_toasts(app)
@rt
def toasting(session):
f"cooked", "info")
add_toast(session, f"ready", "success")
add_toast(session, return Titled("toaster")
setup_toasts(duration)
allows you to specify how long a toast will be visible before disappearing.10 seconds.
Authentication and authorization are handled with Beforeware, which functions that run before the route handler is called.
Auth
def user_auth_before(req, sess):
# `auth` key in the request scope is automatically provided to any handler which requests it and can not be injected
= req.scope['auth'] = sess.get('auth', None)
auth if not auth: return RedirectResponse('/login', status_code=303)
= Beforeware(
beforeware
user_auth_before,=[r'/favicon\.ico', r'/static/.*', r'.*\.css', r'.*\.js', '/login', '/']
skip
)
= fast_app(before=beforeware) app, rt
Server-Side Events (SSE)
FastHTML supports the HTMX SSE extension.
import random
=(Script(src="https://unpkg.com/htmx-ext-sse@2.2.3/sse.js"),)
hdrs= fast_app(hdrs=hdrs)
app,rt
@rt
def index(): return Div(hx_ext="sse", sse_connect="/numstream", hx_swap="beforeend show:bottom", sse_swap="message")
# `signal_shutdown()` gets an event that is set on shutdown
= signal_shutdown()
shutdown_event
async def number_generator():
while not shutdown_event.is_set():
= Article(random.randint(1, 100))
data yield sse_message(data)
@rt
async def numstream(): return EventStream(number_generator())
Websockets
FastHTML provides useful tools for HTMX’s websockets extension.
# These HTMX extensions are available through `exts`:
# head-support preload class-tools loading-states multi-swap path-deps remove-me ws chunked-transfer
= fast_app(exts='ws')
app, rt
def mk_inp(): return Input(id='msg', autofocus=True)
@rt
async def index(request):
# `ws_send` tells HTMX to send a message to the nearest websocket based on the trigger for the form element
= Div(
cts id='notifications'),
Div(id='form', ws_send=True),
Form(mk_inp(), ='ws', ws_connect='/ws')
hx_extreturn Titled('Websocket Test', cts)
async def on_connect(send): await send(Div('Hello, you have connected', id="notifications"))
async def on_disconnect(ws): print('Disconnected!')
@app.ws('/ws', conn=on_connect, disconn=on_disconnect)
async def ws(msg:str, send):
# websocket hander returns/sends are treated as OOB swaps
await send(Div('Hello ' + msg, id="notifications"))
return Div('Goodbye ' + msg, id="notifications"), mk_inp()
Single File Uploads
Form
defaults to “multipart/form-data”. A Starlette UploadFile is passed to the handler.
= Path("filez")
upload_dir
@rt
def index():
return (
=upload, hx_target="#result")(
Form(hx_posttype="file", name="file"),
Input("Upload", type="submit")),
Button(id="result")
Div(
)
# Use `async` handlers where IO is used to avoid blocking other clients
@rt
async def upload(file: UploadFile):
= await file.read()
filebuffer / file.filename).write_bytes(filebuffer)
(upload_dir return P('Size: ', file.size)
For multi-file, use Input(..., multiple=True)
, and a type annotation of list[UploadFile]
in the handler.
Fastlite
Fastlite and the MiniDataAPI specification it’s built on are a CRUD-oriented API for working with SQLite. APSW and apswutils is used to connect to SQLite, optimized for speed and clean error handling.
from fastlite import *
= database(':memory:') # or database('data/app.db') db
Tables are normally constructed with classes, field types are specified as type hints.
class Book: isbn: str; title: str; pages: int; userid: int
# The transform arg instructs fastlite to change the db schema when fields change.
# Create only creates a table if the table doesn't exist.
= db.create(Book, pk='isbn', transform=True)
books
class User: id: int; name: str; active: bool = True
# If no pk is provided, id is used as the primary key.
= db.create(User, transform=True)
users users
<Table user (id, name, active)>
Fastlite CRUD operations
Every operation in fastlite returns a full superset of dataclass functionality.
= users.insert(name='Alex',active=False)
user user
User(id=1, name='Alex', active=0)
# List all records
users()
[User(id=1, name='Alex', active=0)]
# Limit, offset, and order results:
='name', limit=2, offset=1)
users(order_by
# Filter on the results
="name='Alex'")
users(where
# Placeholder for avoiding injection attacks
"name=?", ('Alex',))
users(
# A single record by pk
id] users[user.
User(id=1, name='Alex', active=0)
Test if a record exists by using in
keyword on primary key:
1 in users
True
Updates (which take a dict or a typed object) return the updated record.
='Lauren'
user.name=True
user.active users.update(user)
User(id=1, name='Lauren', active=1)
.xtra()
to automatically constrain queries, updates, and inserts from there on:
=True)
users.xtra(active users()
[User(id=1, name='Lauren', active=1)]
Deleting by pk:
id) users.delete(user.
<Table user (id, name, active)>
NotFoundError is raised by pk []
, updates, and deletes.
try: users['Amy']
except NotFoundError: print('User not found')
User not found
MonsterUI
MonsterUI is a shadcn-like component library for FastHTML. It adds the Tailwind-based libraries FrankenUI and DaisyUI to FastHTML, as well as Python’s mistletoe for Markdown, HighlightJS for code highlighting, and Katex for latex support, following semantic HTML patterns when possible. It is recommended for when you wish to go beyond the basics provided by FastHTML’s built-in pico support.
A minimal app:
from fasthtml.common import *
from monsterui.all import *
= fast_app(hdrs=Theme.blue.headers()) # Use MonsterUI blue theme
app, rt
@rt
def index():
= (('github','https://github.com/AnswerDotAI/MonsterUI'),)
socials return Titled("App",
Card("App", cls=TextPresets.muted_sm),
P(# LabelInput, DivLAigned, and UkIconLink are non-semantic MonsterUI FT Components,
'Email', type='email', required=True),
LabelInput(=DivLAligned(*[UkIconLink(icon,href=url) for icon,url in socials]))) footer
Flex Layout Elements (such as DivLAligned
and DivFullySpaced
) can be used to create layouts concisely
def TeamCard(name, role, location="Remote"):
= ("mail", "linkedin", "github")
icons return Card(
DivLAligned(=24, w=24),
DiceBearAvatar(name, h
Div(H3(name), P(role))),=DivFullySpaced(
footer"map-pin", height=16), P(location)),
DivHStacked(UkIcon(*(UkIconLink(icon, height=16) for icon in icons)))) DivHStacked(
Forms are styled and spaced for you without significant additional classes.
def MonsterForm():
= ["Parent",'Sibling', "Friend", "Spouse", "Significant Other", "Relative", "Child", "Other"]
relationship return Div(
DivCentered("Emergency Contact Form"),
H3("Please fill out the form completely", cls=TextPresets.muted_sm)),
P(
Form("Name",id='name'),LabelInput("Email", id='email')),
Grid(LabelInput("Relationship to patient"),
H3(*[LabelCheckboxX(o) for o in relationship], cols=4, cls='space-y-3'),
Grid("Submit Form", cls=ButtonT.primary))),
DivCentered(Button(='space-y-4') cls
Text can be styled with markdown automatically with MonsterUI
"""
render_md(# My Document
> Important note here
+ List item with **bold**
+ Another with `code`
```python
def hello():
print("world")
```
""")
'<div><h1 class="uk-h1 text-4xl font-bold mt-12 mb-6">My Document</h1>\n<blockquote class="uk-blockquote pl-4 border-l-4 border-primary italic mb-6">\n<p class="text-lg leading-relaxed mb-6">Important note here</p>\n</blockquote>\n<ul class="uk-list uk-list-bullet space-y-2 mb-6 ml-6 text-lg">\n<li class="leading-relaxed">List item with <strong>bold</strong></li>\n<li class="leading-relaxed">Another with <code class="uk-codespan px-1">code</code></li>\n</ul>\n<pre class="bg-base-200 rounded-lg p-4 mb-6"><code class="language-python uk-codespan px-1 uk-codespan px-1 block overflow-x-auto">def hello():\n print("world")\n</code></pre>\n</div>'
Or using semantic HTML:
def SemanticText():
return Card(
"MonsterUI's Semantic Text"),
H1(
P("MonsterUI"), " brings the power of semantic HTML to life with ",
Strong("beautiful styling"), " and ", Mark("zero configuration"), "."),
Em(
Blockquote("Write semantic HTML in pure Python, get modern styling for free."),
P("MonsterUI Team")),
Cite(=Small("Released February 2025"),) footer