FastAPI Static Files
FastAPI can conveniently serve static files (such as images, CSS, and JavaScript files) using Starletteβs StaticFiles.
Install Dependencies
StaticFiles depends on aiofiles, which needs to be installed:
pip install aiofiles
Mount Static File Directory
Use app.mount() to mount the static file directory onto the application:
Example
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# Mount static file directory
# "/static" is the URL path prefix
# directory="static" is the local directory name
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
async def root():
return{"message": "Hello World"}
Code Explanation:
| Parameter | Description |
|---|---|
"/static" |
URL path prefix; e.g., accessing /static/logo.png |
directory="static" |
Local directory nameβthe folder where static files are stored |
name="static" |
Internal name used for URL generation (via url_for) |
mountattaches a standalone "sub-application" to a specified path.StaticFilesitself is an ASGI application responsible for handling static file requests. After mounting, all requests starting with/staticare handled directly byStaticFiles, bypassing FastAPIβs routing system.
Directory Structure Example
project/
βββ main.py
βββ static/
βββ css/
β βββ style.css
βββ js/
β βββ app.js
βββ images/
βββ logo.png
Access Methods:
| File Path | URL |
|---|---|
static/css/style.css |
http://127.0.0.1:8000/static/css/style.css |
static/js/app.js |
http://127.0.0.1:8000/static/js/app.js |
static/images/logo.png |
http://127.0.0.1:8000/static/images/logo.png |
HTML Template Rendering
FastAPI supports the Jinja2 template engine for dynamic HTML page rendering:
Example
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
# Mount static files
app.mount("/static", StaticFiles(directory="static"), name="static")
# Configure template directory
templates = Jinja2Templates(directory="templates")
@app.get("/hello/{name}")
async def hello(request: Request, name: str):
# Render template and pass context variables
return templates.TemplateResponse(
"hello.html",
{"request": request,"name": name}
)
Template file templates/hello.html:
Example
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<link rel="stylesheet"href="/static/css/style.css">
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<img src="/static/images/logo.png"alt="Logo">
</body>
</html>
When rendering templates, the
requestobject must be passed, as templates may require request context (e.g., for URL generation).
Summary
- Use
StaticFilesto serve static files - Use
app.mount()to mount the static file directory to a specified path - After mounting, static file paths are not managed by FastAPIβs routing system
- Combined with the Jinja2 template engine, HTML page rendering is possible
- Static files are suitable for resources that do not change dynamically, such as CSS, JS, and images
YouTip