FastHTML Tutorial: Build and Deploy a Python Guestbook App
FastHTML builds a Python web app without a separate frontend: routes and HTML components live in the same file, and HTMX handles the interactivity. This tutorial builds a digital guestbook, styles it with Pico CSS, stores the messages in a Supabase Postgres database and deploys it to Vercel, without writing any JavaScript.
Table of contents
Install and run
FastHTML installs with pip as python-fasthtml. Save the example from the FastHTML documentation as main.py and start it with Python; the server runs on port 5001.
pip install python-fasthtml
from fasthtml.common import *
app, rt = fast_app()
@rt("/")
def get():
return Div(P("Hello World!"), hx_get="/change")
serve()
python main.py
INFO: Uvicorn running on http://0.0.0.0:5001 (Press CTRL+C to quit)
INFO: Started reloader process [20424] using WatchFiles
INFO: Started server process [24424]
INFO: Waiting for application startup.
INFO: Application startup complete.
The log shows 0.0.0.0, which listens on every address. If the browser cannot open that address, use http://localhost:5001.
How FastHTML works
FastHTML is built on Starlette, the toolkit FastAPI also runs on, and HTMX, which adds interactivity through HTML attributes instead of JavaScript. Each route is a Python function that returns HTML components such as Div and P.
In the example, fast_app() creates the app and the router (rt). The root route returns a div with a paragraph, and its hx_get="/change" attribute is HTMX: clicking the div requests the /change route, which does not exist yet.
Adding that route makes the click swap in the new paragraph without reloading the page. Wrapping the content in Titled adds a title and applies Pico CSS, the styling library FastHTML loads by default. You can use another CSS library such as Tailwind instead.
from fasthtml.common import *
app, rt = fast_app()
@rt("/change")
def get():
return P("Nice to be here!")
@rt("/")
def get():
return Titled(Div(P("Hello World!"), hx_get="/change"))
serve()
With a regular link instead of the HTMX attribute, the click navigates to the other page and the URL changes, which is how you build a multi-page app. The same idea in Streamlit is covered in my multipage web app tutorial.
The guestbook form
The guestbook needs a form with a name field, a message field and a submit button. I build it in a separate function instead of inside the route, which keeps the route short. role="group" comes from the “Usage with group” example in the Pico documentation and puts the inputs and the button on one line.
from fasthtml.common import *
MAX_NAME_CHAR = 15
MAX_MESSAGE_CHAR = 50
app, rt = fast_app()
def render_content():
form = Form(
Fieldset(
Input(
type="text",
name="name",
placeholder="Name",
required=True,
maxlength=MAX_NAME_CHAR,
),
Input(
type="text",
name="message",
placeholder="Message",
required=True,
maxlength=MAX_MESSAGE_CHAR,
),
Button("Submit", type="submit"),
role="group",
)
)
The full render_content function, including what it returns, follows in the form submission step below.
The Supabase database
The messages live in a Postgres database on Supabase, which has a free plan. Create an account, an organization and a project, then a table called MyGuestbook with the default id column plus three text columns: name, message and timestamp.
Copy the project URL and API key into a .env file as SUPABASE_URL and SUPABASE_KEY, and install the Supabase Python client with python-dotenv and pytz:
pip install supabase python-dotenv pytz
Read the messages
The script loads the environment variables, creates the Supabase client and reads all messages, newest first. Each message renders as a Pico article card, and the list gets the id message-list so HTMX can replace it later.
import os
from fasthtml.common import *
from supabase import create_client, Client
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
MAX_NAME_CHAR = 15
MAX_MESSAGE_CHAR = 50
# Initialize Supabase client
supabase = create_client(os.getenv("SUPABASE_URL"), os.getenv("SUPABASE_KEY"))
app, rt = fast_app()
def get_messages():
# Sort by 'id' in descending order to get the latest entries first
response = (
supabase.table("MyGuestbook").select("*").order("id", desc=True).execute()
)
return response.data
def render_message(entry):
return (
Article(
Header(f"Name: {entry['name']}"),
P(entry["message"]),
Footer(Small(Em(f"Posted: {entry['timestamp']}"))),
),
)
def render_message_list():
messages = get_messages()
return Div(
*[render_message(entry) for entry in messages],
id="message-list",
)
Save a message
add_message stamps the entry with the current time in CET and inserts it into the table.
from datetime import datetime
import pytz
MAX_NAME_CHAR = 15
MAX_MESSAGE_CHAR = 50
TIMESTAMP_FMT = "%Y-%m-%d %I:%M:%S %p CET"
def get_cet_time():
cet_tz = pytz.timezone("CET")
return datetime.now(cet_tz)
def add_message(name, message):
timestamp = get_cet_time().strftime(TIMESTAMP_FMT)
supabase.table("MyGuestbook").insert(
{"name": name, "message": message, "timestamp": timestamp}
).execute()
Handle the form submission
When someone submits the form, HTMX posts it to /submit-message. That route saves the message and returns a fresh message list, which replaces only the old list on the page. The form then resets itself.
def render_content():
form = Form(
Fieldset(
Input(
type="text",
name="name",
placeholder="Name",
required=True,
maxlength=MAX_NAME_CHAR,
),
Input(
type="text",
name="message",
placeholder="Message",
required=True,
maxlength=MAX_MESSAGE_CHAR,
),
Button("Submit", type="submit"),
role="group",
),
method="post",
hx_post="/submit-message", # Send a POST request to the /submit-message endpoint
hx_target="#message-list", # Only swap the message list
hx_swap="outerHTML", # Replace the entire content of the target element with the response
hx_on__after_request="this.reset()", # Reset the form after submission
)
return Div(
P(Em("Write something nice!")),
form,
Div(
"Made with ❤️ by ",
A("Sven", href="https://youtube.com/@codingisfun", target="_blank"),
),
Hr(),
render_message_list(),
)
@rt("/")
def get():
return Titled("My Guestbook 📖", render_content())
@rt("/submit-message", methods=["POST"])
def post(name: str, message: str):
add_message(name, message)
return render_message_list()
Favicon
For the browser tab icon, put a PNG in an assets folder and add a link to it in the headers of fast_app().
app, rt = fast_app(
hdrs=(Link(rel="icon", type="image/png", href="/assets/favicon.png"),),
)
The repository code sets type="assets/x-icon". That is not a valid MIME type; image/png is the correct one for a PNG file.
Deploy to Vercel
Vercel deploys the app straight from a GitHub repository. Initialize a git repository, add a .gitignore that excludes the .env file, add a requirements.txt and push the code to GitHub. This is the requirements file from the repository:
python-dotenv==1.0.1
python_fasthtml==0.4.5
pytz==2022.1
supabase==2.7.3
sqlite-minutils
Those pins are the versions from the recording. FastHTML changes quickly, so if you start fresh, install the current releases and pin what works for you.
In Vercel, create a new project, select the repository, enter SUPABASE_URL and SUPABASE_KEY as environment variables and click Deploy. Then submit a test message on the live site.

If you would rather stay in Streamlit, the same idea of a form that saves to a database is in my Streamlit data entry form for Google Sheets.
