π¨ FastAPI Templates & Static Files
The Art Gallery of Your Web App
The Story: Your Web App is Like an Art Gallery
Imagine youβre building an art gallery.
- The paintings on the walls? Those are your HTML templates β the beautiful pages visitors see.
- The frames, lighting, and decorations? Those are your static files β CSS styles, images, and JavaScript.
Without templates, your gallery has no art to show. Without static files, everything looks plain and boring. Together, they make your gallery stunning!
πΌοΈ Part 1: Template Rendering
Painting Pictures for Your Visitors
What is Template Rendering?
Think of a template like a coloring book page.
The page has outlines (the structure), but you fill in different colors each time (the data). Same page, different results!
Simple Example:
Hello, _____ !
Welcome to _____ !
You fill in the blanks with different names and places. Thatβs exactly what template rendering does!
Why Use Templates?
β Without templates (Hard Way):
return "<h1>Hello John!</h1>"
return "<h1>Hello Sara!</h1>"
return "<h1>Hello Mike!</h1>"
# Writing HTML for every person? No way!
β With templates (Easy Way):
# One template, endless possibilities!
return template("hello.html", name=user)
Setting Up Jinja2 Templates
FastAPI uses Jinja2 β think of it as your magic paintbrush!
Step 1: Install the magic brush
pip install jinja2
Step 2: Create your templates folder
my_app/
βββ main.py
βββ templates/
βββ hello.html
Step 3: Connect FastAPI to templates
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
# Point to your templates folder
templates = Jinja2Templates(
directory="templates"
)
Your First Template
templates/hello.html:
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<p>Welcome to {{ place }}!</p>
</body>
</html>
See those {{ }} curly braces? Thatβs where the magic happens! Theyβre like blank spaces waiting to be filled.
@app.get("/greet/{name}")
async def greet(request: Request, name: str):
return templates.TemplateResponse(
"hello.html",
{
"request": request,
"name": name,
"place": "FastAPI Land"
}
)
Visit /greet/Emma and see:
Hello, Emma! Welcome to FastAPI Land!
Template Magic Tricks πͺ
graph TD A["π¨ Template File"] --> B{Jinja2 Engine} C["π Your Data"] --> B B --> D["β¨ Beautiful HTML Page"]
Trick 1: Loops β Show Many Items
Show a shopping list:
<ul>
{% for item in shopping_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Python:
return templates.TemplateResponse(
"list.html",
{
"request": request,
"shopping_list": ["Apples", "Bread", "Milk"]
}
)
Trick 2: Conditions β Show or Hide
{% if user_logged_in %}
<p>Welcome back, {{ username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
Trick 3: Filters β Transform Data
<!-- Make text uppercase -->
<h1>{{ title | upper }}</h1>
<!-- Format numbers -->
<p>Price: ${{ price | round(2) }}</p>
<!-- Default values -->
<p>Hello, {{ name | default("Guest") }}!</p>
The Request Object β Always Required!
β οΈ Important Rule: Always pass request to your template!
# β
Correct
{
"request": request, # Always first!
"name": "John"
}
# β Wrong - missing request
{
"name": "John"
}
Why? Templates need to know about the visitorβs request to work properly!
π¦ Part 2: Static Files
Decorating Your Gallery
What are Static Files?
Static files are things that donβt change β they look the same for everyone:
- π¨ CSS files β Make things pretty
- πΌοΈ Images β Pictures and icons
- β‘ JavaScript β Add interactivity
- π Fonts β Custom text styles
Theyβre called βstaticβ because unlike templates, they donβt get filled with different data.
Setting Up Static Files
Step 1: Install the helper
pip install aiofiles
Step 2: Create your static folder
my_app/
βββ main.py
βββ templates/
βββ static/
βββ css/
β βββ style.css
βββ js/
β βββ app.js
βββ images/
βββ logo.png
Step 3: Tell FastAPI where to find them
from fastapi.staticfiles import StaticFiles
app.mount(
"/static", # URL path
StaticFiles(directory="static"),
name="static" # Name for reference
)
Using Static Files in Templates
In your HTML template:
<!DOCTYPE html>
<html>
<head>
<!-- Link to CSS -->
<link rel="stylesheet"
href="{{ url_for('static', path='css/style.css') }}">
</head>
<body>
<!-- Show an image -->
<img src="{{ url_for('static', path='images/logo.png') }}"
alt="Logo">
<!-- Link to JavaScript -->
<script src="{{ url_for('static', path='js/app.js') }}">
</script>
</body>
</html>
The url_for() function creates the correct path automatically!
Complete Example π
Folder structure:
my_app/
βββ main.py
βββ templates/
β βββ home.html
βββ static/
βββ css/
βββ style.css
static/css/style.css:
body {
font-family: Arial, sans-serif;
background-color: #f0f8ff;
text-align: center;
padding: 50px;
}
h1 {
color: #2e7d32;
}
templates/home.html:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<link rel="stylesheet"
href="{{ url_for('static', path='css/style.css') }}">
</head>
<body>
<h1>{{ message }}</h1>
<p>Styled with CSS!</p>
</body>
</html>
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# Setup templates
templates = Jinja2Templates(directory="templates")
# Setup static files
app.mount("/static",
StaticFiles(directory="static"),
name="static")
@app.get("/")
async def home(request: Request):
return templates.TemplateResponse(
"home.html",
{
"request": request,
"title": "My App",
"message": "Welcome to FastAPI!"
}
)
π― Quick Summary
graph TD A["π User Visits Page"] --> B["FastAPI Route"] B --> C["Template Engine"] C --> D["π HTML Template"] C --> E["π Your Data"] D --> F["β¨ Rendered Page"] E --> F F --> G["π¦ Static Files"] G --> H["π¨ CSS + JS + Images"] H --> I["π Beautiful Page!"]
| Feature | Purpose | Location |
|---|---|---|
| Templates | Dynamic HTML pages | templates/ folder |
| Static Files | CSS, JS, Images | static/ folder |
| Jinja2 | Template engine | pip install jinja2 |
url_for() |
Link to static files | In templates |
π You Did It!
Now you know how to:
- β Create HTML templates with Jinja2
- β Fill templates with dynamic data
- β Use loops and conditions in templates
- β Serve CSS, JavaScript, and images
- β Link static files in your templates
Your web app gallery is ready for visitors! π¨β¨
