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

Chris
  • 18,724
  • 6
  • 46
  • 80
Joel
  • 11
  • 1
  • Please have a look at [this answer](https://stackoverflow.com/a/74498663/17865804) as well as [this answer](https://stackoverflow.com/a/74759329/17865804), which explain how the order in which the endpoints are defined matters. – Chris Jan 15 '23 at 13:17

1 Answers1

1

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.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84