FastAPI and HTMX: Building Interactive UIs Without a JS Framework

How FastAPI and HTMX pair together to build dynamic, interactive web apps using server-rendered HTML instead of a JavaScript frontend framework

FastAPI is usually reached for as a JSON API backend paired with a separate React or Vue frontend. HTMX offers a genuinely different path: skip the separate frontend framework entirely, and let FastAPI return HTML fragments directly.

The core idea

HTMX lets HTML attributes trigger AJAX requests, WebSocket connections, and server-sent events, then swap the response directly into the page — no client-side JavaScript framework, no separate build step, no API contract to maintain between a frontend and backend repo. FastAPI, instead of returning JSON, returns HTML fragments (via Jinja2Templates or similar) that HTMX swaps into the DOM.

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.get("/search")
async def search(request: Request, q: str = ""):
    results = run_search(q)
    return templates.TemplateResponse(
        "results.html", {"request": request, "results": results}
    )
<input
	type="text"
	name="q"
	hx-get="/search"
	hx-trigger="keyup changed delay:300ms"
	hx-target="#results"
/>
<div id="results"></div>

That’s a live search box with no client-side JavaScript written by you at all — HTMX handles the request and DOM swap, FastAPI handles rendering the fragment.

Why this combination specifically

FastAPI’s speed and async support make it well suited to handling frequent small HTMX requests (every keystroke, every partial page update) without the overhead a heavier synchronous framework would add. And FastAPI’s dependency injection and Pydantic validation apply just as well to HTML-returning routes as JSON ones — you’re not giving up FastAPI’s core strengths by not returning JSON.

When this approach makes sense

Internal tools, admin dashboards, and content-heavy apps where you want interactivity (live search, inline editing, infinite scroll) without committing to a full SPA build pipeline. It’s a poor fit for apps that genuinely need complex client-side state management, offline support, or a native mobile app sharing the same frontend logic — that’s still React/Vue territory.

Django works too, FastAPI isn’t required

HTMX is backend-agnostic — it pairs just as naturally with Django, and Django’s templating is arguably more mature for this pattern. Reach for FastAPI+HTMX specifically when you also want FastAPI’s async performance or are already using FastAPI for a JSON API and want to add a lightweight admin UI without adopting a second framework.

TopicsWeb FrameworksHTMXExplainer