Static Files
NotesThe first thing to implement is the ability to serve static files. For this project, any code relating to rendering web pages will live under a new subdirectory web. To include a static directory, for example style sheets and images, FastAPI uses a mounting concept. Create it in the root of the project including a subdirectory for static files:
mkdir -p web/staticThis guide uses the free Clean Blog theme by Start Bootstrap (MIT licensed), version 3.3.7, which is the Bootstrap 3 version the templates in this section are based on. Download it from GitHub:
curl -L -o clean-blog.zip https://github.com/StartBootstrap/startbootstrap-clean-blog/archive/refs/tags/v3.3.7.zip
unzip clean-blog.zipCopy the css, img, js, and vendor directories from the theme into web/static, keeping its licence alongside them:
cp -r startbootstrap-clean-blog-3.3.7/{css,img,js,vendor} web/static/
cp startbootstrap-clean-blog-3.3.7/LICENSE web/static/LICENSE-clean-blogThe structure should look something like this:
web
└── static
├── css
│ ├── clean-blog.css
│ └── clean-blog.min.css
├── img
│ ├── about-bg.jpg
│ ├── contact-bg.jpg
│ ├── home-bg.jpg
│ ├── post-bg.jpg
│ └── post-sample-image.jpg
├── js
│ ├── clean-blog.js
│ ├── clean-blog.min.js
│ ├── contact_me.js
│ └── jqBootstrapValidation.js
├── LICENSE-clean-blog
└── vendor
├── bootstrap
├── font-awesome
└── jqueryYou might want to add a favicon.ico to the root of the static directory too, you can generate one here https://favicon.io/.
Edit main.py, import StaticFiles and mount the /static directory:
from fastapi.staticfiles import StaticFiles # NEWdef configure_routing():
main_app.mount('/static', StaticFiles(directory='web/static'), name='static') # NEW
main_app.include_router(health_api.router, prefix=settings.CONF_API_V1_STR, tags=["health"])
main_app.include_router(blog_apis.router, prefix=settings.CONF_API_V1_STR, tags=["blog_apis"])Mounting attaches a separate, self-contained application at a path. Here everything under /static is served straight from files in web/static, without going through your routes. FastAPI re-exports Starlette’s StaticFiles, Jinja2Templates, and responses, so this section imports them from fastapi.
You can validate that the static content is being served, for example http://localhost:8000/static/img/home-bg.jpg.
From here on, the guide shows only the parts of main.py that change. The middleware and CORS from Getting Started stay as they are. The complete file is shown at the end of the Custom 404 Page section.