如何在 OpenAPI (Swagger) 中定义枚举? [英] How to define an enum in OpenAPI (Swagger)?

查看:33
本文介绍了如何在 OpenAPI (Swagger) 中定义枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does anyone know how to define possible 'enum' values in an OpenAPI 2.0 definition so that they will be displayed in the Model tab of Swagger UI? Example here: https://petstore.swagger.io/#!/pet/addPet has an enum option for the status property. How to do define such an enum in OpenAPI 2.0?

推荐答案

枚举"在 OpenAPI 2.0 中像这样工作:

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

在 OpenAPI 3.0 中:

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
      }

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

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

要在本地测试它,您可以在 javascript 中声明一个变量(例如 spec),并将其传递给 SwaggerUi 对象.

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){
    ...

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

The url parameter will be ignored in this case.

最终,输出如下所示:

这篇关于如何在 OpenAPI (Swagger) 中定义枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