Skip to main content

Overview

FastAPI supports rendering HTML templates using Jinja2, a powerful and widely-used templating engine. This is useful when you need to return HTML pages instead of JSON responses, such as building admin interfaces, documentation pages, or server-side rendered applications.

Installation

First, install Jinja2 and the additional dependencies for serving static files:
Jinja2 is the same template engine used by Flask, so if you’re familiar with Flask templates, you’ll feel right at home.

Basic Setup

Here’s a complete example showing how to set up Jinja2 templates with FastAPI:

Project Structure

Your project should have the following structure:

Creating Templates

Basic Template

Create a file templates/item.html:
Use url_for() to generate URLs for your routes and static files. This ensures your URLs remain correct even if you change your route paths.

Template Context

Pass data to your templates using the context parameter:
Always include the request object in your context, even if you don’t use it directly in the template. Some Jinja2 features require it.

Advanced Template Features

Template Inheritance

Create a base template templates/base.html:
Extend it in templates/page.html:

Conditional Rendering

Loops

Jinja2 supports many Python-like features including filters, macros, and includes. Check the Jinja2 documentation for the complete feature set.

Custom Filters

Add custom Jinja2 filters to your templates:
Use it in your template:

Serving Static Files

Static files like CSS, JavaScript, and images should be served from a dedicated directory:
Reference them in templates:

Error Pages

Create custom error pages:

Best Practices

Escape User Input

Jinja2 auto-escapes HTML by default, but be careful when using |safe filter or {% autoescape false %}.

Organize Templates

Use subdirectories for different sections: templates/admin/, templates/public/, etc.

Cache Templates

In production, templates are automatically cached. Set auto_reload=False for better performance.

Separate Concerns

Keep business logic in Python and presentation logic in templates.

Performance Considerations

Disable auto_reload in production to avoid the performance overhead of checking for template changes on every request.

Testing Templates

Test your template endpoints using FastAPI’s test client: