如何在OpenAPI(Swagger)中定义枚举?

问题描述 投票:45回答:4

有人知道如何在OpenAPI 2.0定义中定义可能的'枚举'值,以便它们将显示在Swagger UI的“模型”选项卡中吗?此处的示例:https://petstore.swagger.io/#!/pet/addPet具有status属性的枚举选项。如何在OpenAPI 2.0中定义这样的枚举?

swagger swagger-ui swagger-2.0 openapi
4个回答
63
投票

“枚举”的工作原理如下:

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

如您所见,有一个名为sample的字符串类型的查询参数,并且有一个枚举说明两个可能的值。在这种情况下,示例指出该参数是必需的,因此UI不会显示一个空值作为选项。

要获得最小的工作样本,请尝试以下方法:

{
  "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."
          }
        }
      }
    }
  }
}

要在本地进行测试,您可以在JavaScript中声明一个变量(例如spec),并将其传递到SwaggerUi对象。

  var spec = { ... };

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

在这种情况下,url参数将被忽略。

最终,输出看起来像这样:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9nYm5TSi5wbmcifQ==” alt =“在此处输入图像描述”>


14
投票

使用YAML语法更新此内容:

in: query
name: sample
description: a sample parameter with an enum value
type: string
enum:
    - 1
    - 2
required: true

-1
投票

这应该起作用:

{
    "name": "bookingType",
    "in": "path",
    "type": "array",
    "items": {
        "enum": [
            "packages", "accommodations"
        ]
    },
    "description": "lorem ipsum"
}

参考https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#itemsObject


-1
投票

这不是确切的答案,但在他们添加此功能之前,它可能对您有用。

像这样简单地声明属性

"MyObject":{
   "properties":{
      "MyEnum":{
         "type":"Value1 or Value2 or Value3"
      }
   }
}

您的ModelSchema将显示{},但是模型将显示MyEnum(Value1 or Value2 or Value3, optional)

© www.soinside.com 2019 - 2024. All rights reserved.