翼度科技»论坛 编程开发 python 查看内容

python处理apiDoc转swagger

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
python处理apiDoc转swagger

需要转换的接口

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

apiDoc代码中的格式如下:
  1. /**
  2. * @api {方法} 路径 标题
  3. * @apiGroup Group
  4. * @apiDescription 描述这个API的信息
  5. *
  6. * @apiParam {String} userName 用户名
  7. * @apiParamExample {json} request-example
  8. * {
  9. *  "userName": "Eve"
  10. * }
  11. *
  12. * @apiError {String} message 错误信息
  13. * @apiErrorExample  {json} error-example
  14. * {
  15. *   "message": "用户名不存在"
  16. * }
  17. *
  18. *
  19. * @apiSuccess {String} userName 用户名
  20. * @apiSuccess {String} createTime 创建时间
  21. * @apiSuccess {String} updateTime 更新时间
  22. * @apiSuccessExample  {json} success-example
  23. * {
  24. *   "userName": "Eve",
  25. *   "createTime": "1568901681"
  26. *   "updateTime": "1568901681"
  27. * }
  28. */function getUserInfo(username) {
  29.   // 假如这个函数是根据用户名返回用户信息的
  30. }
复制代码
使用npm安装apidoc插件:
  1. npm install apidoc
复制代码
再新建对应的apidoc.json,格式如下:
  1. {
  2.   "name": "文档名",
  3.   "version": "版本号",
  4.   "description": "解释",
  5.   "title": "标题",
  6.   "url" : "地址"
  7. }
复制代码
然后在apidoc.json路径下执行命令可以生成接口文档(src是接口代码文件夹,apidoc是生成文档的文件夹):
  1. apidoc -i src/ -o apidoc/
复制代码
生成后可以在apidoc文件夹中打开index.html查看生成的接口文档,生成文档时会生成一个api_data.json,下面会用到
swagger格式

这里我们暂时只需要关注参数为json的接口格式
  1. {
  2.     "swagger": "2.0",
  3.     "info": {
  4.         "description": "1.0版本接口文档",
  5.         "version": "1.0.5",
  6.         "title": "智能医疗辅助平台",
  7.         "termsOfService": "http://swagger.io/terms/"
  8.     },
  9.     "host": "http://localhost:8080",
  10.     "basePath": "/",
  11.     "tags": [],
  12.     "paths": {},
  13.     "definitions": {}
  14. }
复制代码
其中path是存放接口的,tags是存放的分组名列表,definitions是实体列表(json参数)
思路

使用apidoc包生成apidoc的json格式数据,然后使用python读取出接口地址、名字、组名、输入参数格式和例子、输出参数格式和例子等,然后根据swagger格式填入对应的数据即可生成swagger的json格式
我的话是会直接使用处理出的swagger的json格式的数据导入yApi中
代码

