Skip to main content
 首页 » 编程设计

python之在没有任何连接的情况下在 Flask 上显示 Swagger UI

2025年05月04日28zhoujg

有人知道我可以在 flask 上提供 swagger UI .yml 文件而不创建或连接 API 的方法吗?我只想在网站上展示 swagger 文件,以便人们可以看到如何使用 API,但我不想创建 API 或连接任何东西,因为 API 是私有(private)的,所以无论如何都无法调用。

API 来自 AWS API Gateway,所以我无法将任何东西与 Flask 连接起来。

我调查了 connexion但我需要连接我的 API 方法才能使用它,但这是行不通的。

我可以使用 openapi 编辑器将 api 规范转换为 html,然后提供 html,但我想尝试使用 swagger ui 提供的漂亮布局。

请您参考如下方法:

Swagger 在 dist folder 中有一个已发布的示例项目的。

浏览器就绪的 javascript 包是 available in unpkg or directly via cloudflare CDN并且可以直接从那里提供服务。

在您的用例中,您可以在 dist 文件夹中编写类似于 index.html 文件的模板文件,而无需为 Swagger UI 设置额外的构建过程为你的 flask 项目捆绑。

您的模板将如下所示,您将 url 的值替换为包含您的 API 定义的 yaml 文件的 URL:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
    <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js"></script> 
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.22.1/swagger-ui-standalone-preset.js"></script> --> 
    <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> 
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.22.1/swagger-ui-bundle.js"></script> --> 
    <link rel="stylesheet" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> 
    <!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.22.1/swagger-ui.css" /> --> 
    <title>Swagger</title> 
</head> 
<body> 
    <div id="swagger-ui"></div> 
    <script> 
        window.onload = function() { 
          SwaggerUIBundle({ 
            url: "https://petstore.swagger.io/v2/swagger.yaml", 
            dom_id: '#swagger-ui', 
            presets: [ 
              SwaggerUIBundle.presets.apis, 
              SwaggerUIStandalonePreset 
            ], 
            layout: "StandaloneLayout" 
          }) 
        } 
    </script> 
</body> 
</html>