Skip to content

#237: Static Routes in FastAPI

When we start serving HTML files with our FastAPI application, we need a way to send images, CSS- and JavaScript files without creating an endpoint for each file. Let us solve this problem with a static route.

The problem

Our template/shared/layout.html file from last week uses CDN URLs for most of Bootstrap. But it also asks for some local files with our customisation. Since they do not exist, we end up with logs full of 404 errors:

INFO: 127.0.0.1:56801  GET /about HTTP/1.1 200 OK
INFO: 127.0.0.1:56801  GET /styles.css HTTP/1.1 404 Not Found
INFO: 127.0.0.1:56803  GET /main.js HTTP/1.1 404 Not Found

While we could remove those missing files in our layout.html, we keep them and prepare a durable solution for that problem.

Create a static route

Since we do not want to create an endpoint for each CSS file, we can take a different approach and create a static route. As with the template directory, I had to reuse the BASE_DIR to get the file paths working:

...
from fastapi.staticfiles import StaticFiles

from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent

app = FastAPI()
app.include_router(todo.router, prefix="/api/todo")

app.mount("/static", StaticFiles(directory=str(Path(BASE_DIR, 'static'))), name="static")
...

Changes to the template

Inside layout.html we need to fix the two links for styles.css and main.js and add a /static/ in front of them:

1
2
3
4
5
6
7
8
9
...

<link rel="stylesheet" href="/static/styles.css">

...

<script src="/static/main.js"></script>

...

Create the static files

We can now create a static folder next to our main.py and add two empty files for styles.css and main.js. If we restart Uvicorn, we should see that we now get 200 as status codes for these files:

INFO: 127.0.0.1:62227  GET /about HTTP/1.1 200 OK
INFO: 127.0.0.1:62227  GET /styles.css HTTP/1.1 200 OK
INFO: 127.0.0.1:62228  GET /static/main.js HTTP/1.1 200 OK

If we want to use any other file in our web interface, we can put it into the static folder and FastAPI will deliver it for us.

Next

The static route is a great help to serve files through FastAPI without creating a special endpoint for each file. Next week we extend our solution and create the dashboard where we combine our templates with our database.