Templates enable serving HTML pages to users while maintaining separate JSON endpoints for the backend API. This chapter covers setting up Jinja2 templates, passing data to templates, using template syntax for loops and conditionals, implementing template inheritance, adding Bootstrap styling, and configuring static file serving.

Why Templates Matter

Returning raw HTML strings from route functions works for trivial examples, but becomes unmanageable once you need full HTML pages with headers, navigation, footers, and styling. Templates solve this problem by allowing proper HTML files with dynamic data injection.

The architecture maintains clear separation:

  • API routes return JSON for programmatic access
  • page routes return HTML using templates.

Both can use the same underlying data but serve different audiences.

Setting Up Jinja2

When FastAPI is installed with the standard extras (fastapi[standard]), Jinja2 is already included—no additional installation required. Jinja2 is the same templating engine used by Flask, so developers familiar with Flask will recognize the syntax immediately.

If, for any reason, you installed FastAPI without the standard extras, install Jinja2 separately:

pip install jinja2
# or with UV:
uv add jinja2

Begin by importing the required components:

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

The Request object is required by Jinja2 templates. The HTMLResponse import from the previous chapter is no longer needed and can be removed.

Next, create a templates directory in your project root. This is the standard convention in both FastAPI and Flask projects. After creating the application instance, configure the templates object:

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

This creates a templates object that knows to look for template files in the templates directory.

Creating Your First Template

Inside the templates folder, create home.html with a basic HTML structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FastAPI Blog</title>
</head>
<body>
    <h1>Homepage</h1>
    <p>Using a template</p>
</body>
</html>

Update the home route to use this template:

@app.get("/", include_in_schema=False)
@app.get("/posts", include_in_schema=False)
def home(request: Request):
    return templates.TemplateResponse(request, "home.html")

Key changes: The response_class=HTMLResponse parameter is removed. The request parameter is added to the function signature because Jinja2 requires it. The function now returns templates.TemplateResponse() with the request object and template filename.

Passing Data to Templates

Templates become powerful when they receive dynamic data. The TemplateResponse accepts a third argument: a context dictionary containing all variables the template should access.

@app.get("/", include_in_schema=False)
@app.get("/posts", include_in_schema=False)
def home(request: Request):
    return templates.TemplateResponse(
        request,
        "home.html",
        {"posts": posts}
    )

The template can now access anything in this context dictionary.

Jinja2 Template Syntax

Jinja2 uses two primary syntax patterns:

  • Control structures (loops, conditionals): {% ... %}
  • Variable display: {{ ... }}

Looping Through Data

Update home.html to display all posts:

{% for post in posts %}
    <h2>{{ post.title }}</h2>
    <p>{{ post.content }}</p>
{% endfor %}

The {% for post in posts %} loop iterates over the posts list passed in the context. Inside the loop, {{ post.title }} and {{ post.content }} display values using double curly braces.

Important syntax note: Jinja2 allows dot notation for dictionary access. Even though post is a dictionary, post.title works cleanly instead of requiring post['title']. This makes templates more readable.

Conditional Statements

Conditionals control what content appears based on variable values. A common use case is setting dynamic page titles with fallbacks:

<title>
    {% if title %}
        FastAPI Blog - {{ title }}
    {% else %}
        FastAPI Blog
    {% endif %}
</title>

Update the context to pass a title:

return templates.TemplateResponse(
    request,
    "home.html",
    {
        "posts": posts,
        "title": "Home"
    }
)

If a title is provided, it displays as “FastAPI Blog - Home”. Without a title, it defaults to “FastAPI Blog”.

These three constructs—loops, variable display, and conditionals—form the foundation of Jinja2 templating and will be used constantly throughout template development.

Template Inheritance

Template inheritance eliminates code duplication by creating a parent template with common structure that child templates extend. Without inheritance, every page would duplicate the HTML structure, head section, navigation, and footer. Changing a single navigation link would require updates across every template.

Create layout.html as the parent template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
        {% if title %}
            FastAPI Blog - {{ title }}
        {% else %}
            FastAPI Blog
        {% endif %}
    </title>
</head>
<body>
    {% block content %}
    {% endblock content %}
</body>
</html>

The {% block content %} and {% endblock content %} tags define a section called “content” that child templates can override. You can define multiple blocks with different names (sidebar, scripts, etc.) as needed.

Update home.html to extend this layout:

{% extends "layout.html" %}
 
{% block content %}
    {% for post in posts %}
        <h2>{{ post.title }}</h2>
        <p>{{ post.content }}</p>
    {% endfor %}
{% endblock content %}

The home.html template is now dramatically simpler. It extends layout.html and only defines what goes in the content block. The full HTML structure, head section, and conditional title all come from the layout.

Creating additional pages now requires only extending the layout and defining the content block. Structural changes—adding navigation, updating the footer, modifying meta tags—happen once in layout.html and affect all inheriting templates.

Adding Styling with Bootstrap and Static Files

