Serving static files lets your web app show images, styles, or scripts directly to users. It helps display things like pictures or CSS without extra coding.
Serving static files in FastAPI
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles app = FastAPI() app.mount("/static", StaticFiles(directory="path_to_static_files"), name="static")
The mount method connects a URL path to a folder with static files.
The directory is where your static files are stored on your computer.
static in your project root at URL path /static.app.mount("/static", StaticFiles(directory="./static"), name="static")
assets folder at URL path /assets.app.mount("/assets", StaticFiles(directory="assets"), name="assets")
/files URL.app.mount("/files", StaticFiles(directory="/var/www/files"), name="files")
This program creates a FastAPI app that serves any file inside the ./static folder at the URL path /static. For example, if you have an image named example.png inside ./static, you can open it in your browser at http://localhost:8000/static/example.png.
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles app = FastAPI() # Mount the static directory to serve files under /static URL app.mount("/static", StaticFiles(directory="./static"), name="static") # Run this app and visit http://localhost:8000/static/example.png to see the image if it exists in ./static folder
Make sure the static folder exists and has the files you want to serve.
Static files are served as-is; FastAPI does not process them.
Use meaningful URL paths to organize your static files for easier access.
Use app.mount with StaticFiles to serve static files in FastAPI.
Static files include images, CSS, JavaScript, and other resources.
Access static files via the URL path you set in mount.