Static files — CSS, JS, images
Mount a directory as a static file server. Files are served as-is, no processing.
main.py
v3.1
API simulator
click Simulate
Click "Simulate" to see what this FastAPI app does.
🧠 How it works
app.mount('/prefix', StaticFiles(directory='path'), name='static') — serves every file in 'path' at '/prefix/filename'. The directory path is RELATIVE TO your CWD when you run uvicorn, not relative to main.py. name='static' is for URL reversing (rarely used). Files are served with the correct Content-Type based on extension (.css → text/css, .js → application/javascript). StaticFiles does NOT do any processing — what's in the file is what's served. For production: use a CDN or nginx for static files — they're faster than FastAPI. But for dev, mounting them in FastAPI is fine and convenient.
✏️ Try these changes
-
Change mount path from '/static' to '/assets'→ URLs change to /assets/style.css -
Add a new file app/static/logo.png and reference it with <img src="/static/logo.png">→ image appears -
Change the directory to 'static_files' and create that folder→ files served from new location