Skip to content

Instantly share code, notes, and snippets.

@tiagocoutinho
Created June 11, 2025 08:18
Show Gist options
  • Save tiagocoutinho/7c53ef564a4a8b69020e58b1e39230fb to your computer and use it in GitHub Desktop.
Save tiagocoutinho/7c53ef564a4a8b69020e58b1e39230fb to your computer and use it in GitHub Desktop.
HTMX + FastAPI
from functools import partial
from typing import Annotated
from fastapi import responses, FastAPI, Form
FormField = Annotated[str, Form()]
app = FastAPI()
get_html = partial(app.get, response_class=responses.HTMLResponse)
put_html = partial(app.put, response_class=responses.HTMLResponse)
PAGE = """\
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/dist/htmx.min.js" defer></script>
</head>
<body style="font-size:1.5rem;">
<h1>HTMX Demo!</h1>
{view}
</body>
</html>"""
VIEW = """\
<div hx-target="this" hx-swap="outerHTML">
<div><label>First Name</label>: {firstName}</div>
<div><label>Last Name</label>: {lastName}</div>
<div><label>Email</label>: {email}</div>
<br/>
<button hx-get="/contact/{user_id}/edit">Click To Edit</button>
</div>"""
EDIT = """\
<form hx-put="/contact/{user_id}" hx-target="this" hx-swap="outerHTML">
<div><label>First Name: </label><input type="text" name="firstName" value="{firstName}"></div>
<div><label>Last Name: </label><input type="text" name="lastName" value="{lastName}"></div>
<div><label>Email Address: </label><input type="email" name="email" value="{email}"></div>
<br/>
<button>Submit</button>
<button hx-get="/contact/{user_id}">Cancel</button>
</form>"""
USERS = {
1: dict(firstName="John", lastName="Doe", email="[email protected]")
}
def view(user_id):
return VIEW.format(user_id=user_id, **USERS[user_id])
@get_html("/")
def index():
return PAGE.format(view=view(1))
@get_html("/contact/{user_id}/edit")
def edit(user_id: int):
return EDIT.format(user_id=user_id, **USERS[user_id])
@get_html("/contact/{user_id}")
def contact(user_id: int):
return view(user_id)
@put_html("/contact/{user_id}")
def update_contact(user_id: int, firstName: FormField, lastName: FormField, email: FormField):
USERS[user_id] = dict(firstName=firstName, lastName=lastName, email=email)
return view(user_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment