需求来源
公司业务系统中,API文档定义使用了Swagger,由于多人开发中每个人开发的节点不同,整体的业务过于复杂,维护一套完整的 API 文档十分繁重,且容易出现误修改,所以用 python 实现了多个 yaml 文件 OpenAPI 文档合并工具。
Open API 相关资料
推荐阅读
Writing OpenAPI (Swagger) Specification Tutorial
https://apihandyman.io/writing-openapi-swagger-specification-tutorial-part-1-introduction/Swagger 从入门到精通 (第一个链接的译文)
https://www.gitbook.com/book/huangwenchao/swagger/detailsOpenAPI Specification 2.0 (手册,无需通读)
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md
推荐工具
- Prism (OpenAPI Mock 工具)
http://stoplight.io/platform/prism/
YAML示例
swagger: "2.0"
info:
version: "0.0.1"
title: XXX
description: XXX
host: localhost:4010
schemes:
- http
basePath: /api/v1
produces:
- application/json
paths:
... # 路由项
definitions:
... # 定义项
responses:
... # 响应消息中定义项
parameters:
... # 路径参数定义项
核心逻辑
1. 各个模块(paths,definitions等)的查找分离
def findstring(all_the_text):
head_string = re.search(r".*paths:", all_the_text, re.S).group()
# 删除 paths: 之上的头部信息
all_the_text = all_the_text.replace(head_string, '\npaths:')
# 获取模块名,以此为匹配条件
module_name_strings = re.findall(r"(\n\w*:)", all_the_text, re.S)
# print(module_name_strings)
# 新建字典存放模块内容
modules = {}
for i in range(len(module_name_strings)):
if i + 1 <len(module_name_strings):
modules[(module_name_strings[i].replace("\n","").replace(":",""))] = \
re.search(module_name_strings[i]+".*"+module_name_strings[i+1], all_the_text, re.S).group()\
.replace(module_name_strings[i],"").replace(module_name_strings[i+1],"")
else:
modules[(module_name_strings[i].replace("\n","").replace(":",""))] = \
re.search(module_name_strings[i]+".*", all_the_text, re.S).group().replace(module_name_strings[i],"")
# 应用平移函数