怎样隐藏一个路径的 OpenAPI 项?隐藏后还能访问吗?
查看完整题解
参考回答
直接回答
在路径装饰器设置 include_in_schema=False,该操作可从生成的 OpenAPI 描述中排除。路由仍按正常规则注册并能收到请求。
讲清原理
隐藏适合健康检查等无需出现在公共契约中的入口。若路径只允许内部访问,要用网络或应用鉴权限制。
例子与易错点
示例确认公开路径出现在描述里,隐藏路径虽然没列出,直接请求仍返回 200。
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/catalog")
def catalog():
return []
@app.get("/health", include_in_schema=False)
def health():
return {"ready": True}
with TestClient(app) as client:
spec = client.get("/openapi.json").json()
assert "/catalog" in spec["paths"] and "/health" not in spec["paths"]
assert client.get("/health").json() == {"ready": True}
print("health omitted from schema; still reachable")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。