Python实现处理apiDoc转swagger的方法详解

 更新时间:2023年02月02日 08:46:27   作者:七仔的博客  
这篇文章主要为大家详细介绍了Python实现处理apiDoc转swagger的方法,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以了解一下

需要转换的接口

现在我需要转换的接口全是nodejs写的数据,而且均为post传输的json格式接口

apiDoc格式

apiDoc代码中的格式如下:

/**
 * @api {方法} 路径 标题
 * @apiGroup Group
 * @apiDescription 描述这个API的信息
 *
 * @apiParam {String} userName 用户名
 * @apiParamExample {json} request-example
 * {
 *  "userName": "Eve"
 * }
 *
 * @apiError {String} message 错误信息
 * @apiErrorExample  {json} error-example
 * {
 *   "message": "用户名不存在"
 * }
 * 
 * 
 * @apiSuccess {String} userName 用户名
 * @apiSuccess {String} createTime 创建时间
 * @apiSuccess {String} updateTime 更新时间
 * @apiSuccessExample  {json} success-example
 * {
 *   "userName": "Eve",
 *   "createTime": "1568901681"
 *   "updateTime": "1568901681"
 * }
 */function getUserInfo(username) {
  // 假如这个函数是根据用户名返回用户信息的
}

使用npm安装apidoc插件:

npm install apidoc

再新建对应的apidoc.json,格式如下:

{
  "name": "文档名",
  "version": "版本号",
  "description": "解释",
  "title": "标题",
  "url" : "地址"
}

然后在apidoc.json路径下执行命令可以生成接口文档(src是接口代码文件夹,apidoc是生成文档的文件夹):

apidoc -i src/ -o apidoc/

生成后可以在apidoc文件夹中打开index.html查看生成的接口文档,生成文档时会生成一个api_data.json,下面会用到

swagger格式

这里我们暂时只需要关注参数为json的接口格式

{
    "swagger": "2.0",
    "info": {
        "description": "1.0版本接口文档",
        "version": "1.0.5",
        "title": "智能医疗辅助平台",
        "termsOfService": "http://swagger.io/terms/"
    },
    "host": "http://localhost:8080",
    "basePath": "/",
    "tags": [],
    "paths": {},
    "definitions": {}
}

其中path是存放接口的,tags是存放的分组名列表,definitions是实体列表(json参数)

思路

使用apidoc包生成apidoc的json格式数据,然后使用python读取出接口地址、名字、组名、输入参数格式和例子、输出参数格式和例子等,然后根据swagger格式填入对应的数据即可生成swagger的json格式

我的话是会直接使用处理出的swagger的json格式的数据导入yApi中

代码

代码虽然在下面,但是是我临时着急用写的,有的地方是写死的,需要改,这里放出来主要是讲个大致的思路

import re
import json
import demjson
import decimal


# 保存时会出现byte格式问题,使用这个处理
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)


# 分析例子转json,在这里可以自己添加规则
def analyze_demjson(json_data):
    item = json_data.replace("\\n", "").replace("\\", "").replace(" ", "")
    result_item = {}
    try:
        result_item = demjson.decode(item, encoding='UTF-8')
    except:
        print(item)
    return result_item


# 获取解析apidoc数据
def get_api_doc_data(name):
    data_list = None
    group_list = {}
    with open(name, mode='r', encoding="UTF-8") as f:
        data_list = json.load(f)
    for data in data_list:
        if data['group'] in group_list:
            group_list[data['group']].append(data)
        else:
            group_list[data['group']] = [data]
    return group_list


