Full answer
FastAPI is API-first, but it can also render HTML for small sites, admin tools or dashboards.
Setup:
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/students/{roll_no}", response_class=HTMLResponse)
def page(request: Request, roll_no: str):
return templates.TemplateResponse(request, "student.html", {"roll_no": roll_no})(Install jinja2.) In recent Starlette versions the request is the first argument to TemplateResponse; the older TemplateResponse(name, {"request": request, ...}) form is deprecated.
In templates: {{ roll_no }}, loops and conditions with {% for %} and {% if %}, inheritance with {% extends "base.html" %} and blocks, and {{ url_for('static', path='/app.css') }} for assets.
Security and behaviour:
- Autoescaping is on for
.html, so<script>in a student's name renders as text. Mark content safe (|safe) only for HTML you generated yourself. response_class=HTMLResponsesets the content type and makes the OpenAPI docs show HTML.- Templates are cached; in development use
--reloadandauto_reload. - The dependency injection system works the same way: a dependency can supply the current user, and the template receives it in context.
StaticFileshandles ETag and Last-Modified headers and rejects path traversal; in production a CDN or reverse proxy normally serves static files.- For rich interactivity, FastAPI is more often paired with a separate frontend, with Jinja2 kept for emails, reports and admin pages.
import tempfile
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.testclient import TestClient
root = Path(tempfile.mkdtemp())
(root / "static").mkdir()
(root / "templates").mkdir()
(root / "static" / "app.css").write_text("body { color: navy; }")
(root / "templates" / "student.html").write_text(
'<link rel="stylesheet" href="{{ url_for(\'static\', path=\'/app.css\') }}">\n'
"<h1>{{ name }}</h1>\n"
"<ul>{% for s in subjects %}<li>{{ s }}</li>{% endfor %}</ul>"
)
app = FastAPI()
app.mount("/static", StaticFiles(directory=root / "static"), name="static")
templates = Jinja2Templates(directory=root / "templates")
@app.get("/students/{roll_no}", response_class=HTMLResponse)
def page(request: Request, roll_no: str):
return templates.TemplateResponse(request, "student.html",
{"name": "<script>alert(1)</script> Asha", "subjects": ["Maths", "DBMS"]})
c = TestClient(app)
r = c.get("/students/BCA-1")
print(r.status_code, r.headers["content-type"])
print(r.text)
print(c.get("/static/app.css").text, c.get("/static/missing.css").status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install jinja2`; the snippet writes its templates to a temporary folder. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 200 text/html; charset=utf-8 <link rel="stylesheet" href="http://testserver/static/app.css"> <h1><script>alert(1)</script> Asha</h1> <ul><li>Maths</li><li>DBMS</li></ul> body { color: navy; } 404
Key points
- Jinja2Templates plus TemplateResponse render HTML
- Mount StaticFiles for assets
- Autoescaping protects from XSS; avoid |safe on user input
- Pass request first in recent Starlette versions
- Serve static files from a CDN or proxy in production
Common mistakes
- Using |safe on user-supplied text
- Using the deprecated TemplateResponse(name, {'request': request}) call style
- Serving static files through Python in production at scale
- Forgetting to install jinja2
- Trying to build a heavy interactive UI only with Jinja2
Follow-ups
- How would you pass the current user to every template?
- How does FastAPI serve HTML differently from JSON in OpenAPI?
- How do you cache templates in production?
Tips
- Show setup in three lines
- Mention autoescape
- Say CDN in production