You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FastAPI的Swagger UI中展示HTMLResponse返回的实际HTML页面?

解决FastAPI Swagger UI展示原始HTML的问题

Swagger UI默认会把HTMLResponse的内容当作纯文本显示,要让它渲染成实际页面,可以用下面两种方法:

方法一:直接访问接口地址

不用通过Swagger UI,直接在浏览器地址栏输入你的接口URL(比如http://localhost:8000/items/),浏览器会自动渲染HTML内容,展示实际页面。

方法二:修改接口的OpenAPI元数据

通过给接口添加openapi_extra参数,告诉Swagger UI以HTML格式渲染响应。修改后的代码如下:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()


@app.get(
    "/items/",
    openapi_extra={
        "responses": {
            200: {
                "content": {"text/html": {"schema": {"type": "string"}}},
                "description": "返回渲染后的HTML页面"
            }
        }
    }
)
async def read_items():
    html_content = """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """
    return HTMLResponse(content=html_content, status_code=200)

修改后重启服务,在Swagger UI里调用接口,就能看到渲染后的HTML页面了。

内容的提问来源于stack exchange,提问作者user14681827

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:10:31