如何在 FastAPI 中使用本地资源自定义 Swagger UI

要自定义 FastAPI 中的 Swagger UI,且使用本地资源来代替 CDN。只是需要稍微修改一下。

修改后的代码:

步骤:

  1. 挂载本地静态文件目录:我们将本地的 Swagger UI 资源文件(如 .js, .css, favicon.png 等)放置在项目的一个目录中(例如:static/swagger-ui)。
  2. 自定义 Swagger UI 页面:您可以通过 FastAPI 的 get_swagger_ui_html() 方法来加载本地的 Swagger UI 页面。

修改后的代码:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html

app = FastAPI(
    docs_url=None,  # 禁用默认的 Swagger UI 地址
    redoc_url=None  # 禁用 ReDoc 默认地址
)

# Step 1: Mount the static directory for Swagger UI resources
app.mount("/static", StaticFiles(directory="static"), name="static")

# Step 2: Define custom Swagger UI route
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui():
    return get_swagger_ui_html(
        openapi_url="/openapi.json",  # 指定 OpenAPI 文档路径
        title="API Docs",  # 自定义页面标题
        swagger_js_url="/static/swagger-ui/swagger-ui-bundle.js",  # 本地 JS 文件
        swagger_css_url="/static/swagger-ui/swagger-ui.css",  # 本地 CSS 文件
        swagger_favicon_url="/static/swagger-ui/favicon.png"  # 本地 favicon 图标
    )

解释:

  1. 禁用默认的 Swagger UI

    docs_url=None,  # 禁用默认的 Swagger UI 地址
    redoc_url=None  # 禁用 ReDoc 默认地址
    

    通过设置 docs_url=Noneredoc_url=None,您禁用了 FastAPI 默认提供的 Swagger UI 和 ReDoc 文档路径。

  2. 挂载静态文件目录

    app.mount("/static", StaticFiles(directory="static"), name="static")
    

    这行代码将本地 static 目录挂载为静态文件服务。Swagger UI 资源文件应该放在 static/swagger-ui 目录下。

  3. 自定义 Swagger UI 页面

    @app.get("/docs", include_in_schema=False)
    async def custom_swagger_ui():
        return get_swagger_ui_html(
            openapi_url="/openapi.json",
            title="API Docs",
            swagger_js_url="/static/swagger-ui/swagger-ui-bundle.js",
            swagger_css_url="/static/swagger-ui/swagger-ui.css",
            swagger_favicon_url="/static/swagger-ui/favicon.png"
        )
    

    get_swagger_ui_html() 是 FastAPI 提供的函数,用于生成 Swagger UI 的 HTML 页面。您可以在其中自定义:

    • openapi_url:指定您的 OpenAPI 文档 URL。
    • swagger_js_urlswagger_css_urlswagger_favicon_url:指定 Swagger UI 需要的本地资源文件路径。

本地文件结构:

您的文件夹结构应该如下:

project/
│
├── app.py  # FastAPI 代码
├── static/
│   └── swagger-ui/
│       ├── swagger-ui.css
│       ├── swagger-ui-bundle.js
│       ├── swagger-ui-standalone-preset.js
│       └── favicon.png

访问 Swagger UI:

  • 启动应用后,访问 http://127.0.0.1:8000/docs,您应该可以看到加载了本地资源的 Swagger UI 页面,而不再依赖外部 CDN。

这样,您就可以使用 FastAPI 提供的本地资源来定制 Swagger UI 了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值