代码虽然在下面,但是是我临时着急用写的,有的地方是写死的,需要改,这里放出来主要是讲个大致的思路
  1. import re
  2. import json
  3. import demjson
  4. import decimal
  5. # 保存时会出现byte格式问题,使用这个处理
  6. class DecimalEncoder(json.JSONEncoder):
  7.     def default(self, o):
  8.         if isinstance(o, decimal.Decimal):
  9.             return float(o)
  10.         super(DecimalEncoder, self).default(o)
  11. # 分析例子转json,在这里可以自己添加规则
  12. def analyze_demjson(json_data):
  13.     item = json_data.replace("\\n", "").replace("\", "").replace(" ", "")
  14.     result_item = {}
  15.     try:
  16.         result_item = demjson.decode(item, encoding='UTF-8')
  17.     except:
  18.         print(item)
  19.     return result_item
  20. # 获取解析apidoc数据
  21. def get_api_doc_data(name):
  22.     data_list = None
  23.     group_list = {}
  24.     with open(name, mode='r', encoding="UTF-8") as f:
  25.         data_list = json.load(f)
  26.     for data in data_list:
  27.         if data['group'] in group_list:
  28.             group_list[data['group']].append(data)
  29.         else:
  30.             group_list[data['group']] = [data]
  31.     return group_list
  32. # 转为swagger写入
  33. def set_swagger_data(data):
  34.     swagger_json = {
  35.         "swagger": "2.0",
  36.         "info": {
  37.             "description": "1.0版本接口文档",
  38.             "version": "1.0.5",
  39.             "title": "智能医疗辅助平台",
  40.             "termsOfService": "http://swagger.io/terms/"
  41.         },
  42.         "host": "http://localhost:8080",
  43.         "basePath": "/",
  44.         "tags": [],
  45.         "paths": {},
  46.         "definitions": {}
  47.     }
  48.     # 添加分组
  49.     for group_key in data:
  50.         swagger_json['tags'].append({
  51.             "name": group_key,
  52.             "description": group_key
  53.         })
  54.     # 添加接口信息
  55.     # 循环分组
  56.     for group_key in data:
  57.         # 循环每组列表
  58.         for interface in data[group_key]:
  59.             parameters = {}
  60.             if 'parameter' in interface and 'fields' in interface['parameter']:
  61.                 # 获取参数demo信息
  62.                 content = ""
  63.                 if 'examples' in interface['parameter']:
  64.                     content = analyze_demjson(interface['parameter']['examples'][0]['content'])
  65.                 # 添加参数信息
  66.                 parameter_dict = {}
  67.                 for parameter in interface['parameter']['fields']['Parameter']:
  68.                     parameter_type = "None"
  69.                     if "type" in parameter:
  70.                         parameter_type = parameter['type'].lower()
  71.                         if parameter_type == 'number':
  72.                             parameter_type = "integer"
  73.                     parameter_item = {
  74.                         "description": parameter['description'].replace('<p>', '').replace('</p>', ''),
  75.                         "required": parameter['optional'],
  76.                         "type": parameter_type,
  77.                         "default": ''
  78.                     }
  79.                     if parameter['field'] in content:
  80.                         parameter_item['default'] = content[parameter['field']]
  81.                     parameter_dict[parameter['field']] = parameter_item
  82.                 parameters = {
  83.                     "in": "body",
  84.                     "name": interface['name'],
  85.                     "description": interface['name'],
  86.                     "required": "true",
  87.                     "schema": {
  88.                         "originalRef": interface['name'],
  89.                         "$ref": "#/definitions/" + interface['name']
  90.                     }
  91.                 }
  92.                 swagger_json['definitions'][interface['name']] = {
  93.                         "type": "object",
  94.                         "properties": parameter_dict
  95.                     }
  96.             # 添加返回信息
  97.             responses = {
  98.                 "200": {
  99.                     "description": "successful operation",
  100.                     "schema": {
  101.                         "originalRef": interface['name'] + "_response",
  102.                         "$ref": "#/definitions/" + interface['name'] + "_response"
  103.                     }
  104.                 }
  105.             }
  106.             schema = {
  107.                 "type": "object",
  108.                 "properties": {
  109.                     "errcode": {
  110.                         "type": "integer",
  111.                         "default": 0,
  112.                         "description": "编码,成功返回1"
  113.                     },
  114.                     "data": {
  115.                         "type": "object",
  116.                         "default": {},
  117.                         "description": "监管对象明细,包含表头和数据内容两部分"
  118.                     },
  119.                     "errmsg": {
  120.                         "type": "string",
  121.                         "default": "ok",
  122.                         "description": '编码提示信息,成功时返回 "ok"'
  123.                     }
  124.                 }
  125.             }
  126.             # 返回例子
  127.             if "success" in interface:
  128.                 response_example = ""
  129.                 if len(interface['success']['examples']) == 1:
  130.                     response_example = analyze_demjson(interface['success']['examples'][0]['content'])
  131.                 else:
  132.                     response_example = analyze_demjson(interface['success']['examples']['content'])
  133.                 if 'data' in response_example and response_example['data'] != {}:
  134.                     schema['properties']['data'] = response_example['data']
  135.             swagger_json['definitions'][interface['name'] + "_response"] = schema
  136.             # 加入
  137.             swagger_json['paths'][interface['url']] = {
  138.                 interface['type']: {
  139.                     "tags": [group_key],
  140.                     "summary": interface['title'].replace(interface['url'] + '-', ''),
  141.                     "description": interface['title'],
  142.                     "consumes": [
  143.                         "application/json"
  144.                     ],
  145.                     "produces": [
  146.                         "application/json"
  147.                     ],
  148.                     "parameters": [parameters],
  149.                     "responses": responses
  150.                 }}
  151.     # 写入json文件
  152.     with open('swagger_data.json', 'w', encoding="UTF-8") as json_file:
  153.         json.dump(swagger_json, json_file, cls=DecimalEncoder, indent=4, ensure_ascii=False)
  154. if __name__ == '__main__':
  155.     group_data = get_api_doc_data('api_data.json')
  156.     set_swagger_data(group_data)
复制代码
来源:https://www.cnblogs.com/baby7/p/python_apidoc_to_swagger.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具