0
0
FastAPIframework~5 mins

Serving static files in FastAPI

Choose your learning style9 modes available
Introduction

Serving static files lets your web app show images, styles, or scripts directly to users. It helps display things like pictures or CSS without extra coding.

You want to show images like logos or photos on your website.
You need to add CSS files to style your web pages.
You want to serve JavaScript files for interactive features.
You have downloadable files like PDFs or documents for users.
You want to serve favicon or icons for your website.
Syntax
FastAPI
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

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

The mount method connects a URL path to a folder with static files.

The directory is where your static files are stored on your computer.

Examples
Serve files from a folder named static in your project root at URL path /static.
FastAPI
app.mount("/static", StaticFiles(directory="./static"), name="static")
Serve files from assets folder at URL path /assets.
FastAPI
app.mount("/assets", StaticFiles(directory="assets"), name="assets")
Serve files from an absolute path on your system at /files URL.
FastAPI
app.mount("/files", StaticFiles(directory="/var/www/files"), name="files")
Sample Program

This program creates a FastAPI app that serves any file inside the ./static folder at the URL path /static. For example, if you have an image named example.png inside ./static, you can open it in your browser at http://localhost:8000/static/example.png.

FastAPI
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

# Mount the static directory to serve files under /static URL
app.mount("/static", StaticFiles(directory="./static"), name="static")

# Run this app and visit http://localhost:8000/static/example.png to see the image if it exists in ./static folder
OutputSuccess
Important Notes

Make sure the static folder exists and has the files you want to serve.

Static files are served as-is; FastAPI does not process them.

Use meaningful URL paths to organize your static files for easier access.

Summary

Use app.mount with StaticFiles to serve static files in FastAPI.

Static files include images, CSS, JavaScript, and other resources.

Access static files via the URL path you set in mount.