from fasthtml.common import *
Web Devs Quickstart
Installation
pip install python-fasthtml
A Minimal Application
A minimal FastHTML application looks something like this:
main.py
- 1
- We import what we need for rapid development! A carefully-curated set of FastHTML functions and other Python objects is brought into our global namespace for convenience.
- 2
-
We instantiate a FastHTML app with the
fast_app()
utility function. This provides a number of really useful defaults that we’ll take advantage of later in the tutorial. - 3
-
We use the
rt()
decorator to tell FastHTML what to return when a user visits/
in their browser. - 4
-
We connect this route to HTTP GET requests by defining a view function called
get()
. - 5
- A tree of Python function calls that return all the HTML required to write a properly formed web page. You’ll soon see the power of this approach.
- 6
-
The
serve()
utility configures and runs FastHTML using a library calleduvicorn
.
Run the code:
python main.py
The terminal will look like this:
INFO: Uvicorn running on http://0.0.0.0:5001 (Press CTRL+C to quit)
INFO: Started reloader process [58058] using WatchFiles
INFO: Started server process [58060]
INFO: Waiting for application startup.
INFO: Application startup complete.
Confirm FastHTML is running by opening your web browser to 127.0.0.1:5001. You should see something like the image below:
While some linters and developers will complain about the wildcard import, it is by design here and perfectly safe. FastHTML is very deliberate about the objects it exports in fasthtml.common
. If it bothers you, you can import the objects you need individually, though it will make the code more verbose and less readable.
If you want to learn more about how FastHTML handles imports, we cover that here.
A Minimal Charting Application
The Script
function allows you to include JavaScript. You can use Python to generate parts of your JS or JSON like this:
import json
from fasthtml.common import *
= fast_app(hdrs=(Script(src="https://cdn.plot.ly/plotly-2.32.0.min.js"),))
app, rt
= json.dumps({
data "data": [{"x": [1, 2, 3, 4],"type": "scatter"},
"x": [1, 2, 3, 4],"y": [16, 5, 11, 9],"type": "scatter"}],
{"title": "Plotly chart in FastHTML ",
"description": "This is a demo dashboard",
"type": "scatter"
})
@rt("/")
def get():
return Titled("Chart Demo", Div(id="myDiv"),
f"var data = {data}; Plotly.newPlot('myDiv', data);"))
Script(
serve()
Debug Mode
When we can’t figure out a bug in FastHTML, we can run it in DEBUG
mode. When an error is thrown, the error screen is displayed in the browser. This error setting should never be used in a deployed app.
from fasthtml.common import *
1= fast_app(debug=True)
app, rt
@rt("/")
def get():
21/0
return Titled("FastHTML Error!", P("Let's error!"))
serve()
- 1
-
debug=True
sets debug mode on. - 2
- Python throws an error when it tries to divide an integer by zero.
Routing
FastHTML builds upon FastAPI’s friendly decorator pattern for specifying URLs, with extra features:
main.py
- 1
- The “/” URL on line 5 is the home of a project. This would be accessed at 127.0.0.1:5001.
- 2
- “/hello” URL on line 9 will be found by the project if the user visits 127.0.0.1:5001/hello.
It looks like get()
is being defined twice, but that’s not the case. Each function decorated with rt
is totally separate, and is injected into the router. We’re not calling them in the module’s namespace (locals()
). Rather, we’re loading them into the routing mechanism using the rt
decorator.
You can do more! Read on to learn what we can do to make parts of the URL dynamic.
Variables in URLs
You can add variable sections to a URL by marking them with {variable_name}
. Your function then receives the {variable_name}
as a keyword argument, but only if it is the correct type. Here’s an example:
main.py
- 1
-
We specify two variable names,
name
andage
. - 2
- We define two function arguments named identically to the variables. You will note that we specify the Python types to be passed.
- 3
- We use these functions in our project.
Try it out by going to this address: 127.0.0.1:5001/uma/5. You should get a page that says,
“Hello Uma, age 5”.
What happens if we enter incorrect data?
The 127.0.0.1:5001/uma/5 URL works because 5
is an integer. If we enter something that is not, such as 127.0.0.1:5001/uma/five, then FastHTML will return an error instead of a web page.
HTTP Methods
FastHTML matches function names to HTTP methods. So far the URL routes we’ve defined have been for HTTP GET methods, the most common method for web pages.
Form submissions often are sent as HTTP POST. When dealing with more dynamic web page designs, also known as Single Page Apps (SPA for short), the need can arise for other methods such as HTTP PUT and HTTP DELETE. The way FastHTML handles this is by changing the function name.
main.py
- 1
-
On line 6 because the
get()
function name is used, this will handle HTTP GETs going to the/
URI. - 2
-
On line 10 because the
post()
function name is used, this will handle HTTP POSTs going to the/
URI.
CSS Files and Inline Styles
Here we modify default headers to demonstrate how to use the Sakura CSS microframework instead of FastHTML’s default of Pico CSS.
main.py
from fasthtml.common import *
app, rt = fast_app(
1 pico=False,
hdrs=(
Link(rel='stylesheet', href='assets/normalize.min.css', type='text/css'),
2 Link(rel='stylesheet', href='assets/sakura.css', type='text/css'),
3 Style("p {color: red;}")
))
@app.get("/")
def home():
return Titled("FastHTML",
P("Let's do this!"),
)
serve()
- 1
-
By setting
pico
toFalse
, FastHTML will not includepico.min.css
. - 2
-
This will generate an HTML
<link>
tag for sourcing the css for Sakura. - 3
-
If you want an inline styles, the
Style()
function will put the result into the HTML.
Other Static Media File Locations
As you saw, Script
and Link
are specific to the most common static media use cases in web apps: including JavaScript, CSS, and images. But it also works with videos and other static media files. The default behavior is to look for these files in the root directory - typically we don’t do anything special to include them. We can change the default directory that is looked in for files by adding the static_path
parameter to the fast_app
function.
= fast_app(static_path='public') app, rt
FastHTML also allows us to define a route that uses FileResponse
to serve the file at a specified path. This is useful for serving images, videos, and other media files from a different directory without having to change the paths of many files. So if we move the directory containing the media files, we only need to change the path in one place. In the example below, we call images from a directory called public
.
@rt("/{fname:path}.{ext:static}")
async def get(fname:str, ext:str):
return FileResponse(f'public/{fname}.{ext}')
Rendering Markdown
from fasthtml.common import *
= (MarkdownJS(), HighlightJS(langs=['python', 'javascript', 'html', 'css']), )
hdrs
= fast_app(hdrs=hdrs)
app, rt
= """
content Here are some _markdown_ elements.
- This is a list item
- This is another list item
- And this is a third list item
**Fenced code blocks work here.**
"""
@rt('/')
def get(req):
return Titled("Markdown rendering example", Div(content,cls="marked"))
serve()
Code highlighting
Here’s how to highlight code without any markdown configuration.
from fasthtml.common import *
# Add the HighlightJS built-in header
= (HighlightJS(langs=['python', 'javascript', 'html', 'css']),)
hdrs
= fast_app(hdrs=hdrs)
app, rt
= """
code_example import datetime
import time
for i in range(10):
print(f"{datetime.datetime.now()}")
time.sleep(1)
"""
@rt('/')
def get(req):
return Titled("Markdown rendering example",
Div(# The code example needs to be surrounded by
# Pre & Code elements
Pre(Code(code_example))
))
serve()
Defining new ft
components
We can build our own ft
components and combine them with other components. The simplest method is defining them as a function.
def hero(title, statement):
return Div(H1(title),P(statement), cls="hero")
# usage example
Main("Hello World", "This is a hero statement")
hero( )
<main> <div class="hero">
<h1>Hello World</h1>
<p>This is a hero statement</p>
</div>
</main>
Pass through components
For when we need to define a new component that allows zero-to-many components to be nested within them, we lean on Python’s *args
and **kwargs
mechanism. Useful for creating page layout controls.
def layout(*args, **kwargs):
"""Dashboard layout for all our dashboard views"""
return Main(
"Dashboard"),
H1(*args, **kwargs),
Div(="dashboard",
cls
)
# usage example
layout(*[Li(o) for o in range(3)]),
Ul("Some content", cls="description"),
P( )
<main class="dashboard"> <h1>Dashboard</h1>
<div>
<ul>
<li>0</li>
<li>1</li>
<li>2</li>
</ul>
<p class="description">Some content</p>
</div>
</main>
Dataclasses as ft components
While functions are easy to read, for more complex components some might find it easier to use a dataclass.
from dataclasses import dataclass
@dataclass
class Hero:
str
title: str
statement:
def __ft__(self):
""" The __ft__ method renders the dataclass at runtime."""
return Div(H1(self.title),P(self.statement), cls="hero")
# usage example
Main("Hello World", "This is a hero statement")
Hero( )
<main> <div class="hero">
<h1>Hello World</h1>
<p>This is a hero statement</p>
</div>
</main>
Testing views in notebooks
Because of the ASGI event loop it is currently impossible to run FastHTML inside a notebook. However, we can still test the output of our views. To do this, we leverage Starlette, an ASGI toolkit that FastHTML uses.
# First we instantiate our app, in this case we remove the
# default headers to reduce the size of the output.
= fast_app(default_hdrs=False)
app, rt
# Setting up the Starlette test client
from starlette.testclient import TestClient
= TestClient(app)
client
# Usage example
@rt("/")
def get():
return Titled("FastHTML is awesome",
"The fastest way to create web apps in Python"))
P(
print(client.get("/").text)
<!doctype html>
<html>
<head>
<title>FastHTML is awesome</title> </head>
<body>
<main class="container"> <h1>FastHTML is awesome</h1>
<p>The fastest way to create web apps in Python</p>
</main> </body>
</html>
Forms
To validate data coming from users, first define a dataclass representing the data you want to check. Here’s an example representing a signup form.
from dataclasses import dataclass
@dataclass
class Profile: email:str; phone:str; age:int
Create an FT component representing an empty version of that form. Don’t pass in any value to fill the form, that gets handled later.
= 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(
) profile_form
<form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email">
</label><label>Phone <input name="phone">
</label><label>Age <input name="age">
</label></fieldset><button type="submit">Save</button></form>
Once the dataclass and form function are completed, we can add data to the form. To do that, instantiate the profile dataclass:
= Profile(email='[email protected]', phone='123456789', age=5)
profile profile
Profile(email='[email protected]', phone='123456789', age=5)
Then add that data to the profile_form
using FastHTML’s fill_form
class:
fill_form(profile_form, profile)
<form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="[email protected]">
</label><label>Phone <input name="phone" value="123456789">
</label><label>Age <input name="age" value="5">
</label></fieldset><button type="submit">Save</button></form>
Forms with views
The usefulness of FastHTML forms becomes more apparent when they are combined with FastHTML views. We’ll show how this works by using the test client from above. First, let’s create a SQlite database:
= Database("profiles.db")
db = db.create(Profile, pk="email") profiles
Now we insert a record into the database:
profiles.insert(profile)
Profile(email='[email protected]', phone='123456789', age=5)
And we can then demonstrate in the code that form is filled and displayed to the user.
@rt("/profile/{email}")
def profile(email:str):
1= profiles[email]
profile 2= fill_form(profile_form, profile)
filled_profile_form return Titled(f'Profile for {profile.email}', filled_profile_form)
print(client.get(f"/profile/[email protected]").text)
- 1
-
Fetch the profile using the profile table’s
email
primary key - 2
- Fill the form for display.
<!doctype html>
<html>
<head>
<title>Profile for [email protected]</title> </head>
<body>
<main class="container"> <h1>Profile for [email protected]</h1>
<form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="[email protected]">
</label><label>Phone <input name="phone" value="123456789">
</label><label>Age <input name="age" value="5">
</label></fieldset><button type="submit">Save</button></form></main> </body>
</html>
And now let’s demonstrate making a change to the data.
@rt("/profile")
1def post(profile: Profile):
2
profiles.update(profile)3return RedirectResponse(url=f"/profile/{profile.email}")
= dict(email='[email protected]', phone='7654321', age=25)
new_data 4print(client.post("/profile", data=new_data).text)
- 1
-
We use the
Profile
dataclass definition to set the type for the incomingprofile
content. This validates the field types for the incoming data - 2
- Taking our validated data, we updated the profiles table
- 3
- We redirect the user back to their profile view
- 4
- The display is of the profile form view showing the changes in data.
<!doctype html>
<html>
<head>
<title>Profile for [email protected]</title> </head>
<body>
<main class="container"> <h1>Profile for [email protected]</h1>
<form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="[email protected]">
</label><label>Phone <input name="phone" value="7654321">
</label><label>Age <input name="age" value="25">
</label></fieldset><button type="submit">Save</button></form></main> </body>
</html>
Strings and conversion order
The general rules for rendering 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
As a consequence, 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 NotStr()
, a convenient way to reuse python code that returns already HTML. If you use pandas, you can use pandas.DataFrame.to_html()
to get a nice table. To include the output a FastHTML, wrap it in NotStr()
, like Div(NotStr(df.to_html()))
.
Above we saw how a dataclass behaves with the __ft__
method defined. On a plain dataclass, str()
will be called (but not escaped).
from dataclasses import dataclass
@dataclass
class Hero:
str
title: str
statement:
# rendering the dataclass with the default method
Main("<h1>Hello World</h1>", "This is a hero statement")
Hero( )
<main>Hero(title='<h1>Hello World</h1>', statement='This is a hero statement')</main>
# This will display the HTML as text on your page
"Let's include some HTML here: <div>Some HTML</div>") Div(
<div>Let's include some HTML here: <div>Some HTML</div></div>
# Keep the string untouched, will be rendered on the page
"<div><h1>Some HTML</h1></div>")) Div(NotStr(
<div><div><h1>Some HTML</h1></div></div>
Custom exception handlers
FastHTML allows customization of exception handlers, but does so gracefully. What this means is by default it includes all the <html>
tags needed to display attractive content. Try it out!
from fasthtml.common import *
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
@rt('/')
def get():
return (Titled("Home page", P(A(href="/oops")("Click to generate 404 error"))))
serve()
We can also use lambda to make things more terse:
from fasthtml.common import *
={
exception_handlers404: lambda req, exc: Titled("404: I don't exist!"),
418: lambda req, exc: Titled("418: I'm a teapot!")
}
= fast_app(exception_handlers=exception_handlers)
app, rt
@rt('/')
def get():
return (Titled("Home page", P(A(href="/oops")("Click to generate 404 error"))))
serve()
Sessions
For convenience and security, FastHTML has a mechanism for storing small amounts of data in the user’s browser. We can do this by adding a session
argument to routes. FastHTML sessions are Python dictionaries, and we can leverage to our benefit. The example below shows how to concisely set and get sessions.
@rt('/adder/{num}')
def get(session, num: int):
'sum', 0)
session.setdefault('sum'] = session.get('sum') + num
session[return Response(f'The sum is {session["sum"]}.')
Toasts (also known as Messages)
Toasts, sometimes called “Messages” are small notifications usually in colored boxes used to notify users that something has happened. Toasts can be of four types:
- info
- success
- warning
- error
Examples toasts might include:
- “Payment accepted”
- “Data submitted”
- “Request approved”
Toasts require the use of the setup_toasts()
function plus every view needs these two features:
- The session argument
- Must return FT components
1
setup_toasts(app)
@rt('/toasting')
2def get(session):
# Normally one toast is enough, this allows us to see
# different toast types in action.
f"Toast is being cooked", "info")
add_toast(session, f"Toast is ready", "success")
add_toast(session, f"Toast is getting a bit crispy", "warning")
add_toast(session, f"Toast is burning!", "error")
add_toast(session, 3return Titled("I like toast")
- 1
-
setup_toasts
is a helper function that adds toast dependencies. Usually this would be declared right afterfast_app()
- 2
- Toasts require sessions
- 3
- Views with Toasts must return FT components.
Server-sent events (SSE)
With server-sent events, it’s possible for a server to send new data to a web page at any time, by pushing messages to the web page. Unlike WebSockets, SSE can only go in one direction: server to client. SSE is also part of the HTTP specification unlike WebSockets which uses its own specification.
FastHTML introduces several tools for working with SSE which are covered in the example below. While concise, there’s a lot going on in this function so we’ve annotated it quite a bit.
import random
from asyncio import sleep
from fasthtml.common import *
1=(Script(src="https://unpkg.com/[email protected]/sse.js"),)
hdrs= fast_app(hdrs=hdrs)
app,rt
@rt
def index():
return Titled("SSE Random Number Generator",
"Generate pairs of random numbers, as the list grows scroll downwards."),
P(2="sse",
Div(hx_ext3="/number-stream",
sse_connect4="beforeend show:bottom",
hx_swap5="message"))
sse_swap
6= signal_shutdown()
shutdown_event
7async def number_generator():
8while not shutdown_event.is_set():
= Article(random.randint(1, 100))
data 9yield sse_message(data)
await sleep(1)
@rt("/number-stream")
10async def get(): return EventStream(number_generator())
- 1
- Import the HTMX SSE extension
- 2
- Tell HTMX to load the SSE extension
- 3
-
Look at the
/number-stream
endpoint for SSE content - 4
- When new items come in from the SSE endpoint, add them at the end of the current content within the div. If they go beyond the screen, scroll downwards
- 5
- Specify the name of the event. FastHTML’s default event name is “message”. Only change if you have more than one call to SSE endpoints within a view
- 6
- Set up the asyncio event loop
- 7
-
Don’t forget to make this an
async
function! - 8
- Iterate through the asyncio event loop
- 9
- We yield the data. Data ideally should be comprised of FT components as that plugs nicely into HTMX in the browser
- 10
-
The endpoint view needs to be an async function that returns a
EventStream
Websockets
With websockets we can have bi-directional communications between a browser and client. Websockets are useful for things like chat and certain types of games. While websockets can be used for single direction messages from the server (i.e. telling users that a process is finished), that task is arguably better suited for SSE.
FastHTML provides useful tools for adding websockets to your pages.
from fasthtml.common import *
from asyncio import sleep
1= fast_app(ws_hdr=True)
app, rt
2def mk_inp(): return Input(id='msg', autofocus=True)
@rt('/')
async def get(request):
= Div(
cts id='notifications'),
Div(3id='form', ws_send=True),
Form(mk_inp(), 4='ws', ws_connect='/ws')
hx_extreturn Titled('Websocket Test', cts)
5async def on_connect(send):
print('Connected!')
6await send(Div('Hello, you have connected', id="notifications"))
7async def on_disconnect(ws):
print('Disconnected!')
8@app.ws('/ws', conn=on_connect, disconn=on_disconnect)
9async def ws(msg:str, send):
10await send(Div('Hello ' + msg, id="notifications"))
await sleep(2)
11return Div('Goodbye ' + msg, id="notifications"), mk_inp()
- 1
-
To use websockets in FastHTML, you must instantiate the app with the
ws_hdr
set toTrue
- 2
-
As we want to use websockets to reset the form, we define the
mk_input
function that can be called from multiple locations - 3
-
We create the form and mark it with the
ws_send
attribute, which is documented here in the HTMX websocket specification. This tells HTMX to send a message to the nearest websocket based on the trigger for the form element, which for forms is pressing theenter
key, an action considered to be a form submission - 4
-
This is where the HTMX extension is loaded (
hx_ext='ws'
) and the nearest websocket is defined (ws_connect='/ws'
) - 5
-
When a websocket first connects we can optionally have it call a function that accepts a
send
argument. Thesend
argument will push a message to the browser. - 6
-
Here we use the
send
function that was passed into theon_connect
function to send aDiv
with anid
ofnotifications
that HTMX assigns to the element in the page that already has anid
ofnotifications
- 7
- When a websocket disconnects we can call a function which takes no arguments. Typically the role of this function is to notify the server to take an action. In this case, we print a simple message to the console
- 8
-
We use the
app.ws
decorator to mark that/ws
is the route for our websocket. We also pass in the two optionalconn
anddisconn
parameters to this decorator. As a fun experiment, remove theconn
anddisconn
arguments and see what happens - 9
-
Define the
ws
function as async. This is necessary for ASGI to be able to serve websockets. The function accepts two arguments, amsg
that is user input from the browser, and asend
function for pushing data back to the browser - 10
-
The
send
function is used here to send HTML back to the page. As the HTML has anid
ofnotifications
, HTMX will overwrite what is already on the page with the same ID - 11
-
The websocket function can also be used to return a value. In this case, it is a tuple of two HTML elements. HTMX will take the elements and replace them where appropriate. As both have
id
specified (notifications
andmsg
respectively), they will replace their predecessor on the page.