You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中解析OpenAPI 3 YAML文件获取请求/响应体

在Python中解析OpenAPI 3 YAML文件获取请求/响应体示例

问题背景

之前用的Swagger Parser只支持Swagger 2.0规范,没法处理OpenAPI 3格式的YAML文件,现在需要从OpenAPI 3配置里提取接口的请求/响应体,生成对应的JSON示例。

解决思路

用支持OpenAPI 3的Python工具链:先加载解析YAML规范,自动处理Schema里的$ref、allOf这类引用和组合规则,再基于解析后的Schema生成符合要求的JSON示例数据。

具体实现步骤

  1. 安装依赖库
    需要三个核心工具:pyyaml读取YAML文件,openapi-core解析OpenAPI 3规范,hypothesis-jsonschema生成Schema对应的示例数据。

    pip install pyyaml openapi-core hypothesis-jsonschema
    
  2. 编写解析代码

    import yaml
    from openapi_core import OpenAPICore
    from hypothesis_jsonschema import from_schema
    import json
    
    # 加载本地OpenAPI 3 YAML文件
    with open('petstore.yaml', 'r', encoding='utf-8') as f:
        openapi_spec = yaml.safe_load(f)
    
    # 初始化OpenAPI解析器
    core_parser = OpenAPICore(openapi_spec)
    
    # 示例1:获取/pets POST接口的请求体示例
    post_pet_op = core_parser.spec.paths['/pets'].operations['post']
    req_schema = post_pet_op.request_body.content['application/json'].schema
    req_example = from_schema(req_schema).example()
    print("POST /pets 请求体示例:")
    print(json.dumps(req_example, indent=2))
    
    # 示例2:获取/pets/{id} GET接口的200响应体示例
    get_pet_op = core_parser.spec.paths['/pets/{id}'].operations['get']
    resp_schema = get_pet_op.responses['200'].content['application/json'].schema
    resp_example = from_schema(resp_schema).example()
    print("\nGET /pets/{id} 200响应体示例:")
    print(json.dumps(resp_example, indent=2))
    

注意事项

  • 规范里的allOf、anyOf等组合Schema,openapi-core会自动合并解析,不用手动处理引用关系。
  • 生成的示例是随机符合Schema规则的,要是需要固定默认值,可以在Schema里添加example字段,工具会优先用这个值生成示例。
  • 如果当前YAML是Swagger 2.0格式,得先转成OpenAPI 3格式再解析。

内容的提问来源于stack exchange,提问作者mohit nayak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 01:02:18