首页 > 解决方案 > 如何在 OpenAPI 规范中将枚举定义为查询参数

问题描述

我想在 OpenAPI 规范中的函数的查询字符串参数中定义一个枚举值。

这是我如何在 OpenAPI 规范 (yaml) 中指定参数的示例:

openapi: 3.0.0
info:
  description: Vends sodas
  version: 1.0.0
  title: VendingMachineService
paths:
  /soda/{bill}:
    get:
      summary: Provides a soda for a provided amount of money
      description: Provides a soda for a provided amount of money
      operationId: getSoda
      parameters:
      - name: bill
        in: path
        description: Money (e.g. one, two, five)
        required: true
        schema:
          $ref: "#/components/schemas/Bill"
      responses:
        "200":
          description: Success
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Result"
        "404":
          description: Templates for Source not found
servers:
- url: http://localhost:8080/
components:
  schemas:
    Bill:
      type: string
      enum:
      - one
      - two
      - five
    Result:
      type: string

OpenAPI 规范的关键部分是我在底部的模式对象中定义枚举,键入字符串,并在函数的参数部分中引用它,还将其定义为路径 /{bill} 的一部分

然后我使用 openapi-generator 生成 spring 服务器:

openapi-generator generate -i ~/vending-machine.yaml -g spring -o ~/output

然后我启动服务器(将项目导入 Intellij 并在 spring-boot 配置中运行)并转到 localhost:8080/ 打开 Swagger UI。我尝试使用 api 并收到以下错误:

{ "timestamp": "2019-03-29T15:43:14.737Z", "status": 400,
"error": "Bad Request", "message": "无法转换类型的值'java.lang.String ' 到所需类型 'org.openapitools.model.Bill';嵌套异常是 org.springframework.core.convert.ConversionFailedException:无法从类型 [java.lang.String] 转换为类型 [@javax.validation.constraints.NotNull @io.swagger.annotations.ApiParam @javax.validation.Valid @org.springframework.web.bind.annotation.RequestParam org.openapitools.model.Bill] 值'null';嵌套异常是 java.lang.IllegalArgumentException: 否枚举常量 org.openapitools.model.Bill.null", "path": "/soda/%7Bbill%7D" }

(预计 501 未实施)

在 OpenAPI 规范中定义查询参数和枚举以使用枚举值的正确方法是什么?

标签: springswaggeropenapi

解决方案


推荐阅读