Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

Chapter 13: Creating a Website with Templates

ASP.NET Core offers Razor Pages and MVC views. FastAPI does not include a page framework, but Starlette supports Jinja2 templates.

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

router = APIRouter()
templates = Jinja2Templates(directory="templates")


@router.get("/recipes", response_class=HTMLResponse)
def recipes_index(request: Request):
    recipes = recipes_service.list_public_recipes()
    return templates.TemplateResponse(
        "recipes/index.html",
        {"request": request, "recipes": recipes},
    )

Python template guidance:

If you want a deeply integrated server-rendered framework, Django is usually the better Python choice. FastAPI plus Jinja2 is excellent when your app is API-first and needs some server-rendered pages.