Home > Article > Backend Development > How to Serve Custom HTML Files Instead of index.html in FastAPI's Root Path?
In FastAPI, you can serve static files, including HTML, using the StaticFiles middleware. However, using StaticFiles for the root path (/) can lead to unexpected behavior, as it automatically serves index.html for the root directory.
According to the [Starlette documentation](https://www.starlette.io/static-files/), StaticFiles has an html option that, when set to True, automatically loads index.html for directories if such a file exists.
To correctly render your custom HTML file on the root path, mount StaticFiles to a different path, such as /static:
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static")
The order in which you mount StaticFiles and define your endpoints is crucial. If you mount StaticFiles after defining your root endpoint, the root endpoint will take precedence and the custom HTML file will be served.
If you want to serve different HTML files dynamically and have additional endpoints, it's recommended to remove the html=True option from StaticFiles and use FastAPI's [Templates](https://fastapi.tiangolo.com/templates/) instead.
By addressing the ordering and configuration of StaticFiles, you can serve your custom HTML file instead of index.html on the root path while also enabling additional API endpoints. Consider the html=True option carefully depending on your specific use case.
The above is the detailed content of How to Serve Custom HTML Files Instead of index.html in FastAPI's Root Path?. For more information, please follow other related articles on the PHP Chinese website!