首页 > 解决方案 > 在 Open Api 3.0.x yaml 格式中使用 $refs,Swagger

问题描述

我正在尝试在 swagger (Open api 3.0.x) 上记录一个 api,但我发现使用 $refs 存在问题。

如此处所写,它按预期工作,但调试器显示我的请求正文定义错误(它缺少内容、应用程序/json、架构)

这样做的正确方法是什么?

/foobarbaz:
    post:   
     requestBody:
        description: lorem ipsum
        content:
          application/json:
            schema:
              oneOf:
                - $ref: '#/components/requestBodies/foo'
                - $ref: '#/components/requestBodies/bar'
                - $ref: '#/components/requestBodies/baz'
        examples:
              foo:
                $ref: '#/components/examples/foo'
              bar:
                $ref: '#/components/examples/bar'
              baz:
                $ref: '#/components/examples/baz'

components:
  requestBodies: 
    foo: <-- here it highlights (Missing property "$ref".)
    schema
     type: object
      properties:
        foo:
          type: string
        bar:
          type: string
    bar: <-- here it highlights (Missing property "$ref".)
    schema
     type: object
      properties:
        foo:
          type: string
        bar:
          type: string
    baz: <-- here it highlights (Missing property "$ref".)
    schema
     type: object
      properties:
        foo:
          type: string
        bar:
          type: string

  examples:
    foo:
      value:
        foo: 'bar'
        bar: '20'
    bar:
      value:
        foo: 'bar'
        bar: '20'
    baz:
      value:
        foo: 'bar'
        bar: '20'

标签: swaggerswagger-uiopenapi

解决方案


oneOf只能 $ref 模式,不能 requestBody 组件。这是正确的版本:

  /foobarbaz:
    post:   
     requestBody:
        description: lorem ipsum
        content:
          application/json:
            schema:
              oneOf:
                - $ref: '#/components/schemas/foo'  # <--- $refs point to schemas, not requestBodies
                - $ref: '#/components/schemas/bar'
                - $ref: '#/components/schemas/baz'
        examples:
          ...

components:
  schemas:   # <--- Put the schemas in the "schemas" section rather than "requestBodies"
    foo:
      type: object
      properties:
        foo:
          type: string
        bar:
          type: string
    bar:
      type: object
      properties:
        foo:
          type: string
        bar:
          type: string
    baz:
      type: object
      properties:
        foo:
          type: string
        bar:
          type: string

推荐阅读