You aim to render a custom HTML file, such as custom.html, as the root path of your FastAPI app. However, your current setup leads to the default index.html being returned instead.
As described in the Starlette documentation on StaticFiles:
html - Run in HTML mode. Automatically loads index.html for directories if such file exists.
To resolve this issue, you have two options:
1. Mount StaticFiles to Different Path:
Mount your StaticFiles instance to a unique path, such as /static. This ensures that any path starting with /static is handled by the StaticFiles application.
app.mount('/static', StaticFiles(directory='static'), name='static')
2. Define StaticFiles After Endpoints:
If you still want to mount StaticFiles to the root path (/), define the StaticFiles instance after declaring all your API endpoints. This ensures that the endpoints have priority over StaticFiles.
@app.get('/') async def index(): return FileResponse('static/custom.html')
app.mount('/', StaticFiles(directory='static', html=True), name='static')
The html=True argument enables easy serving of static web content with a single line of code. However, if you require dynamic HTML files and additional API endpoints, consider employing Templates and mounting StaticFiles to a different path without using html=True.
The above is the detailed content of How to Serve a Custom HTML File as the FastAPI Root Path?. For more information, please follow other related articles on the PHP Chinese website!