Python 实现 Swagger yaml 格式 api 文档合并

本文档介绍了一个使用Python编写的工具,用于合并多个Swagger YAML格式的OpenAPI文档。该工具解决了多人开发中API文档维护的问题,通过查找分离各个模块、处理行首空格不一致以及检测并合并重复定义,简化了API文档的维护工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求来源

公司业务系统中,API文档定义使用了Swagger,由于多人开发中每个人开发的节点不同,整体的业务过于复杂,维护一套完整的 API 文档十分繁重,且容易出现误修改,所以用 python 实现了多个 yaml 文件 OpenAPI 文档合并工具。

Open API 相关资料

推荐阅读
  1. Writing OpenAPI (Swagger) Specification Tutorial
    https://apihandyman.io/writing-openapi-swagger-specification-tutorial-part-1-introduction/

  2. Swagger 从入门到精通 (第一个链接的译文)
    https://www.gitbook.com/book/huangwenchao/swagger/details

  3. OpenAPI Specification 2.0 (手册,无需通读)
    https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md

推荐工具
  1. 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],
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值