Serving Static Files in FastAPI: Tutorial & Example

Updated: January 19, 2023 By: Khue Post a comment

This tutorial shows you how to serve static files (images, CSS files, Javascript files, HTML files, or something like that) in FastAPI. Before getting started, you can see a live demo at the URL shown below:

https://api.slingacademy.com/public/sample-photos/10.jpeg

Our REST API, api.slingacademy.com, is built with FastAPI, and our static files are all located in a folder named public and its subdirectories (sample-photos is one of the subdirectories).

What is the point?

To serve static files in FastAPI, just call the built-in mount() method on your app instance. For example, you can use the following code to serve static assets in a directory named public:

# main.py
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/public", StaticFiles(directory="public"), name="static")

Any path that starts with /public will be used for serving static materials. Note that public is just a demonstration, and you can use whatever name you like.

The mount() method creates an independent sub-application in a specific path that then takes care of handling all the sub-paths. Note that the OpenAPI and docs from your main application won’t include anything from the sub-application.

Let me explain the code snippet above a bit deeper:

  • /public: The sub-path of the sub-application that is mounted on
  • public: The path to the directory where you want to store your static files
  • static: This is optional. It provides a name for FastAPI’s internal use. static isn’t mandatory, and you can use another string as you wish.

If you have a ton of static files, you can keep your project organized by adding more subdirectories like this:

├── main.py
├── public
│   ├── css
│   ├── images
│   └── js
└── requirements.txt

You can also mount other directories to your application, like this:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/audios", StaticFiles(directory="audios"), name="audios")
app.mount("/images", StaticFiles(directory="images"), name="images")
app.mount("/docs", StaticFiles(directory="docs"), name="documents")