Home > Backend Development > Python Tutorial > How to Serve a Custom HTML File as the FastAPI Root Path?

How to Serve a Custom HTML File as the FastAPI Root Path?

Barbara Streisand
Release: 2024-11-12 01:49:01
Original
673 people have browsed it

How to Serve a Custom HTML File as the FastAPI Root Path?

Serving Custom HTML File as FastAPI Root Path

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.

Cause of Index.html Return

As described in the Starlette documentation on StaticFiles:

html - Run in HTML mode. Automatically loads index.html for directories if such file exists.
Copy after login

Solution

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

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')
Copy after login
app.mount('/', StaticFiles(directory='static', html=True), name='static')
Copy after login

html=True Option

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!

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