How to Use Templates in FastAPI: Simple Guide with Examples
In FastAPI, you use
Jinja2Templates from fastapi.templating to render HTML templates dynamically. You create a Templates instance pointing to your templates folder, then return TemplateResponse with the request and data to render the template.Syntax
To use templates in FastAPI, you first import Jinja2Templates and create an instance with the directory of your HTML files. Then, in your path operation function, you return a TemplateResponse passing the template name, the request object, and any data you want to show in the template.
- Jinja2Templates(directory="templates"): sets the folder where your HTML templates live.
- TemplateResponse(template_name, context): renders the HTML template with the given context data.
- request: must be included in the context for template rendering.
python
from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates from fastapi.responses import HTMLResponse app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def read_root(request: Request): return templates.TemplateResponse("index.html", {"request": request, "data": "Hello, FastAPI!"})
Example
This example shows a FastAPI app rendering a simple HTML page using a template. The template receives a message and displays it inside an <h1> tag.
You need a folder named templates with a file index.html containing Jinja2 syntax.
python
from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates from fastapi.responses import HTMLResponse app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def home(request: Request): message = "Welcome to FastAPI Templates!" return templates.TemplateResponse("index.html", {"request": request, "message": message})
Output
When you visit http://localhost:8000/ you see a webpage with the text "Welcome to FastAPI Templates!" inside an <h1> tag.
Common Pitfalls
- Forgetting to include
requestin the context dictionary causes template rendering errors. - Not setting
response_class=HTMLResponsein the route decorator can lead to incorrect content type. - Placing templates outside the specified directory will cause file not found errors.
- Using synchronous file operations or blocking code inside async functions can slow down your app.
python
from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates from fastapi.responses import HTMLResponse app = FastAPI() templates = Jinja2Templates(directory="templates") # Wrong: missing 'request' in context @app.get("/wrong", response_class=HTMLResponse) async def wrong(request: Request): return templates.TemplateResponse("index.html", {"message": "Oops!"}) # Right: include 'request' @app.get("/right", response_class=HTMLResponse) async def right(request: Request): return templates.TemplateResponse("index.html", {"request": request, "message": "Fixed!"})
Quick Reference
Remember these key points when using templates in FastAPI:
- Use
Jinja2Templates(directory="templates")to set your templates folder. - Always pass
requestin the context dictionary. - Return
TemplateResponsewith template name and context. - Set
response_class=HTMLResponsein your route decorator. - Keep templates in the specified directory for easy management.
Key Takeaways
Use Jinja2Templates to load templates from a folder in FastAPI.
Always include the request object in the template context.
Return TemplateResponse with template name and data to render HTML.
Set response_class=HTMLResponse to serve HTML content correctly.
Keep your templates organized in the specified directory.