← Back to Tutorials

15. Static Files

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

# Mount static files directory
app.mount("/static", StaticFiles(directory="static"), name="static")

Folder Structure

project/
├── main.py
├── static/
│   ├── css/
│   │   └── style.css
│   ├── js/
│   │   └── app.js
│   └── images/
│       └── logo.png
└── templates/
    └── index.html

Using in Templates

<!-- templates/index.html -->
<link rel="stylesheet" href="/static/css/style.css">
<script src="/static/js/app.js"></script>
<img src="/static/images/logo.png" alt="Logo">
💡 Note: Mounting static files happens after routes. If you mount before, FastAPI matches the mount path before checking routes. Order matters for path matching.
✏️ Exercise: Create a static folder with a CSS file that styles your template. Mount it in FastAPI and verify the CSS is applied in the browser.