Fastapi getting static routes right?

Viewed 541

My setup is such that i want to run Svelte and FastAPI on the same Heroku instance. I managed to get the static routes in this way that I have two apps:

app = FastAPI(title="Main App")
api_app=FastAPI(title="Api App")
app.mount('/api', api_app)
app.mount('/build', StaticFiles(directory="frontend-svelte/public/build", html=True), name="build")
app.mount('/', StaticFiles(directory="frontend-svelte/public", html=True), name="static")

Which is great for serving index.html - however, svelte would like to have the internal routes in a way that anything that isn't /api or /build serves index.html. This is why I added

@app.route("/{full_path:path}")
async def catch_all(request: Request, full_path: str):
    print("full_path: "+full_path)
    return templates.TemplateResponse("index.html", {"request": request})

However it returns a 404 and I don't know whats wrong?

1 Answers

First, you need to define your route before mounts. Second, @app.route don't work with {full_path:path}. If you need only to serve static files, you can use get. Or copy your functoin for post, delete and put methods.

app = FastAPI(title="Main App")
api_app = FastAPI(title="Api App")


@app.get("/{full_path:path}")
async def catch_all(full_path: str, request: Request):
    print("full_path: "+full_path)
    return templates.TemplateResponse("index.html", {"request": request})

app.mount("/api", api_app)
app.mount(
    "/build",
    StaticFiles(directory="frontend-svelte/public/build", html=True),
    name="build",
)
app.mount(
    "/", StaticFiles(directory="frontend-svelte/public", html=True), name="static"
)

If you only need to serve static files for other app, nginx will work better.

Related