使用 Flasgger 为 flask restful 应用添加 openapi规范文档及SwaggerUI

问题

在使用 flask restful 编写RESTful接口的时候,可以使用 Flasgger 为RESTful接口添加SwaggerUI,直接集成在当前的flask服务器中。在测试的时候使用flask内置的HTTP服务器,启动之后,默认是5000端口,直接访问http://localhost:5000/apidocs就可以看到 SwaggerUI 的界面,可以直接查看以及测试各个接口。

使用方式

下面只列出一般使用方式,更详细的请查看项目文档
项目地址 https://github.com/flasgger/flasgger

安装

pip install -U setuptools
pip install flasgger

使用

初始化

首先在 main.py 的主文件中导入包并初始化 swagger

from flask import Flask, jsonify
from flasgger import Swagger

app = Flask(__name__)
swagger = Swagger(app)

添加文档(三种方式)

  1. 直接在对应的方法下面添加注释
@app.route('/colors/<palette>/')
def colors(palette):
    """Example endpoint returning a list of colors by palette
    This is using docstrings for specifications.
    ---
    parameters:
      - name: palette
        in: path
        type: string
        enum: ['all', 'rgb', 'cmyk']
        required: true
        default: all
    definitions:
      Palette:
        type: object
        properties:
          palette_name:
            type: array
            items:
              $ref: '#/definitions/Color'
      Color:
        type: string
    responses:
      200:
        description: A list of colors (may be filtered by palette)
        schema:
          $ref: '#/definitions/Palette'
        examples:
          rgb: ['red', 'green', 'blue']
    """
    all_colors = {
        'cmyk': ['cian', 'magenta', 'yellow', 'black'],
        'rgb': ['red', 'green', 'blue']
    }
    if palette == 'all':
        result = all_colors
    else:
        result = {palette: all_colors.get(palette)}

    return jsonify(result)
  1. 在对应的方法下面使用 file 来引入yml文件
    如下图所示,是引入 spec 文件夹下的 scans_post.yml 文件
  2. 使用 @swag_from('specs/scans_get_scanid.yml') 装饰器来引入外部yml文件
    需要先在函数所在的文件中引入对应的方法 from flasgger import swag_from

注意

不要使用 swagger 在线编辑器来编写用于此项目的 yml 文件,部分格式不兼容。
例如,在 Flasgger 插件中,枚举(enum)的编写方式是类似数组的方式,而编辑器中不是。下图是在 flasgger 插件中编写的方式

最终效果

参考

openapi文档编写格式参考:https://www.breakyizhan.com/swagger/2965.html
样例:https://www.cnblogs.com/huchong/p/10569480.html

posted @ 2021-02-03 15:21  TheTai  阅读(1471)  评论(0编辑  收藏  举报