2

I have an API where I post a set of object to the server, differentiated by type, where each type has some different parameters. The commands are structured like so:

{
    "type": <command-name>,
    "args": { 
        <command-specific args>
    }
}

For example, these may be two possible commands:

{
    "type": "Flooblinate",
    "args": {
        "intensity": "High",
        "frequency": "Every blue moon"
    }
}

{
    "type": "Blagostrate",
    "args": {
        "temperature": 34.5,
        "darkMatter": true
    }
}

How can I specify this in Swagger? I can specify an enum for "type", but how do I say ""args" is one of these possible objects"?

I've checked out the docs but nothing stands out. The most promising one was allOf because it displayed nicely in the editor (pastebin, paste into the online editor):

definitions:
  Product:
    type: object
    allOf:
    - type: object
      title: Flooblinate
      properties:
        intensity:
          type: string
        frequency:
          type: string

    - type: object
      title: Blagostrate
      properties:
        temperature:
          type: number
        darkMatter:
          type: boolean

Which looks like this:

enter image description here

However, this isn't semantically what I need, and, not surprisingly, in the online viewer (that one's not set up for my test case, not sure how to link up a local file easily), they are presented as if all the fields appear at the same time, which is of course what allOf means:

enter image description here

What's the proper way to represent this with Swagger?

4

1 回答 1

1

根据 Ron 在google group上的输入,我想要的是使用该discriminator属性:

definitions:
  Product:
    type: object
    discriminator: type
    properties:
      type: string
    required: [type]
  Flooblinate:
    allOf:
    - $ref: '#/definitions/Product'
    - type: object
      properties:
        intensity:
          type: string
        frequency:
          type: string
  Blagostrate:
    allOf:
    - $ref: '#/definitions/Product'
    - type: object
      properties:
        temperature:
          type: number
        darkMatter:
          type: boolean

从语义上讲,这意味着我想要它的意思。我应该指定$ref: '#/definitions/Product'API 接受或返回任何一个Flooblinate或的位置Blagostrate。请注意,这需要对象上的一个字段(type此处称为)作为鉴别器。

我认为这可能是方法,但工具并没有显示出我的预期。然而:

那是因为这些工具还不是 100% 支持鉴别器 - 但是,这是描述您的用例的正确方法。一旦你在顶层模型中定义了鉴别器,任何'allOf'都将被认为是一个可行的选项,实际上你参考了顶层模型的使用。

于 2015-10-20T14:45:15.097 回答