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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With