Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve static files from root in FastAPI

Tags:

svelte

fastapi

I'm trying to have FastAPI work with Svelte. I've built the static files with Svelte and now I'm trying to serve them from FastAPI. The problem is that the built Svelte files reference e.g. global.css from root, which means I can't have them mounted on a subfolder.

Instead, I have to mount them on root:

app.mount("/", StaticFiles(directory="web/public", html=True), name="web")

However, this makes anything defined in routes (function decorators) inaccessible.

Is it possible have either both static files and functions defined? Either,

a) routes take precedence and if there's no route, it tries to read from static directories

b) static directories take precedence, and I specify an exclude path, which goes to routes instead

like image 509
shadesofdarkred Avatar asked Nov 16 '25 02:11

shadesofdarkred


1 Answers

Create an outer (root) FastAPI app and mount the StaticFiles app and your existing FastAPI app inside of it.

# Your main app must be first!
app = FastAPI(title="my app root")

api_app = FastAPI(title="my existing api")
api_app.include_router(my_existing_router)
app.mount('/api', api_app)

app.mount('/', StaticFiles(directory="static", html=True), name="static")

The order of mounting of the app objects seems to matter. For the OpenAPI docs, you'll have a /docs for the root app, and a /api/docs for your API app.

like image 121
ldrg Avatar answered Nov 18 '25 20:11

ldrg