Loading Bootstrap and Custom Styles

While the fundamentals work, the pages still appear plain. Adding Bootstrap provides responsive styling with minimal effort. (Tailwind or other CSS frameworks work equally well.)

Update layout.html to include Bootstrap from a CDN:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 
    <!-- Site Info -->
    {% if title %}
      <title>FastAPI Blog - {{ title }}</title>
    {% else %}
      <title>FastAPI Blog</title>
    {% endif %}
    <meta name="description" content="FastAPI Tutorial">
    <meta name="author" content="Corey Schafer">
 
    <!-- Open Graph Tags: The title of the page for social media sharing. It can match the title tag or be more descriptive. -->
    <meta property="og:title" content="FastAPI Blog">
 
    <!-- Open Graph Tags: Typically set to "website" for static sites or "article" for content-heavy pages. -->
    <meta property="og:type" content="website">
 
    <!-- Open Graph Tags: The URL of the page, used to ensure link previews resolve to the correct page. -->
    <meta property="og:url" content="">
 
    <!-- Open Graph Tags: URL of an image that represents the page. Useful for link previews. -->
    <meta property="og:image" content="">
 
    <!-- Open Graph Tags: Provides an alternative text for the image to improve accessibility. -->
    <meta property="og:image:alt" content="">
 
    <!-- Preconnect for Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
 
    <!-- Custom Font -->
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&family=Nunito:ital,wght@0,200..1000;1,200..1000&display=swap"
          rel="stylesheet">
 
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css"
          rel="stylesheet"
          integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB"
          crossorigin="anonymous">
 
    <!-- Stylesheet -->
    <link rel="stylesheet" type="text/css" href="/static/css/main.css">
 
    <!-- Set a theme color that matches your website's primary color -->
    <meta name="theme-color" content="#527c9f">
 
    <!-- Favicon for all browsers -->
    <link rel="icon" href="/static/icons/favicon.ico" sizes="any">
    <link rel="icon" href="/static/icons/icon.svg" type="image/svg+xml">
 
    <!-- Apple touch icon for iOS devices -->
    <link rel="apple-touch-icon" sizes="180x180" href="/static/icons/icon.png">
    <!-- Web app manifest for Progressive Web Apps -->
    <link rel="manifest" href="/static/site.webmanifest">
 
    <!-- Content Security Policy: Uncomment to enhance security by restricting where content can be loaded from (useful for preventing certain attacks like XSS). Update if adding external sources (e.g., Google Fonts, Bootstrap CDN, analytics, etc). -->
    <!-- <meta http-equiv="Content-Security-Policy" content=" default-src 'self'; script-src 'self' code.jquery.com; style-src 'self' fonts.googleapis.com; font-src fonts.gstatic.com; img-src 'self' images.examplecdn.com; "> -->
  </head>
  <body class="d-flex flex-column min-vh-100">
    <header class="site-header">
      <nav class="navbar navbar-expand-md bg-steel fixed-top"
           data-bs-theme="dark">
        <div class="container">
          <a class="navbar-brand me-4" href="#">FastAPI Blog</a>
          <button class="navbar-toggler"
                  type="button"
                  data-bs-toggle="collapse"
                  data-bs-target="#navbarToggle"
                  aria-controls="navbarToggle"
                  aria-expanded="false"
                  aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarToggle">
            <div class="navbar-nav me-auto">
              <a class="nav-link active" aria-current="page" href="#">Home</a>
            </div>
            <!-- Navbar Right Side -->
            <div class="navbar-nav">
              <a class="btn btn-outline-light mb-2 mb-md-0 me-md-2" href="#">Login</a>
              <a class="btn btn-light mb-2 mb-md-0 me-md-3" href="#">Register</a>
              <div class="nav-item dropdown">
                <a class="nav-link dropdown-toggle"
                   href="#"
                   role="button"
                   id="bd-theme"
                   data-bs-toggle="dropdown"
                   aria-expanded="false">
                  <span id="bd-theme-text">🌗 Auto</span>
                </a>
                <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="bd-theme">
                  <li>
                    <button class="dropdown-item" type="button" data-bs-theme-value="light">🌝 Light</button>
                  </li>
                  <li>
                    <button class="dropdown-item" type="button" data-bs-theme-value="dark">🌚 Dark</button>
                  </li>
                  <li>
                    <button class="dropdown-item" type="button" data-bs-theme-value="auto">🌗 Auto</button>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </nav>
    </header>
 
    <main role="main" class="container">
      <div class="row">
        <div class="col-md-8">
          {% block content %}
          {% endblock content %}
        </div>
        <aside class="col-md-4">
          <div class="content-section py-3 px-4 mb-4">
            <h3>Our Sidebar</h3>
            <p class="text-body-secondary">You can put any information here you'd like.</p>
            <ul class="list-group">
              <li class="list-group-item">Latest Posts</li>
              <li class="list-group-item">Announcements</li>
              <li class="list-group-item">Calendars</li>
              <li class="list-group-item">etc</li>
            </ul>
          </div>
        </aside>
      </div>
    </main>
 
    <footer class="mt-auto py-3 bg-body-tertiary border-top">
      <div class="container text-center">
        <p class="text-body-secondary mb-0">
          © <span id="year"></span> Corey Schafer
        </p>
      </div>
    </footer>
 
    <!-- Set the current year in the footer -->
    <script>document.getElementById('year').textContent = new Date().getFullYear();</script>
 
    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI"
            crossorigin="anonymous"></script>
 
    <!-- Dark Mode Toggle -->
    <script>
      const setTheme = (theme) => {
        if (theme === 'auto') {
          document.documentElement.setAttribute('data-bs-theme', 
            window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
        } else {
          document.documentElement.setAttribute('data-bs-theme', theme);
        }
        localStorage.setItem('theme', theme);
        
        // Update button text
        const themeText = { light: '🌝 Light', dark: '🌚 Dark', auto: '🌗 Auto' };
        document.getElementById('bd-theme-text').textContent = themeText[theme];
      };
 
      // Set theme on click
      document.querySelectorAll('[data-bs-theme-value]').forEach(button => {
        button.addEventListener('click', () => setTheme(button.getAttribute('data-bs-theme-value')));
      });
 
      // Initialize
      setTheme(localStorage.getItem('theme') || 'auto');
    </script>
  </body>
</html>

The custom CSS references /static/css/main.css, which doesn’t exist yet. This leads to the next topic: static file serving.

Configuring Static Files

Static files—CSS, JavaScript, images, and icons—don’t change dynamically and are served as-is. Create a static directory in your project root with subdirectories for organization:

static/
├── css/
│   └── main.css
├── js/
│   └── utils.js
├── icons/
│   └── favicon.ico
└── profile_pics/
    └── default.jpg

Configure FastAPI to serve this directory by importing StaticFiles and mounting the directory:

from fastapi.staticfiles import StaticFiles
 
app.mount("/static", StaticFiles(directory="static"), name="static")

The mount() method takes three arguments:

  1. URL path ("/static"): Where static files will be accessible in the browser
  2. StaticFiles instance (StaticFiles(directory="static")): Points to the static folder
  3. Name (name="static"): Reference name for use in templates

Any file in the static folder is now accessible at /static/ in the browser. For example, static/css/main.css becomes accessible at /static/css/main.css.

Using url_for() in Templates

Hard-coded paths like /static/css/main.css work but aren’t flexible. If you change route paths or the static mount point, every hard-coded link breaks. The url_for() function generates URLs dynamically based on route names, automatically updating when paths change.

Update navigation links in layout.html:

<nav>
    <a href="{{ url_for('home') }}">Home</a>
    <a href="{{ url_for('posts') }}">Posts</a>
</nav>

The url_for() function references the route function name. When multiple decorators point to the same function, explicitly name each route to avoid ambiguity:

@app.get("/", include_in_schema=False, name="home")
@app.get("/posts", include_in_schema=False, name="posts")
def home(request: Request):
    return templates.TemplateResponse(
        request,
        "home.html",
        {"posts": posts, "title": "Home"}
    )

Now url_for('home') generates / and url_for('posts') generates /posts, even though both execute the same function.

For Static Files

Static file references use a slightly different syntax:

<link rel="stylesheet" href="{{ url_for('static', path='css/main.css') }}">

The first argument ('static') matches the name parameter in app.mount(). The path argument specifies the file path within the static directory. This generates /static/css/main.css.

Additional examples:

<!-- Favicon -->
<link rel="icon" href="{{ url_for('static', path='icons/favicon.ico') }}">
 
<!-- Profile picture -->
<img src="{{ url_for('static', path='profile_pics/default.jpg') }}" alt="Profile">
 
<!-- JavaScript -->
<script src="{{ url_for('static', path='js/utils.js') }}"></script>

Critical detail: If url_for() references a route that doesn’t exist, it throws an error. When adding navigation links for routes not yet implemented (login, register), either leave them as placeholder hash symbols (href="#") or wait until those routes are created.

Summary

This chapter established the template foundation for the application. The setup includes a templates directory configured with Jinja2, data passing through context dictionaries, Jinja2 syntax for loops ({% for %}), variable display ({{ }}), and conditionals ({% if %}), template inheritance using layout.html as the parent template to eliminate duplication, Bootstrap integration for responsive styling, a static directory mounted for serving CSS, JavaScript, images, and icons, and url_for() for generating dynamic URLs to routes and static files.

The architecture now cleanly separates the HTML frontend (served via templates) from the JSON backend (served via API routes). Both access the same underlying data but serve different purposes: human-readable pages versus programmatic access.

The next chapter covers URL parameters for retrieving specific resources. Instead of returning all posts at once, path parameters will enable fetching individual posts. This includes creating both API endpoints and template pages for single post views, making homepage posts clickable, and implementing type validation with proper error handling.