Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define an array of different examples in a Swagger spec?

I'm trying to document an API with a static swagger file that can return some JSON that contains an array that looks something like this:

[
  {
    "type": "type A",
    "field A": "this field is specific to type A"
  },
  {
    "type": "type B",
    "field B": "this field is specific to type B"
  }
]

I've tried a few different ways of defining my spec using either polymorphism or explicitly defining multiple examples. The examples have always either ended up looking like:

[
  {
    "type": "type A",
    "field A": "this field is specific to type A",
    "field B": "this field is specific to type B"
  }
]

or just:

[
  {
    "type": "type A",
    "field A": "this field is specific to type A"
  }
]

Is there a way to define an example in my swagger spec so that the example payload shown by swagger-ui will contain an array containing an example of Type A and an example of Type B like the first JSON I wrote?

like image 474
Joseph Downing Avatar asked Jun 19 '15 16:06

Joseph Downing


People also ask

How do you declare an array of strings in Swagger?

YAML. Firstly, we start by specifying the array of strings in Swagger using YAML notation. In the schema section, we include type: array with items String.

How do you declare an empty array in Swagger?

You can specify an empty array [] as an example for your array schema. This will override the default examples values generated by Swagger UI. Save this answer.


2 Answers

Actually, you can. In the responses object, put an examples object with an array as the value of the mime type. like so:

    400:
      description: Bad Request
      examples:
        application/json:
          [
            {
              code:10000,
              message:"Missing Input Parameters",
              fieldA: "AAAAA"
            },{
              code:42,
              message:"Ask the question",
              fieldB: "BBBBBB"
            }
          ]
    default:
      description: Unexpected error
      schema:
        $ref: '#/definitions/Error'
like image 55
Kriil Avatar answered Oct 13 '22 00:10

Kriil


You can't.

You can only define one example per mime-type per response :

{
  "description": "A response",
  "schema": {
    "type": "string"
    }
  },
  "examples": {
    "application/json": {
      "name": "Dog"
    },
    "application/xml": {
      "name": "Cat"
    }
  }
}

If you want add complete scenario, I suggest you to write (or generate) a full scenario example in an HTML page and link it with an externalDocs. You can define externalDocs in root, operations, tags and schemas.

like image 36
Nelson G. Avatar answered Oct 13 '22 00:10

Nelson G.