htmx Core Attributes
| Attribute | Description | Example |
|---|---|---|
hx-get |
GET request on trigger | hx-get="/api/data" |
hx-post |
POST request | hx-post="/api/chat" |
hx-target |
Where to put response | hx-target="#results" |
hx-swap |
How to insert response | hx-swap="innerHTML" |
hx-trigger |
When to fire | hx-trigger="click" |
hx-indicator |
Loading spinner | hx-indicator="#spinner" |
AI Chat with htmx + FastAPI
<form hx-post="/chat" hx-target="#messages" hx-swap="beforeend" hx-indicator="#loading">
<input name="prompt" placeholder="Ask anything..." autocomplete="off">
<button>Send</button>
<span id="loading" class="htmx-indicator">Thinking...</span>
</form>
<div id="messages"></div># FastAPI backend
from fastapi import FastAPI, Form
from fastapi.responses import HTMLResponse
import openai
app = FastAPI()
@app.post("/chat", response_class=HTMLResponse)
async def chat(prompt: str = Form()):
response = openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
answer = response.choices[0].message.content
return f'<div class="message"><b>You:</b> {prompt}</div><div class="message"><b>AI:</b> {answer}</div>'Swap Strategies
hx-swap="innerHTML" <!-- Replace inner HTML -->
hx-swap="outerHTML" <!-- Replace entire element -->
hx-swap="beforeend" <!-- Append inside -->
hx-swap="afterend" <!-- Insert after -->
hx-swap="delete" <!-- Remove element -->
hx-swap="none" <!-- No DOM update -->Triggers
hx-trigger="click" <!-- On click (default for buttons) -->
hx-trigger="submit" <!-- On form submit -->
hx-trigger="keyup changed delay:500ms" <!-- Debounced search -->
hx-trigger="revealed" <!-- When scrolled into view -->
hx-trigger="every 5s" <!-- Polling -->
hx-trigger="sse:message" <!-- Server-sent events -->SSE for Streaming AI
<div hx-ext="sse" sse-connect="/stream" sse-swap="message">
<!-- Streaming AI response appears here -->
</div>FAQ
Q: What is htmx? A: htmx is a 14KB library with 47,700+ GitHub stars that adds AJAX, WebSockets, and CSS transitions to HTML via attributes — no JavaScript framework required.
Q: Why use htmx for AI tools? A: AI backends (Python/Go) do the heavy lifting. htmx lets you build dynamic UIs that talk to your backend without a JavaScript build step. Perfect for AI demos, internal tools, and prototypes.
Q: Is htmx free? A: Yes, open-source under BSD-2-Clause license.