FastAPI Static Files

FastAPI can conveniently serve static files (such as images, CSS, JavaScript files), using Starlette'sStaticFilesImplementation.


Install dependencies

StaticFilesincluded inaiofilesIn, you need to install:

pip install aiofiles

Mount the static file directory

Usageapp.mount()Mount the static file directory to the application:

Example

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

# Mount the 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:

ParameterDescription
"/static"URL path prefix, such as accessing/static/logo.png
directory="static"Local directory name, the folder that stores static files
name="static"the internally used name, used to generate URLs (viaurl_for)

mountis to mount an independent "sub-application" onto a specified path.StaticFilesis itself an ASGI application, responsible for handling static file requests. After mounting, all requests starting with/staticRequests starting with are all handled byStaticFilesare handled, and will not go through FastAPI's routing system.


Example directory structure

project/
├── main.py
└── static/
    ├── css/
    │   └── style.css
    ├── js/
    │   └── app.js
    └── images/
        └── logo.png

Access method:

File pathURL
static/css/style.csshttp://127.0.0.1:8000/static/css/style.css
static/js/app.jshttp://127.0.0.1:8000/static/js/app.js
static/images/logo.pnghttp://127.0.0.1:8000/static/images/logo.png

HTML Template Rendering

FastAPI supports the Jinja2 template engine, which can dynamically render 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 template
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 filetemplates/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, must passrequestobject, because the template may need to use the request context (such as generating URLs, etc.).


Summary

  • UsageStaticFilesServing static files
  • Usageapp.mount()Mount the static file directory to the specified path
  • The 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, images, etc.
other extensions