Option 1: Static file mounting
It was easier than expected. Just needed to put all static files including index.html into static folder in project directory and mount static files.
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
That’s it. My index.html is now available under http://localhost:8000/static/index.html.
In case it should be accessible right under http://localhost:8000/ without /static and the .html ending one needs to change two things. First it needs to be mounted on / instead of /static and an HTML flag must be set to true when mounting. So just use this line instead:
app.mount("/", StaticFiles(directory="static",html = True), name="static")
(Thanks to this answer)
The index.html is now available under http://localhost:8000/
Option 2: Serving only index.html
As fastapi is based on starlette, a simple FileResponse does the job.
from starlette.responses import FileResponse
@app.get("/")
async def read_index():
return FileResponse('index.html')
Found here.