1

我有一项服务,它可以根据Content-Type标头具有两种不同的主体参数。

例如路径/Pet

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

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

关于如何在 OpenAPI (Swagger) 中体现这一点的任何建议?

4

2 回答 2

4

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'
于 2017-12-14T20:51:21.750 回答
1

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

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

创建两个单独的路径项

例如:

/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 规范中进行了描述。

例子:

/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操作或正文参数的属性中记录这些要求。

于 2016-12-17T20:23:10.967 回答