Swagger array of integer return type

Gargoyle picture Gargoyle · Jan 19, 2017 · Viewed 13.7k times · Source

I'm just getting started with using the swagger-editor to define my RESTful API and I'm confused on the responses. Many of my methods simply return an array of integers, and I'm not understanding how to specify that in the YAML.

Answer

Helen picture Helen · Jan 24, 2017

The OpenAPI (fka Swagger) Specification 2.0 uses a subset of JSON Schema v4. You can refer to the JSON Schema docs or this great guide to learn how to describe different data types using JSON Schema. But keep in mind that some features of JSON Schema are not supported or work differently in OpenAPI/Swagger. The Specification mentions what exactly is supported.

Back to your question, an array of integers is defined as:

type: array
items:
  type: integer

Or in the context of a response:

paths:
  /something:
    get:
      responses:
        200:
          description: OK
          schema:
            type: array
            items:
              type: integer

If arrays of integers are used in multiple places in your spec, you can define the array in the global definitions section and then use $ref to refer to it:

paths:
  /something:
    get:
      responses:
        200:
          description: OK
          schema:
            $ref: "#/definitions/ArrayOfInt"

definitions:
  ArrayOfInt:
    type: array
    items:
      type: integer

You can also specify example values for the array. Swagger UI will display this example, and some mocking tools will use it when generating sample responses.

definitions:
  ArrayOfInt:
    type: array
    items:
      type: integer
    example: [1, 2, 3, 4]
    # Make sure to put the multi-item "example"
    # on the same level as the "type" and "items" keywords