๐Ÿ“ Fastapi

HTML sites with FastAPI: Jinja, static files, and forms

P
Author
PyLand Team
๐Ÿ“…
Published
18.09.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
3
๐ŸŒฟ
Level
Medium

FastAPI can return more than JSON. Jinja2Templates renders HTML, while
StaticFiles serves CSS and images. A regular HTML form uses
application/x-www-form-urlencoded; a file form uses multipart/form-data.

This is useful when a separate frontend is unnecessary: FastAPI reads data, Jinja
places it into a template, and the browser receives complete HTML. Forms send changes
back to the same application.

A small site needs only templates, static, and GET/POST routes. Render one page
successfully first, then connect its form.

Build paths relative to the application file, not the shell working directory:

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

BASE_DIR = Path(__file__).resolve().parent
app = FastAPI()
app.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static")
templates = Jinja2Templates(directory=BASE_DIR / "templates")

@app.get("/")
def home(request: Request):
    return templates.TemplateResponse(
        request=request, name="index.html", context={"projects": []}
    )

Use {{ url_for('static', path='/style.css') }} in the template. Accept fields with
Form, keep <input name> values aligned with route parameters, add
enctype="multipart/form-data" for files, and redirect with 303 after a successful
POST. Browser validation helps users, but the server must validate every field again.

The friendly GET โ†’ POST โ†’ redirect cycle

  1. GET displays the form and current data.
  2. POST validates fields and saves changes.
  3. On failure, render the form again with a useful explanation.
  4. On success, return a 303 redirect to a GET page.

This prevents a browser refresh from submitting the form twice. If CSS is missing,
open DevTools โ†’ Network: a 404 usually points to a wrong directory or mount name.

Official documentation

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

SQLModel CRUD in FastAPI

SQLModel combines SQLAlchemy and Pydantic โ€” a single model for both the database and the...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 403
๐Ÿ“

Middleware and CORS in FastAPI

Middleware processes requests and responses around FastAPI routes, while CORS controls which browser origins may...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 434
๐Ÿ“

HTTPException in FastAPI

Covered topics: Basic Usage, Status Codes, Error Details, Custom Headers.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 371

Did you like the article?

Subscribe to our updates and be the first to receive new articles. Grow with PyLand!