YouTip LogoYouTip

Fastapi Static Files

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)

mount attaches a standalone "sub-application" to a specified path. StaticFiles itself is an ASGI application responsible for handling static file requests. After mounting, all requests starting with /static are handled directly by StaticFiles, 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 request object must be passed, as templates may require request context (e.g., for URL generation).


Summary

  • Use StaticFiles to 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
← Fastapi TestingFastapi Middleware β†’