如何在Swagger中复用正则模式 避免parameters与schemas重复定义
OpenAPI 3 正则模式全局复用方案
你可以通过抽离公共Schema实现仅声明一次正则,全文档复用,操作步骤如下:
步骤1:新增通用正则Schema
在components/schemas下新增公共的UUID格式Schema,统一存放正则规则:
components: schemas: # 新增通用UUID规则,所有需要UUID校验的位置直接引用即可 UUID: type: string format: uuid pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' # 原有其他Schema保留,仅替换UUID相关的字段定义 Request: type: object properties: data: type: object properties: type: type: string id: $ref: '#/components/schemas/UUID' # 替换原有重复的pattern定义 Data: type: object properties: type: type: string id: $ref: '#/components/schemas/UUID' # 替换原有重复的pattern定义 GeometryError: type: object required: - code - status - title properties: id: $ref: '#/components/schemas/UUID' # 替换原有重复的pattern定义 status: type: string example: 400 title: type: string detail: type: string meta: type: object
步骤2:路径参数复用规则
有两种复用层级可选,按需使用:
- 仅复用正则规则:路径参数的schema直接引用公共UUID Schema
parameters: - name: xId in: path required: true schema: $ref: '#/components/schemas/UUID' # 直接引用通用规则,无需重复写pattern - name: yId in: path required: true schema: $ref: '#/components/schemas/UUID' - name: zId in: path required: true schema: $ref: '#/components/schemas/UUID'
- 全参数配置复用:如果参数的名称、位置、必填属性都固定,可以进一步抽离为公共参数,减少更多重复代码:
首先在components下新增parameters节点:
components: parameters: XIdParam: name: xId in: path required: true schema: $ref: '#/components/schemas/UUID' YIdParam: name: yId in: path required: true schema: $ref: '#/components/schemas/UUID' ZIdParam: name: zId in: path required: true schema: $ref: '#/components/schemas/UUID'
之后路径下的参数可以直接引用公共参数配置:
paths: "/x/{xId}/y/{yId}/z/{zId}": get: parameters: - $ref: '#/components/parameters/XIdParam' - $ref: '#/components/parameters/YIdParam' - $ref: '#/components/parameters/ZIdParam' patch: parameters: - $ref: '#/components/parameters/XIdParam' - $ref: '#/components/parameters/YIdParam' - $ref: '#/components/parameters/ZIdParam'
修改完成后,整个文档仅需维护一处UUID正则规则,所有引用位置会自动同步规则,所有兼容OpenAPI 3.0规范的解析工具都可以正常识别该配置。
内容的提问来源于stack exchange,提问作者Gaurav Jeswani
相关产品推荐
相关产品推荐

