Home > Article > Backend Development > How to Serve a Custom HTML File at the Root Path in FastAPI with StaticFiles?
In a FastAPI application that serves static files using StaticFiles, the request to the root path returns index.html instead of a custom HTML file specified in a separate @app.get("/").
According to the Starlette documentation for StaticFiles:
html - Run in HTML mode. Automatically loads index.html for directories if such file exists.
To fix this issue, mount the StaticFiles instance to a different path, such as /static, instead of / (root path), as demonstrated below:
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse app = FastAPI() app.mount('/static', StaticFiles(directory='static'), name='static') @app.get('/') async def index() -> FileResponse: return FileResponse('static/custom.html', media_type='html')
The order of mounting and defining endpoints is crucial:
Setting html=True simplifies serving a directory of web content in one line. However, for dynamic content or additional endpoints, consider using 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 at the Root Path in FastAPI with StaticFiles?. For more information, please follow other related articles on the PHP Chinese website!