How to Use Static Files in FastAPI: Simple Guide
In FastAPI, you serve static files by mounting the
StaticFiles middleware on a specific path using app.mount(). This lets you serve files like images, CSS, or JavaScript from a folder to your users easily.Syntax
To serve static files in FastAPI, use app.mount() with StaticFiles(directory='your_folder'). The directory is where your static files live, and the mount path is the URL prefix users will use to access them.
app.mount(path, StaticFiles(directory=folder_path), name='static'): Mounts static files atpath.directory: The folder on your server with static files.name: A name for the mounted route (optional).
python
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static")
Example
This example shows how to serve static files from a folder named static. Files inside this folder can be accessed via URLs starting with /static. For example, static/image.png is available at http://localhost:8000/static/image.png.
python
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles app = FastAPI() # Mount the static files directory app.mount("/static", StaticFiles(directory="static"), name="static") # Run with: uvicorn filename:app --reload
Output
When running the app and visiting http://localhost:8000/static/yourfile.ext, the file from the static folder is served.
Common Pitfalls
- Not creating the static folder or placing files inside it before running the app causes 404 errors.
- Mounting static files on the root path
"/"can interfere with other routes. - Forgetting to add
StaticFilesimport or using incorrect directory paths causes errors. - Static files are served as-is; no processing happens, so ensure files are ready to serve.
python
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles app = FastAPI() # Wrong: Mounting on root path can block other routes # app.mount("/", StaticFiles(directory="static"), name="static") # Right: Use a subpath like /static app.mount("/static", StaticFiles(directory="static"), name="static")
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Mount Static Files | Attach static folder to URL path | app.mount('/static', StaticFiles(directory='static'), name='static') |
| Directory | Folder with static files | 'static' folder in project root |
| Access URL | URL prefix to access files | http://localhost:8000/static/filename.ext |
| Common Error | 404 if folder missing or wrong path | Check folder exists and path is correct |
Key Takeaways
Use app.mount() with StaticFiles to serve static files in FastAPI.
Place your static files in a folder and specify its path in StaticFiles(directory=...).
Mount static files on a subpath like '/static' to avoid route conflicts.
Ensure the static folder exists and contains files before running the app.
Access static files via URLs starting with the mount path you set.