How to Use Jinja2 with FastAPI: Simple Template Rendering
To use
jinja2 with fastapi, install jinja2 and fastapi[all], then create a Jinja2Templates instance pointing to your templates folder. Use TemplateResponse in your route handlers to render HTML pages with dynamic data.Syntax
Here is the basic syntax to use Jinja2 templates in FastAPI:
Jinja2Templates(directory='templates'): Creates a template engine pointing to the folder with your HTML files.TemplateResponse('template.html', {'request': request, 'key': value}): Renders the template with data and returns an HTML response.requestmust be passed to the template for URL generation and other FastAPI features.
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, 'message': 'Hello from FastAPI!'})
Example
This example shows a complete FastAPI app rendering a Jinja2 template named index.html with a message passed from the backend.
Create a folder named templates in your project root and add index.html with 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): return templates.TemplateResponse('index.html', {'request': request, 'title': 'Welcome', 'user': 'Alice'})
Common Pitfalls
- Not passing the
requestobject to the template context causes runtime errors because Jinja2Templates expects it. - Forgetting to set
response_class=HTMLResponsein the route can cause FastAPI to return JSON instead of HTML. - Incorrect template folder path or missing template files will raise template not found errors.
- Using synchronous file operations or blocking code inside async routes 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(): return templates.TemplateResponse('index.html', {'title': 'Oops'}) # Right: include request @app.get('/right', response_class=HTMLResponse) async def right(request: Request): return templates.TemplateResponse('index.html', {'request': request, 'title': 'Fixed'})
Quick Reference
Remember these key points when using Jinja2 with FastAPI:
- Install with
pip install fastapi[all]orpip install jinja2. - Use
Jinja2Templates(directory='templates')to set template folder. - Always pass
requestin the context dictionary. - Use
TemplateResponseto return rendered HTML. - Set
response_class=HTMLResponsein your route decorator.
Key Takeaways
Always pass the request object to Jinja2 templates for proper rendering.
Use TemplateResponse with response_class=HTMLResponse to serve HTML pages.
Keep your templates in a dedicated folder and point Jinja2Templates to it.
Check template paths and names carefully to avoid file not found errors.
Install Jinja2 and FastAPI dependencies before using templates.