Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 50 ยท Responses, errors and docs

Jinja2 templates and static files

Serve HTML pages from FastAPI with Jinja2Templates and TemplateResponse, mount a StaticFiles directory, loop and branch in templates, and build a form-based to-do page.

FastAPI is famous for JSON APIs, but it is also a perfectly good web server for pages. An admin screen, a landing page, or a tiny internal tool is often easier to build as server-rendered HTML than as a separate front end. FastAPI (through Starlette) gives you two tools for that: Jinja2 templates to turn data into HTML, and StaticFiles to serve CSS, JavaScript and images.

In this lesson you will render a template, use loops and conditions inside it, serve a static directory, and finish with a small to-do page driven by an HTML form. Everything runs in the browser here: the template files are written to the sandbox's virtual disk, and the app is called in-process like in the other lessons.

Two pieces of a server-rendered page

Templates HTML with holes for your data.
Static files CSS, JS and images, served as-is.
Your endpoint Picks data, picks a template.
1 / 2

Setting up Jinja2Templates

Install Jinja2 (pip install jinja2, or pip install "fastapi[standard]", which includes it). Then point Jinja2Templates at a folder that holds your template files:

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

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

@app.get("/hello/{name}")
async def hello(request: Request, name: str):
    return templates.TemplateResponse(
        request=request,
        name="hello.html",
        context={"name": name},
    )

Three details matter:

  • The endpoint receives the Request object, and you hand it to TemplateResponse. Templates need it to build URLs (more on that below).
  • context is a plain dictionary. Every key becomes a variable inside the template.
  • The response class is HTML, so FastAPI sets Content-Type: text/html. If you want the /docs page to show it that way, add response_class=HTMLResponse to the decorator. It is optional for the page to work.

Old tutorials show TemplateResponse("hello.html", {"request": request, "name": name}). Current Starlette versions prefer the keyword form above, with request as its own argument, and the old form is deprecated.

Template syntax in five minutes

Jinja2 templates are ordinary HTML plus three kinds of markers:

  • {{ expression }} prints a value. Output is HTML-escaped by default, so a name like <script> appears as text, not as code. This is your protection against cross-site scripting.
  • {% statement %} runs logic: if, for, set, include, extends.
  • {# comment #} is a comment that never reaches the browser.

Filters transform values with a pipe: {{ title|upper }}, {{ price|round(2) }}, {{ items|length }}.

Python Render a template with loops and conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice three things in the output: the loop counter and cycle helper from the special loop variable, the {% else %} branch for an empty list, and the owner note. The note contained <b> tags, but they were escaped to &lt;b&gt;, so a visitor's text can never inject markup.

Template inheritance

Real sites repeat a header, a footer and the same <head> on every page. Put that in one base template with named blocks, and let child templates fill them:

HTML
<!-- templates/base.html -->
<!doctype html>
<html lang="en">
<head>
  <title>{% block title %}My site{% endblock %}</title>
  <link rel="stylesheet" href="{{ url_for('static', path='site.css') }}">
</head>
<body>
  <nav>...</nav>
  <main>{% block content %}{% endblock %}</main>
</body>
</html>

<!-- templates/page.html -->
{% extends "base.html" %}
{% block title %}Welcome{% endblock %}
{% block content %}<h1>Welcome, {{ name }}</h1>{% endblock %}

extends must be the first thing in the child, and anything outside a {% block %} in a child is ignored.

Serving static files

CSS, images and browser JavaScript do not need an endpoint. Mounting a StaticFiles app at a path serves a whole directory:

Python
from fastapi.staticfiles import StaticFiles

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

A request for /static/site.css now returns the file static/site.css. The name="static" is what lets templates build links with url_for('static', path='site.css') instead of hard-coding the prefix. That matters when your app later lives under a different path, for example behind a proxy.

Mounts are matched by path prefix and are not part of the OpenAPI document, so static files never clutter /docs. Read more about mounting in Mounting sub-apps and static directories.

StaticFiles raises an error at startup if the directory does not exist (check_dir=True is the default). Create the directory first, even if it is empty. In production, let nginx or a CDN serve static files and keep StaticFiles for development and small apps.

A form-driven to-do page

Now combine everything. The page lists tasks, has a form to add one, and each task has a button to complete it. The pattern is the classic Post/Redirect/Get: a form POST changes data and answers with a redirect, so refreshing the page does not submit the form again.

Reading form fields needs python-multipart (pip install python-multipart); the forms lesson shows Form(...) on its own.

Python To-do page with a form, a redirect and a static mount

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the details. 303 See Other tells the browser to follow up with a GET, which is the right status after a successful form POST (a plain 307 would repeat the POST). The url_for('static', ...) call produced the full URL of the CSS file, and the <my> in the new task was escaped in the page. (Serving the CSS file itself is the one thing we cannot show live: StaticFiles reads the disk in worker threads, and the browser sandbox has none. On a real server, /static/todo.css simply returns the file.) The app keeps tasks in a list; a real one would use a database.

Template tips

  • Reuse the templates object. Create one Jinja2Templates at import time, not per request. It caches compiled templates.
  • Add custom filters with templates.env.filters["money"] = my_function, or global values with templates.env.globals["site_name"] = "Acme".
  • Use |safe sparingly. It turns escaping off for one value. Only use it for HTML you generated yourself, never for user input.
  • Pages and API together. The same app can serve / as HTML and /api/tasks as JSON. Add include_in_schema=False to HTML endpoints to hide them from the docs.
  • Interactivity. For sprinkles of dynamic behaviour, many teams add htmx or Alpine.js. For rich client apps, keep the API and build a separate front end.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does {{ value }} do with HTML characters in value by default in Jinja2?

    Autoescaping is on, which protects pages against injected markup. Use |safe only for trusted HTML.
  2. 2. Why do you pass request to TemplateResponse?

    Jinja2Templates uses the request to resolve routes and the app's URL structure inside templates.
  3. 3. What does app.mount("/static", StaticFiles(directory="static"), name="static") do?

    A mount serves a whole directory by path prefix, and the name lets url_for('static', path=...) build links.
  4. 4. After a successful form POST, which redirect status makes the browser follow up with a GET?

    303 See Other always switches to GET. That is the Post/Redirect/Get pattern, which avoids duplicate submissions on refresh.

Summary

  • Jinja2Templates(directory=...) plus TemplateResponse(request=..., name=..., context=...) renders HTML pages.
  • Templates use {{ }} for values (auto-escaped), {% %} for if/for/extends/block, and filters such as |length.
  • Base templates and {% block %} remove repeated layout code.
  • app.mount("/static", StaticFiles(...), name="static") serves CSS, JS and images; url_for('static', path=...) links to them.
  • Form posts should end with a 303 redirect (Post/Redirect/Get).
  • Keep JSON APIs and HTML pages in one app when it helps, and hide pages from the docs with include_in_schema=False.

Next: Mounting sub-apps and static directories goes deeper on app.mount.