1

The error message is as follows:

GET http://localhost:8080/api 404 (Not Found)

It works well except for the @app.get("/api") request in the code below. I tried a similar function using Node.js(Express) and it worked well.

Do I need to separate the API server from the server that distributes the static files unlike Node.js?

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from fastapi import FastAPI
import uvicorn

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

@app.get("/", response_class=FileResponse)
async def root():
    return FileResponse("./front/index.html", media_type="text/html")

@app.get("/api")
async def api():
    return {"Fastapi with web": "Hello"}

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8080, reload=True)

Error message

GET /api HTTP/1.1" 404 Not Found

1
  • Please have a look at this answer as well as this answer, which explain how the order in which the endpoints are defined matters. Commented Jan 15, 2023 at 13:17

1 Answer 1

2

You have to be careful about the sequence you register the endpoints in when you want one or more endpoints to override each other.

In this case you have to move app.mount(..) to the bottom, so that the other endpoints gets registered first:

from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
async def default():
    return {"default": "yep"}

@app.get("/api")
async def api():
    return {"Fastapi with web": "Hello"}

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

This way both / and /api gets served from their regular endpoints, but any other path gets resolved through the StaticFiles app.

If possible I'd recommend still having a /static path component instead of serving the files directly under / to avoid future confusion, but if necessary this should work.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.