如何隐藏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
相关产品推荐
相关产品推荐

