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

时间:2016-02-15 10:32:11

标签: swagger openapi

我的服务可以根据Content-Type标题有两种不同的身体参数。

E.g。路径/Pet

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

  • 如果使用Content-Type: application/somecustom.function+json,则POST应该使用一些不同的body参数来调用函数并返回不同的响应。

有关如何在OpenAPI(Swagger)中表现出来的任何建议吗?

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:1)

不,在相同的路径项中,无法为同一操作定义两个不同的主体参数。路径项名称是唯一的,因为它是属性名称(因此"键和#34;在JSON键值映射中),并且Swagger规范允许在给定操作中使用at most one body parameter

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

创建两个单独的路径项

例如:

/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-OpenAPI 2.0规范here中描述。

示例:

/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

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

相关问题