How to Serve a Custom HTML File at the Root Path in FastAPI with StaticFiles?

Susan Sarandon
Release: 2024-11-10 09:09:02
Original
427 people have browsed it

How to Serve a Custom HTML File at the Root Path in FastAPI with StaticFiles?

How to Load a Different File than index.html in FastAPI Root Path While Using StaticFiles?

Issue

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("/").

Solution

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')
Copy after login

Order Matters

The order of mounting and defining endpoints is crucial:

  • If StaticFiles is mounted after defining the @app.get("/") endpoint, index.html will not be loaded automatically.
  • If StaticFiles is mounted before all other endpoints, it will handle all requests due to its precedence.

The html=True Option

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template