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的更多相关文章

  1. python的apidoc使用

    一.apidoc的安装 npm install apidoc -g -g参数表示全局安装,这样在哪儿都能使用. 二.apidoc在python接口代码中的使用 def index(): "& ...

  2. ApiDoc 和 Swagger 接口文档

    ApiDoc:https://blog.csdn.net/weixin_38682852/article/details/78812244 Swagger git: https://github.co ...

  3. [aspnetcore.apidoc]一款很不错的api文档生成工具

    AspNetCore.ApiDoc 简单徐速一下为什么选用了aspnetcore.apidoc 而没有选用swagger 最初我们也有在试用swagger,但总是有些感觉,感觉有点不满意,就但从api ...

  4. swagger学习

    https://segmentfault.com/a/1190000010144742 https://segmentfault.com/a/1190000014775124 https://blog ...

  5. 【转载】Java Restful API 文档生成工具 smart-doc

    谁说生成api文档就必须要定义注解? 谁说生成接口请求和返回示例必须要在线? 用代码去探路,不断尝试更多文档交付的可能性. 如果代码有生命,为什么不换种方式和它对话! 一.背景 没有背景.就自己做自己 ...

  6. 【Flask-RESTPlus系列】Flask-RESTPlus系列译文开篇

    0x00 背景介绍 因为工作上的需要,最近开始研究Python中实现Restful API的框架和工具包.之前粗略学习过Flask,由于它比较轻量级,感觉用它来实现Restful API再适合不过了. ...

  7. Spring boot 添加日志 和 生成接口文档

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring- ...

  8. Paw —— 比Postman更舒服的API利器

    特点: 颜值高本地应用,流畅有收藏夹,管理请求可使用环境变量.比如用来一键切换开发环境请求和线上环境请求.即不同环境的同个接口只有host不一样,其它都是一样的,所以就把host抽离出来弄成一个环境变 ...

  9. OpenAPITools 实践

    OpenAPITools 可以依据 REST API 描述文件,自动生成服务端桩(Stub)代码.客户端 SDK 代码,及文档等.其是社区版的 Swagger ,差异可见:OpenAPI Genera ...

  10. Error generating Swagger server (Python Flask) from Swagger editor

    1down votefavorite   http://stackoverflow.com/questions/36416679/error-generating-swagger-server-pyt ...

随机推荐

  1. 部署redis-cluster

    1.环境准备 ☆ 每个Redis 节点采用相同的相同的Redis版本.相同的密码.硬件配置 ☆ 所有Redis服务器必须没有任何数据 #所有主从节点执行: [root@ubuntu2004 ~]#ba ...

  2. Spring Boot:自定义 Whitelabel 错误页面

    一.概述在本文中,我们将研究如何禁用和自定义 Spring Boot 应用程序的默认错误页面,因为正确的错误处理描述了专业性和质量工作. 2.禁用白标错误页面 首先,让我们看看如何通过将server. ...

  3. 在CentOS7下安装Oracle11教程

    前言 安装oracle时,发现网上的文章总是缺少一些信息,导致安装不顺利,因为我对一些文章进行了整合,用以备忘. Oracle安装 首先下载linux版本的oracle安装文件,然后通过XFTP上传到 ...

  4. 我服了!SpringBoot升级后这服务我一个星期都没跑起来!(上)

    最近由于各方面的原因在准备升级 Spring Cloud 和 Spring Boot,经过一系列前置的调研和分析,决定把Spring Boot 相关版本从 2.1.6 升级到 2.7.5,Spring ...

  5. 重新认识下JVM级别的本地缓存框架Guava Cache——优秀从何而来

    大家好,又见面了. 本文是笔者作为掘金技术社区签约作者的身份输出的缓存专栏系列内容,将会通过系列专题,讲清楚缓存的方方面面.如果感兴趣,欢迎关注以获取后续更新. 不知不觉,这已经是<深入理解缓存 ...

  6. 关于小米mini路由器开启ssh红灯解决

    前言 小米 后续版本 对 ssh固件校验失败导致的,下载路由器旧版开发版固件,然后用后台web升级成老版本后,再采用官方方法刷入即可. 旧版路由器固件下载 地址 其他 后续的刷机可以参考我的文章

  7. Jmeter中用户定义的变量跟用户参数的区别

    用户定义的变量: 全局变量,可以跨线程组被调用,但是,在启动运行时,获取一次值,在运行过程中,不会再动态获取值.用户参数: 局部变量,只能在自己的线程组中被调用,不能直接跨线程组被调用:但是,它在启动 ...

  8. JDBC Request 中 Variable names 以及 Result variable name 的使用方法

    1.Variable name 的使用方法 设置好JDBC Connection Configuration.JDBC Request  具体配置百度 如果数据库查询的结果不止一列那就在Variabl ...

  9. 2023年 DevOps 七大趋势

    随着时间的推移,很明显 DevOps 已经成为最高效的敏捷框架中的无人不知晓的名字.越来越多的企业(包括各类规模企业)正在采用 DevOps 方法来简化其运营效率.DevOps 的新时代趋势已经见证了 ...

  10. 【ASP.NET Core】MVC控制器的各种自定义:特性化的路由规则

    MVC的路由规则配置方式比较多,咱们用得最多的是两种: A.全局规则.就是我们熟悉的"{controller}/{action}". app.MapControllerRoute( ...