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

如何为FastAPI各端点生成独立Swagger UI文档页面?

实现FastAPI单端点独立Swagger UI页面

FastAPI默认会把所有端点的文档集中展示,但可以通过两种方式实现单端点专属的Swagger UI页面,满足iframe嵌入需求:

方案一:拆分独立子应用

为目标端点创建单独的FastAPI子应用,子应用会自动生成仅包含自身端点的文档页面,适合模块清晰的项目:

from fastapi import FastAPI

# 主应用
app = FastAPI(title="主应用")

# 仅包含书籍查询端点的子应用
books_api = FastAPI(title="书籍接口文档")

@books_api.get("/books/{book_id}", summary="获取单本书籍详情")
def fetch_book(book_id: int):
    return {"book_id": book_id, "title": "Python实战"}

# 将子应用挂载到主应用路径下
app.mount("/book-docs", books_api)

启动服务后,访问/book-docs/docs就能看到仅展示GET /books/{book_id}的Swagger UI页面,直接把这个URL嵌入iframe即可。

方案二:过滤OpenAPI文档

无需拆分应用,通过修改OpenAPI规范过滤出指定端点,再渲染自定义Swagger页面:

from fastapi import FastAPI, Request
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi

app = FastAPI(title="主应用")

@app.get("/books/{book_id}", summary="获取单本书籍详情")
def fetch_book(book_id: int):
    return {"book_id": book_id, "title": "Python实战"}

@app.get("/users/{user_id}", summary="获取用户详情")
def fetch_user(user_id: int):
    return {"user_id": user_id, "name": "张三"}

# 自定义书籍端点的专属文档路由
@app.get("/single-book-docs", include_in_schema=False)
async def single_book_swagger(request: Request):
    # 获取完整的OpenAPI规范
    full_openapi = get_openapi(
        title="书籍单端点文档",
        version=app.version,
        routes=app.routes
    )
    # 过滤出仅包含书籍路径的端点
    filtered_paths = {path: data for path, data in full_openapi["paths"].items() if "/books/" in path}
    full_openapi["paths"] = filtered_paths
    
    # 返回定制化的Swagger UI页面
    return get_swagger_ui_html(
        title="书籍单端点文档",
        openapi_schema=full_openapi,
        swagger_js_url="/static/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui.css"
    )

访问/single-book-docs即可得到仅展示书籍查询端点的Swagger页面,适合快速实现单端点文档嵌入。

注意点

  • 子应用方案完全独立,配置与主应用隔离,便于维护
  • 过滤方案更灵活,但需确保路径匹配规则准确,避免误过滤
  • 嵌入iframe时,建议设置width="100%" height="600px"这类属性保证显示效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:23:11