Skip to content

Instantly share code, notes, and snippets.

Last active April 3, 2023 22:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
FastAPI with HTMX partials
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<script src=""></script>
body {
background-color: #222;
color: #fff;
font-family: Arial, sans-serif;
table {
border-collapse: collapse;
margin: 20px auto;
width: 80%;
td {
padding: 10px;
text-align: left;
border-bottom: 1px solid #ddd;
th {
background-color: #333;
tr:nth-child(even) {
background-color: #444;
<h1>Sci-Fi Movies</h1>
<button hx-get="/movies" hx-trigger="click" hx-target="#movies" hx-swap="outerHTML">
Get movies table
<div id="movies"></div>
from fastapi import Depends, FastAPI, HTTPException, Query, Request, status
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
async def is_partial_rendering(request: Request):
if "hx-request" in request.headers:
if not request.headers["hx-request"]:
raise HTTPException(
headers={"Location": "/"},
raise HTTPException(
headers={"Location": "/"},
@app.get("/movies", response_class=HTMLResponse)
async def get_movies(
request: Request,
return templates.TemplateResponse("movies.html", {"request": request})
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
<th>Release Year</th>
<th>IMDb Rating</th>
<td>Blade Runner</td>
<td>Ridley Scott</td>
<td>The Matrix</td>
<td>The Wachowskis</td>
<td>Christopher Nolan</td>
<td>Christopher Nolan</td>
<td>James Cameron</td>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment