2

我正在尝试将 swagger 文档添加到我的项目中。我需要为 Sample.class 的@RequestBody 中的@Parameter 添加多个示例,以下代码是文档中提到的编写方式。

@PostMapping("/")
    public Sample createSample(@Parameter(description="Sample description", examples = {
            @ExampleObject(name="foo", description = "na",summary = "na",value = "{\n" +
                    "  \"id\": 10,\n" +
                    "  \"name\": \"ashith\",\n" +
                    "  \"description\": \"none\"\n" +
                    "}"),
            @ExampleObject(name="bar",description = "na",summary = "na",value = "{\n" +
                    "  \"id\": 20,\n" +
                    "  \"name\": \"Akshatha\",\n" +
                    "  \"description\": \"ok\"\n" +
                    "}")
    }
    )
                                   @RequestBody Sample sample) {


正在生成的 yaml 输出如下:

openapi: 3.0.1
info:
  title: OpenAPI definition
  version: v0
servers:
  - url: 'http://localhost:8080/'
    description: Generated server url
paths:
  /api/another/:
    post:
      tags:
        - another-controller
      operationId: createSample
      requestBody:
        description: Sample description
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Sample'
        required: true
      responses:
        '200':
          description: default response
          content:
            '*/*':
              schema:
                $ref: '#/components/schemas/Sample'
        '400':
          description: default response
          content:
            '*/*':
              schema:
                type: string
        '404':
          description: default response
          content:
            '*/*':
              schema:
                type: string

这似乎缺少应该按照代码添加的示例

4

1 回答 1

2

@Parameteruses ParameterIn,它指定它是由 openapi 提供的标题、查询还是路径(请参阅下文)。

package io.swagger.v3.oas.annotations.enums;

public enum ParameterIn {
    DEFAULT(""),
    HEADER("header"),
    QUERY("query"),
    PATH("path"),
    COOKIE("cookie");

    private String value;

    private ParameterIn(String value) {
        this.value = value;
    }

    public String toString() {
        return String.valueOf(this.value);
    }
}

相反,您应该使用RequestBodyopenapi 库,如下所示

@io.swagger.v3.oas.annotations.parameters.RequestBody(content = {
        @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
            @ExampleObject(value = "{\"key1\": \"example1\", \"key2\":\"example1\", \"key3\":\"example1\"}"),
            @ExampleObject(value = "{\"key1\": \"example2\", \"key2\":\"example2\", \"key3\":\"example2\"}")
            })
    })

您可以在方法或参数级别添加它。

于 2020-06-18T06:42:35.820 回答