最近我们公司所有接口文档放在swagger中,一直想统计接口总数量奈何搜索不到好的方法,只能通过python转到Excel中,也方便jmeter循环跑接口时配置CSV文件使用,经过网上各种方法实验,终于解决了该问题,方便想转Excel文档的同学,也方便统计数量。
1.首先将swagger保存为文档
点击左上角IP地址,会出现json文档,右键另存为,可以保存为.json格式的文档,保存修改文档后缀为txt格式。
2.解析json,分析你要取接口地址的内容所在位置,找到提取数据的方式
通过解析我们发现所有接口信息都放在paths这个key里面,每个接口地址为一个子key,如下图:
3.使用Python脚本提取数据并写入Excel中
我基本整个系统模块接口共有上千个,比较多,为了将来使用方便,除接口地址外,顺便提取了请求方式,接口分类,接口描述,方便以后在Excel表格中分类整理取想要的接口;Python脚本如下:
import json
import xlwt
api_excel = xlwt.Workbook(encoding='utf-8') # 创建一个文档
api_sheet = api_excel.add_sheet('listview接口') # 添加一个sheet
json_file = open('D:\\jmxreport\\api-docs.txt', encoding='utf-8') # 打开保存的swagger文本文档
api_data = json.load(json_file) # 将文档json内容转换为Python对象
api = api_data['paths'] # 取swagger文件内容中的path,文件中path是键名
path_list = [] # 创建接口地址空列表
method_list = [] # 创建请求方式空列表
tags_list = [] # 创建接口分类空列表
summary_list = [] # 创建接口描述空列表
for path in api.keys(): # 循环取key
values = api[path] # 根据key获取值
method = tuple(values.keys())[0] # 获取请求方式,文件中请求方式是key
path_list.append(path) # 将path写入接口地址列表中
method_list.append(method) # 将method写入请求方式列表中
if method == 'get': # key为get时从get里面取分类和描述,key为post时从post里面取分类和描述
tags = values['get']['tags'][0] # 获取接口分类
summary = values['get']['summary'] # 获取接口描述
tags_list.append(tags) # 将接口分类写入列表中
summary_list.append(summary) # 将接口描述写入列表中
if method == 'post':
tags = values['post']['tags'][0]
summary = values['post']['summary']
tags_list.append(tags)
summary_list.append(summary)
for i in range(len(path_list)): # 将接口path循环写入第一列
api_sheet.write(i, 0, path_list[i])
for j in range(len(method_list)): # 将请求方式循环写入第二列
api_sheet.write(j, 1, method_list[j])
for m in range(len(tags_list)): # 将接口分类循环写入第三列
api_sheet.write(m, 2, tags_list[m])
for n in range(len(summary_list)): # 将接口描述循环写入第四列
api_sheet.write(n, 3, summary_list[n])
api_excel.save('D:\\jmxreport\\listview接口列表.xls') # 保存文件
运行结果:
---The End---
后续有好的统计或者转换方法还会继续更新,欢迎大家一起交流互助。
如果对你有帮助请关注哦!