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

如何隐藏FastAPI中/redoc页面的「Download OpenAPI specification」按钮

隐藏FastAPI Redoc页面的「Download OpenAPI specification」按钮

要隐藏Redoc页面的下载按钮,你可以通过配置Redoc的内置参数实现,以下是两种可靠方案:

方法一:使用FastAPI内置Redoc模板配置(推荐)

FastAPI提供的get_redoc_html工具函数支持传入Redoc配置参数,只需添加hideDownloadButton: True即可隐藏按钮:

from fastapi import FastAPI
from fastapi.openapi.docs import get_redoc_html

app = FastAPI(docs_url=None, redoc_url="/redoc")

@app.get("/redoc", include_in_schema=False)
async def custom_redoc():
    return get_redoc_html(
        openapi_url=app.openapi_url,
        title=f"{app.title} - ReDoc",
        redoc_options={"hideDownloadButton": True}  # 核心配置:隐藏下载按钮
    )

方法二:完全自定义Redoc HTML模板

如果需要更灵活的页面定制,可以直接返回自定义HTML响应,在Redoc初始化配置中加入隐藏按钮的参数:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI(docs_url=None, redoc_url="/redoc")

REDOC_CUSTOM_HTML = """
<!DOCTYPE html>
<html>
<head>
    <title>我的API文档 - ReDoc</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
    <style>
        body { margin: 0; padding: 0; }
    </style>
</head>
<body>
    <redoc spec-url="/openapi.json" options='{"hideDownloadButton": true}'></redoc>
    <script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"></script>
</body>
</html>
"""

@app.get("/redoc", include_in_schema=False)
async def custom_redoc_page():
    return HTMLResponse(content=REDOC_CUSTOM_HTML)

说明

  • 两种方法都会隐藏Redoc页面上的下载按钮,但用户仍可通过直接访问/openapi.json获取API规范(符合你的需求)。
  • 若不需要Swagger UI,可设置docs_url=None禁用默认Swagger页面,只保留定制后的Redoc。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:32:27