FastAPI Static Files
FastAPI can easily serve static files (such as images, CSS, and JavaScript files) using Starlette's StaticFiles implementation based on the dynamic type of the object.
Install dependencies
StaticFiles included in aiofiles , you need to install:
pip install aiofiles
Mount a static files directory
Use app.mount() Mount a static files directory on the application:
Example
from
fastapi
import
FastAPI
from
fastapi.
staticfiles
import
StaticFiles
app
=
FastAPI
(
)
Mount a static files 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:
| Parameters | Description |
|---|---|
"/static" |
URL path prefix, e.g. when visiting /static/logo.png |
directory="static" |
Local directory name, the folder that stores static files |
name="static" |
Internal name used to generate URLs (via url_for) |
mountmounts an independent "sub-application" at a specified path.StaticFilesis itself an ASGI application that handles static file requests. After mounting, all requests starting with/staticare handled byStaticFiles, and do not pass through FastAPI's routing system.
Example directory structure
project/
├── main.py
└── static/
├── css/
│ └── style.css
├── js/
│ └── app.js
└── images/
└── logo.png
How to access:
| 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, allowing dynamic rendering of HTML pages:
Example
from
fastapi
import
FastAPI
,
Request
from
fastapi.
staticfiles
import
StaticFiles
from
fastapi.
templating
import
Jinja2Templates
app
=
FastAPI
(
)
Static files
app.
mount
(
"/static"
,
StaticFiles
(
directory
=
"static"
)
,
name
=
"static"
)
Jinja2 Templates
templates
=
Jinja2Templates
(
directory
=
"templates"
)
@
app.
get
(
"/hello/{name}"
)
async
def
hello
(
request: Request
,
name:
str
)
:
return
templates.
TemplateResponse
(
request
=
request
,
name
=
"hello.html"
,
context
=
{
"name"
: name
}
)
Template files templates/hello.html:
Example
Hello
Hello, {{ name }}!
When rendering templates, you must pass the
requestobject, because the template may need to use the request context (e.g. to generate URLs).
Summary
- Use
StaticFilesServe static files - Use
app.mount()Mount a static files directory at a specified path - Mounted static file paths are not managed by FastAPI's routing system
- Combined with the Jinja2 template engine, HTML page rendering can be achieved
- Static files are suitable for storing resources that do not change dynamically, such as CSS, JS, and images