如何使用带有 Flask 的静态 .yaml 文件生成 OpenAPI 文档(Swagger UI)页面?

How to generate OpenAPI docs (Swagger UI) page using static .yaml file with Flask?

我正在 RESTful API flask 服务器上工作,我需要创建端点以使用静态文件 (.yaml) 呈现我的 API。我试过 flask_swagger_ui,但我不知道如何指定本地文件的路径。我是开发 RESTful API 和烧瓶服务器的新手,所以我很乐意得到一些建议如何以正确的方式做我想做的事。

假设您有一个名为 openapi.yaml 的规范文件。如果您想自己托管 API 文档,可以按照以下步骤操作:

  1. 创建一个名为 app.py 的文件,然后创建两个视图来为规范文件和 Swagger UI 页面提供服务:
from flask import Flask, render_template, send_from_directory

app = Flask(__name__)


@app.route('/docs')
def swagger_ui():
    return render_template('swagger_ui.html')


@app.route('/spec')
def get_spec():
    return send_from_directory(app.root_path, 'openapi.yaml')
  1. templates 文件夹中创建一个名为 swagger_ui.html 的模板,其中包含以下内容:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@3//swagger-ui.css" >
    <style>
      html
      {
        box-sizing: border-box;
        overflow: -moz-scrollbars-vertical;
        overflow-y: scroll;
      }

      *,
      *:before,
      *:after
      {
        box-sizing: inherit;
      }

      body
      {
        margin:0;
        background: #fafafa;
      }
    </style>
  </head>

  <body>
    <div id="swagger-ui"></div>

    <script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
    <script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js"></script>
    <script>
      window.onload = function() {
      const ui = SwaggerUIBundle({
        url: "{{ url_for('get_spec') }}",
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl
        ],
        layout: "BaseLayout"
      })
    }
    </script>
  </body>
</html>

最终的文件结构将是这样的:

- app.py
- templates
    - swagger_ui.html
- openapi.yaml
  1. 现在 运行 应用具有:
$ flask run
  1. 然后前往http://localhost:5000/docs