# 转为swagger写入
def set_swagger_data(data):
    swagger_json = {
        "swagger": "2.0",
        "info": {
            "description": "1.0版本接口文档",
            "version": "1.0.5",
            "title": "智能医疗辅助平台",
            "termsOfService": "http://swagger.io/terms/"
        },
        "host": "http://localhost:8080",
        "basePath": "/",
        "tags": [],
        "paths": {},
        "definitions": {}
    }
    # 添加分组
    for group_key in data:
        swagger_json['tags'].append({
            "name": group_key,
            "description": group_key
        })
    # 添加接口信息
    # 循环分组
    for group_key in data:
        # 循环每组列表
        for interface in data[group_key]:
            parameters = {}
            if 'parameter' in interface and 'fields' in interface['parameter']:
                # 获取参数demo信息
                content = ""
                if 'examples' in interface['parameter']:
                    content = analyze_demjson(interface['parameter']['examples'][0]['content'])
                # 添加参数信息
                parameter_dict = {}
                for parameter in interface['parameter']['fields']['Parameter']:
                    parameter_type = "None"
                    if "type" in parameter:
                        parameter_type = parameter['type'].lower()
                        if parameter_type == 'number':
                            parameter_type = "integer"
                    parameter_item = {
                        "description": parameter['description'].replace('<p>', '').replace('</p>', ''),
                        "required": parameter['optional'],
                        "type": parameter_type,
                        "default": ''
                    }
                    if parameter['field'] in content:
                        parameter_item['default'] = content[parameter['field']]
                    parameter_dict[parameter['field']] = parameter_item
                parameters = {
                    "in": "body",
                    "name": interface['name'],
                    "description": interface['name'],
                    "required": "true",
                    "schema": {
                        "originalRef": interface['name'],
                        "$ref": "#/definitions/" + interface['name']
                    }
                }
                swagger_json['definitions'][interface['name']] = {
                        "type": "object",
                        "properties": parameter_dict
                    }
            # 添加返回信息
            responses = {
                "200": {
                    "description": "successful operation",
                    "schema": {
                        "originalRef": interface['name'] + "_response",
                        "$ref": "#/definitions/" + interface['name'] + "_response"
                    }
                }
            }
            schema = {
                "type": "object",
                "properties": {
                    "errcode": {
                        "type": "integer",
                        "default": 0,
                        "description": "编码,成功返回1"
                    },
                    "data": {
                        "type": "object",
                        "default": {},
                        "description": "监管对象明细,包含表头和数据内容两部分"
                    },
                    "errmsg": {
                        "type": "string",
                        "default": "ok",
                        "description": '编码提示信息,成功时返回 "ok"'
                    }
                }
            }
            # 返回例子
            if "success" in interface:
                response_example = ""
                if len(interface['success']['examples']) == 1:
                    response_example = analyze_demjson(interface['success']['examples'][0]['content'])
                else:
                    response_example = analyze_demjson(interface['success']['examples']['content'])
                if 'data' in response_example and response_example['data'] != {}:
                    schema['properties']['data'] = response_example['data']
            swagger_json['definitions'][interface['name'] + "_response"] = schema
            # 加入
            swagger_json['paths'][interface['url']] = {
                interface['type']: {
                    "tags": [group_key],
                    "summary": interface['title'].replace(interface['url'] + '-', ''),
                    "description": interface['title'],
                    "consumes": [
                        "application/json"
                    ],
                    "produces": [
                        "application/json"
                    ],
                    "parameters": [parameters],
                    "responses": responses
                }}
    # 写入json文件
    with open('swagger_data.json', 'w', encoding="UTF-8") as json_file:
        json.dump(swagger_json, json_file, cls=DecimalEncoder, indent=4, ensure_ascii=False)


if __name__ == '__main__':
    group_data = get_api_doc_data('api_data.json')
    set_swagger_data(group_data)

到此这篇关于Python实现处理apiDoc转swagger的方法详解的文章就介绍到这了,更多相关Python apiDoc转swagger内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

相关文章

  • Python sklearn CountVectorizer使用详解

    Python sklearn CountVectorizer使用详解

    这篇文章主要介绍了Python_sklearn_CountVectorizer使用详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-03-03
  • pytorch人工智能之torch.gather算子用法示例

    pytorch人工智能之torch.gather算子用法示例

    这篇文章主要介绍了pytorch人工智能之torch.gather算子用法示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • 如何对numpy 矩阵进行通道间求均值

    如何对numpy 矩阵进行通道间求均值

    这篇文章主要介绍了如何对numpy 矩阵进行通道间求均值,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • python分割文件的常用方法

    python分割文件的常用方法

    这篇文章主要介绍了python分割文件的常用方法,包括指定分割大小、按行分割与分割合并等技巧,非常实用,需要的朋友可以参考下
    2014-11-11
  • Python pandas库中isnull函数使用方法

    Python pandas库中isnull函数使用方法

    这篇文章主要介绍了Python pandas库中isnull函数使用方法,python的pandas库中有⼀个⼗分便利的isnull()函数,它可以⽤来判断缺失值,具体介绍需要的小伙伴可以参考一下
    2022-06-06
  • Python批量重命名同一文件夹下文件的方法

    Python批量重命名同一文件夹下文件的方法

    这篇文章主要介绍了Python批量重命名同一文件夹下文件的方法,涉及Python使用os模块操作文件的相关技巧,需要的朋友可以参考下
    2015-05-05
  • 我用Python做个AI出牌器斗地主把把赢

    我用Python做个AI出牌器斗地主把把赢

    这篇文章主要介绍了我是如何用Python做的AI出牌器,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-08-08
  • Python list列表中删除多个重复元素操作示例

    Python list列表中删除多个重复元素操作示例

    这篇文章主要介绍了Python list列表中删除多个重复元素操作,结合实例形式分析了Python删除list列表重复元素的相关操作技巧与注意事项,需要的朋友可以参考下
    2019-02-02
  • Python光学仿真光的偏振编程理解学习

    Python光学仿真光的偏振编程理解学习

    这篇文章主要为大家介绍了通过Python光学仿真来理解光的偏振编程学习,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2021-10-10
  • 详解Python的整数是如何实现的

    详解Python的整数是如何实现的

    本文我们来聊一聊Python的整数,我们知道Python的整数是不会溢出的,换句话说,它可以计算无穷大的数,只要你的内存足够,它就能计算。但问题是,Python底层又是C实现的,那么它是怎么做到整数不溢出的呢?本文就来详细说说
    2022-11-11

最新评论