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

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

问题描述

有人知道如何在OpenAPI 2.0定义中定义可能的枚举"值,以便将其显示在Swagger UI的模型"选项卡中吗?此处的示例: https://petstore.swagger.io/#!/pet/addPetstatus属性具有一个枚举选项.如何在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?

推荐答案

枚举"的工作原理如下:

"enum" works just like this:

      {
        "in": "query",
        "name": "sample",
        "description": "a sample parameter with an enum value",
        "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.

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

Eventually, the output looks like this:

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

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