提问者:小点点

如何在OpenAPI(Swagger)中为同一路径定义不同的身体参数?


我有一个服务,它可以基于Content-Type头有两种不同的主体参数。

例如。对于路径/Pet

>

  • 如果使用 Content-Type: application/somecustom.resource json,则 POST 可以将 Pet 作为正文参数。

    如果使用了Content-Type: Application/somecustom.functionjson,那么POST应该使用一些不同的主体参数来调用函数并返回不同的响应。

    关于如何在OpenAPI(Swagger)中体现这一点,有什么建议吗?


  • 共2个答案

    匿名用户

    OpenAPI 3.0 支持每种媒体类型的不同架构。

    openapi: 3.0.0
    ...
    paths:
      /pet:
        post:
          requestBody:
            required: true
            content:
              application/somecustom.resource+json:
                schema:
                  $ref: '#/components/schemas/Pet'
              application/somecustom.function+json:
                schema:
                  $ref: '#/components/schemas/Foo'
    

    匿名用户

    不,不可能在同一路径项中为同一操作定义两个不同的主体参数。路径项名称是唯一的,因为它是属性名称(因此也是JSON键值映射中的“键”),Swager规范允许在给定操作中最多有一个主体参数。

    有几种替代方法可以满足这一需求:

    创建两个单独的路径项

    例如:

    /pets/createFromDescription:
      post:
        summary: Create a pet from a basic description
        operationId: createPetFromDescription
        parameters:
          - name: petDescription
            in: body
            required: true
            schema:
              $ref: "#/definitions/PetDescriptionObject"
        responses:
          200:
            description: OK
    /pets/createFromCatalog:
      post:
        summary: Create a pet from a standard catalog entry
        operationId: createPetFromCatalogEntry
        parameters:
          - name: petCatalogEntry
            in: body
            required: true
            schema:
              $ref: "#/definitions/PetCatalogEntry"
        responses:
          200:
            description: OK
    

    使用鉴别器创建子类型

    在Swagger–open API 2.0规范中有所描述。

    例:

    /pets:
      post:
        summary: Create a pet 
        operationId: createPet
        parameters:
          - name: petSource
            in: body
            description: Structured pet information, from which to create the object 
            required: true
            schema:
              $ref: "#/definitions/CreatePet_Request"
        responses:
          200:
            description: OK
    
    definitions:
      CreatePet_Request:
        type: object
        properties:
          requestVariant:
            type: string
        required:
        - requestVariant
        discriminator: requestVariant
    
      PetDescriptionObject:
        allOf:
        - $ref: "#/definitions/CreatePet_Request"
        - type: object
          properties: 
            name: 
              type: string
            description:
              type: string
    
      PetCatalogEntry:
        allOf:
        - $ref: "#/definitions/CreatePet_Request"
        - type: object
          properties: 
            SKU: 
              type: string
            Breed:
              type: string
            Comments:
              type: string
    

    这些方法都不是请求的媒体类型。虽然请求可能接受多种媒体类型,但如果使用特定媒体类型意味着对请求正文的某些要求,则必须在操作或正文参数的描述属性中记录该要求。