How to Serve a Specific HTML File in FastAPI Root Path While Using StaticFiles
When using FastAPI along with StaticFiles to serve static files, you might encounter scenarios where you want to load a different HTML file (e.g., custom.html) in the root path instead of the default index.html. This can be achieved by understanding certain aspects of FastAPI's routing and StaticFiles functionality.
Understanding StaticFiles
As per Starlette's documentation, StaticFiles is a middleware that handles serving static files from a specified directory. When html=True is set, it automatically looks for index.html files in directories and serves them accordingly.
Mounting Order
The order of mounting StaticFiles and defining your endpoints plays a crucial role. If StaticFiles is mounted to the root path (i.e., /) and defined before any endpoints, it will take precedence and handle all requests, even if custom endpoints are defined later.
Customizing the Root Path
To serve a specific HTML file in the root path, you need to follow these steps:
Mount StaticFiles to a separate path (e.g., /static):
app.mount('/static', StaticFiles(directory='static'))
Create a custom endpoint that returns the desired HTML file:
@app.get('/') async def index(): return FileResponse('custom.html')
Additional Considerations
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3