~/wiki

FastAPI Web Development

Mis à jour le 2026-04-22Confiance : high
fastapiweb-developmentpython-backendapi-developmenttemplate-renderinghtmx-integrationself-hosted-deployment

Modern Python web framework enabling rapid development of both APIs and web interfaces. Excellent choice for projects requiring unified backend architecture serving both data endpoints and HTML interfaces.

Core Architecture Pattern

FastAPI excels at serving both API endpoints and HTML templates from a single application:

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

app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/")
def listings_page(request: Request):
    return templates.TemplateResponse("listings.html", {"request": request})

@app.get("/api/listings")
def api_listings():
    return {"listings": get_listings()}

HTMX Integration

FastAPI pairs excellently with HTMX for interactive interfaces without JavaScript complexity:

<form hx-post="/update-criteria" hx-target="#results">
    <input name="max_budget" value="700000">
    <button type="submit">Update Search</button>
</form>

<div id="results">
    <!-- Results updated via HTMX -->
</div>

Backend handles partial page updates:

@app.post("/update-criteria")
def update_criteria(request: Request, max_budget: int):
    # Update search criteria
    # Return partial HTML for #results div
    return templates.TemplateResponse("listing_cards.html", 
                                    {"request": request, "listings": filtered_listings})

Self-Hosted Deployment

FastAPI's built-in Uvicorn server makes self-hosting simple:

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Benefits for personal/family projects:

  • Zero deployment complexity
  • Direct local network access (http://macmini.local:8000)
  • Integrated with background tasks (schedulers, scrapers)
  • Full control over data and privacy

Unified Architecture Benefits

Single FastAPI application can handle:

  • Web interface serving
  • Background task scheduling
  • Database operations
  • External API integration
  • File upload/download
  • WebSocket connections

This eliminates need for separate frontend/backend deployment and simplifies maintenance.

Template and Static File Organization

project/
├── main.py              # FastAPI app
├── templates/           # Jinja2 templates
│   ├── base.html       # Base template
│   ├── listings.html   # Main pages
│   └── components/     # Reusable components
├── static/             # CSS, JS, images
│   ├── css/
│   └── images/
└── models/             # Data models

See also

  • HTMX Interactive Interfaces
  • Self-Hosted Deployment Strategy
  • Python Backend Patterns
  • Template Rendering Systems