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

如何批量移除Swagger文档中的user-id参数及示例字段?

处理Swagger YAML的两种实用方案

方案一:用yq命令行工具(快速高效)

yq是专门处理YAML的命令行工具,能直接完成你的需求,不需要给参数加特殊标签。

安装yq

  • macOS:brew install yq
  • Linux:通过对应包管理器安装或下载官方二进制文件
  • Windows:choco install yq

执行命令

针对你的swagger.yaml文件,运行以下命令即可生成清理后的文件:

yq eval 'del(.. | .parameters[]? | select(.name == "user-id")) | del(.. | .example, .x-example)' swagger.yaml > cleaned_swagger.yaml

命令说明:

  • del(.. | .parameters[]? | select(.name == "user-id")):递归遍历所有参数数组,删除名为user-id的参数项
  • del(.. | .example, .x-example):递归删除所有层级的example和x-example字段
  • 最终结果会写入cleaned_swagger.yaml文件

方案二:Python脚本(灵活可控)

如果需要更定制化的处理逻辑,用Python脚本会更灵活,依赖PyYAML库。

步骤1:安装依赖

pip install pyyaml

步骤2:编写清理脚本(命名为clean_swagger.py)

import yaml

def clean_swagger(input_file, output_file):
    # 读取原Swagger文件
    with open(input_file, 'r', encoding='utf-8') as f:
        swagger_data = yaml.safe_load(f)
    
    # 遍历所有路径下的API操作
    for path_item in swagger_data.get('paths', {}).values():
        for operation in path_item.values():
            # 处理参数:移除user-id
            if 'parameters' in operation:
                # 过滤掉user-id参数
                operation['parameters'] = [
                    param for param in operation['parameters']
                    if param.get('name') != 'user-id'
                ]
                # 移除每个参数里的example和x-example字段
                for param in operation['parameters']:
                    param.pop('example', None)
                    param.pop('x-example', None)
    
    # 写入处理后的文件
    with open(output_file, 'w', encoding='utf-8') as f:
        yaml.dump(swagger_data, f, sort_keys=False, default_flow_style=False)

if __name__ == '__main__':
    clean_swagger('swagger.yaml', 'cleaned_swagger.yaml')

运行脚本

python clean_swagger.py

效果验证

以你提供的示例为例:
原参数块:

parameters:
  - name: action-id
    in: path
    description: Action ID which needs to be failed
    required: true
    type: integer
    format: int64
    x-example: 1
  - name: action-category-number
    in: path
    description: Action category number which needs to be failed
    required: true
    type: integer
    format: int64
    example: 2
  - name: user-id
    in: header
    description: User under which the action exists
    required: true
    type: integer
    format: int32
    x-example: 1

处理后会变成:

parameters:
  - name: action-id
    in: path
    description: Action ID which needs to be failed
    required: true
    type: integer
    format: int64
  - name: action-category-number
    in: path
    description: Action category number which needs to be failed
    required: true
    type: integer
    format: int64

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:15:13