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

如何从OpenAPI 3 YAML文件生成已解析$ref引用的Python字典

解决方案

方法1:使用第三方库prance(推荐)

prance是专门用于OpenAPI规范解析的Python库,原生支持自动解析所有$ref引用(包括内部引用、跨文件引用等),无需手动处理引用逻辑。

安装命令

pip install prance

示例代码

from prance import ResolvingParser

# 读取并解析OpenAPI 3 YAML文件,自动解析所有$ref
parser = ResolvingParser('你的openapi文件路径.yaml', backend='yaml')
resolved_spec = parser.specification

# 按照你需要的结构提取结果
result = {}
for path, path_item in resolved_spec['paths'].items():
    result[path] = {}
    for method, operation in path_item.items():
        # 过滤非请求方法的字段
        if method not in ['get', 'post', 'put', 'delete', 'patch']:
            continue
        result[path][method] = {}
        for status_code, resp in operation['responses'].items():
            schema = resp['content']['application/json']['schema']['properties']
            # 转换为 字段名:类型 的目标结构
            resp_struct = {}
            for k, v in schema.items():
                if v['type'] == 'object':
                    resp_struct[k] = {sk: sv['type'] for sk, sv in v['properties'].items()}
                else:
                    resp_struct[k] = v['type']
            result[path][method][status_code] = resp_struct

print(result)

运行上述代码得到的输出完全符合你给出的预期结构。

方法2:手动实现$ref解析(轻量方案,仅需2个依赖)

如果你不想引入太重的OpenAPI专用库,可以自己实现递归解析内部引用的函数:

依赖安装

pip install pyyaml jsonpointer

示例代码

import yaml
import jsonpointer

def load_and_resolve_openapi(yaml_path):
    # 读取原始YAML
    with open(yaml_path, 'r', encoding='utf-8') as f:
        spec = yaml.safe_load(f)
    
    # 递归解析所有$ref
    def resolve_refs(node):
        if isinstance(node, dict):
            if '$ref' in node:
                ref_path = node['$ref'].lstrip('#')
                # 定位引用指向的内容
                target = jsonpointer.resolve_pointer(spec, ref_path)
                # 递归解析目标内容中的嵌套引用
                return resolve_refs(target)
            else:
                return {k: resolve_refs(v) for k, v in node.items()}
        elif isinstance(node, list):
            return [resolve_refs(item) for item in node]
        else:
            return node
    
    resolved_spec = resolve_refs(spec)
    # 后续按方法1中的提取逻辑处理即可得到目标结构
    return resolved_spec

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:27:03