You can serve static files automatically from a directory using Starlette's Static Files.
First you need to install
pip install aiofiles
- "Mount" it the same way you would mount a Sub-Application.
from fastapi import FastAPI from starlette.staticfiles import StaticFiles app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static")
Then you could have a directory
./static/ with some files that will be served directly.
"/static" refers to the sub-path this "sub-application" will be "mounted" on. So, any path that starts with
"/static" will be handled by it.
directory="static" refers to the name of the directory that contains your static files.
name="static" gives it a name that can be used internally by FastAPI.
All these parameters can be different than "
static", adjust them with the needs and specific details of your own application.
For more details and options check Starlette's docs about Static Files.