How to define an enum in OpenAPI (Swagger)?

“enum” works like this in OpenAPI 2.0:

      {
        "in": "query",
        "name": "sample",
        "description": "a sample parameter with an enum value",
        "type": "string",
        "enum": [ "1", "2"],
        "required": true
      }

and in OpenAPI 3.0:

      {
        "in": "query",
        "name": "sample",
        "description": "a sample parameter with an enum value",
        "schema": {
          "type": "string",
          "enum": [ "1", "2"]
        },
        "required": true
      }

As you can see, there’s a query parameter called sample of type string, and has an enum stating two possible values. In this case, the sample states the parameter is required, so the UI will not show an empty value as an option.

For a minimal working sample, try this:

{
  "swagger": "2.0",
  "info": {
    "title": "title",
    "description": "descriptor",
    "version": "0.1"
  },
  "paths": {
    "/sample": {
      "post": {
        "description": "sample",
        "parameters": [
          {
            "in": "query",
            "name": "sample",
            "description": "a sample parameter with an enum value",
            "type": "string",
            "enum": [
              "1",
              "2"
            ],
            "required": true
          }
        ],
        "responses": {
          "200": {
            "description": "Successful request."
          }
        }
      }
    }
  }
}

To test it locally, you can declare a variable (for example spec) in your javascript, and pass it into the SwaggerUi object.

  var spec = { ... };

  window.swaggerUi = new SwaggerUi({
    url: url,
    spec: spec,
    dom_id: "swagger-ui-container",
    supportedSubmitMethods: ['get', 'post', 'put', 'delete'],
    onComplete: function(swaggerApi, swaggerUi){
    ...

The url parameter will be ignored in this case.

Eventually, the output looks like this:

enter image description here

Leave a Comment