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

如何从单个OpenAPI文档中提取指定API至新文档?

自动化提取OpenAPI指定路径及关联模型的方案

当然可以自动化这个流程,以下是几种实用的实现方式:

1. 编写Python脚本自定义处理

利用Python的YAML/JSON解析库,结合引用追踪逻辑,实现精准过滤:

核心思路

  • 加载原始OpenAPI文档
  • 筛选保留目标路径
  • 递归追踪这些路径中所有引用的Schema(包括嵌套依赖)
  • 提取关联Schema并生成新文档

示例代码

import yaml
from collections import deque

def filter_openapi(original_file, output_file, target_paths):
    # 读取原始OpenAPI文件
    with open(original_file, 'r', encoding='utf-8') as f:
        openapi_doc = yaml.safe_load(f)
    
    # 过滤目标路径
    filtered_paths = {p: openapi_doc['paths'][p] for p in target_paths if p in openapi_doc['paths']}
    openapi_doc['paths'] = filtered_paths
    
    # 收集所有需要保留的Schema(含嵌套引用)
    required_schemas = set()
    ref_queue = deque()

    # 遍历路径中的请求/响应,收集顶层引用
    for path_ops in filtered_paths.values():
        for op_details in path_ops.values():
            # 处理请求体Schema
            if 'requestBody' in op_details:
                for content in op_details['requestBody']['content'].values():
                    if '$ref' in content.get('schema', {}):
                        schema_name = content['schema']['$ref'].split('/')[-1]
                        ref_queue.append(schema_name)
            # 处理响应Schema
            if 'responses' in op_details:
                for resp in op_details['responses'].values():
                    for content in resp.get('content', {}).values():
                        if '$ref' in content.get('schema', {}):
                            schema_name = content['schema']['$ref'].split('/')[-1]
                            ref_queue.append(schema_name)
    
    # 递归处理嵌套Schema引用
    while ref_queue:
        current_schema = ref_queue.popleft()
        if current_schema not in required_schemas and current_schema in openapi_doc['components']['schemas']:
            required_schemas.add(current_schema)
            schema = openapi_doc['components']['schemas'][current_schema]
            
            # 处理属性中的嵌套引用
            for prop in schema.get('properties', {}).values():
                if '$ref' in prop:
                    ref_queue.append(prop['$ref'].split('/')[-1])
            
            # 处理allOf/anyOf/oneOf中的引用
            for composite_key in ['allOf', 'anyOf', 'oneOf']:
                for item in schema.get(composite_key, []):
                    if '$ref' in item:
                        ref_queue.append(item['$ref'].split('/')[-1])
    
    # 过滤Schema集合
    openapi_doc['components']['schemas'] = {
        name: openapi_doc['components']['schemas'][name] 
        for name in required_schemas
    }
    
    # 保存过滤后的文档
    with open(output_file, 'w', encoding='utf-8') as f:
        yaml.dump(openapi_doc, f, sort_keys=False, allow_unicode=True)

# 调用示例:保留指定路径
filter_openapi(
    original_file='full_openapi.yaml',
    output_file='gateway_openapi.yaml',
    target_paths=['/api/v1/users', '/api/v1/orders/{id}']
)

2. 使用现成的命令行工具

如果不想写代码,可以用openapi-filter(Node.js工具),它会自动处理路径和关联Schema的过滤:

步骤

  1. 安装工具:npm install -g openapi-filter
  2. 执行过滤命令:
openapi-filter --paths "/api/v1/users,/api/v1/orders/{id}" full_openapi.yaml > gateway_openapi.yaml

该工具会自动识别路径中引用的所有Schema(包括嵌套依赖),无需手动处理引用链。

3. 扩展处理复杂场景

如果你的OpenAPI文档包含特殊结构(如公共参数、自定义扩展),可以在脚本中添加额外逻辑:

  • 保留components/parameters中被目标路径引用的公共参数
  • 保留components/securitySchemes等网关需要的配置
  • 用openapi-spec-validator库校验过滤后的文档是否符合规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:06:33