FastAPI教程-响应类型-返回HTML

介绍

FastAPI 有4种主流返回HTML方式:

  • 返回HTML字符串
  • 返回HTML文件
  • 模板渲染(Jinja2)
  • 自定义Response

注意:FastAPI 默认返回 JSON,想要返回网页HTML,必须使用对应响应类。

1. 返回 HTML 字符串

在装饰器中指定 HTMLResponse,直接把 html文本作为内容返回。

应用场景: 简单页面

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/", response_class=HTMLResponse)
async def index():
    html_content = """
    <html>
        <head><title>FastAPI HTML</title></head>
        <body>
            <h1>Hello FastAPI HTML</h1>
            <p>直接返回html字符串</p>
        </body>
    </html>
    """
    return html_content

2. 返回 HTMLResponse 对象

直接返回 HTMLResponse(content=html_content) 对象

与上面直接返回 html字符串 等价

@app.get("/demo")
async def demo():
    return HTMLResponse("<h1>demo页面</h1>")

响应头自动设置 Content-Type: text/html; charset=utf-8

3. HTMLResponse对象原理

HTMLResponse 继承自 Response

  • content:html文本
  • status_code:状态码,默认200
  • headers:自定义http头
  • media_type="text/html"

手动构造完整响应示例:

from fastapi.responses import HTMLResponse

@app.get("/resp")
async def resp():
    return HTMLResponse(
        content="<h1>自定义响应</h1>",
        status_code=200,
        headers={"X‑Custom‑Header":"hello"}
    )

4. 返回HTML文件

使用 FileResponse 返回磁盘上的 .html 文件。

应用场景: 复杂页面

创建 HTML 文件

在 main.py 的同级目录,创建 index.html,内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
学习fastapi
</body>
</html>

修改 main.py 文件

# 增加导入
from fastapi.responses import FileResponse

@app.get("/page")
async def get_html_file():
    # 返回当前目录下 index.html
    return FileResponse("index.html")

特点

直接读取磁盘文件,适合纯静态网页;会自动设置html的content‑type。

注意路径问题

相对路径以程序启动目录为基准,不是py文件所在目录。

推荐:用绝对路径,避免路径bug。

浏览器访问与接口文档

  • 浏览器访问路由:渲染网页
  • /docs接口文档:会把html源码直接展示在响应体,不会渲染页面,这是正常现象。

原文出处:/show_1GW3riDStUmv.html