如何在Swagger文档中展示多个示例?

huangapple go评论81阅读模式
英文:

How to show multiple example in swagger documentation?

问题

在我的REST API PATCH操作中,我正在使用v3的swagger-annotation:2.0.6

我尝试为我的patch操作PATCH /users/id添加更多的示例作为swagger模式。

请求体:

{
  "operationList": [
    {
      "op": "replace",
      "path": "/username",
      "value": "john1991"
    }
  ]
}

目前我有以下用于请求模型的类。

public class UserPatchOp extends PatchOperation {
    @Override
    @Schema(description = "some description", example = "replace", required = true)
    public PatchOperator getOp() {
        return super.getOp();
    }

    @Override
    @Schema(description = "some description", example = "/username", required = true)
    public String getPath() {
        return super.getPath();
    }

    @Override
    @Schema(description = "some description", example = "john1991", required = true)
    public Object getValue() {
        return super.getValue();
    }
}

在PatchOperation.java中:

public class PatchOperation {

    /**
     * {@link PatchOperator} operation to be performed
     */
    @Schema(description = "Operation to be performed", required = true)
    @JsonProperty
    @NotNull
    private PatchOperator op;

    @Schema(description = "Path to target where operation will be performed", required = true)
    @JsonProperty
    @Pattern(regexp = "/([/A-Za-z0-9~])*-*", message = "Invalid path. Please follow regex pattern")
    private String path;

    @Schema(description = "Value used by operation")
    @JsonProperty
    private Object value;

    public PatchOperation() {
    }
}

在swagger文档中,我在UserPatchOp.java中向终端用户展示了如何替换用户名。在swagger上,请求正文显示为以下示例。

如何在Swagger文档中展示多个示例?

除了通过此patch操作更新用户名之外,终端用户还可以更新描述,然后路径将为/description

终端用户还可以更新所属用户组为/usergroups
因此,一般情况下,我希望在swagger模式中添加更多示例。但我不能做到这一点,因为一次只能显示一个示例。

我想在swagger页面上向客户展示以下多个操作。

{
  "operationList": [
    {
      "op": "replace",
      "path": "/username",
      "value": "john1991"
    },
    {
      "op": "remove",
      "path": "/description"
    },
    {
      "op": "add",
      "path": "/memberships",
      "value": ["1224","8907"]
    }
  ]
}

入口方法是

@PATCH
@Path("users/{id}")
@Consumes({MediaType.APPLICATION_JSON, APPLICATION_JSON_PATCH_JSON})
@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = MessageConstants.OK, content = @Content(schema = @Schema(implementation = UserInfo.class))),
        @ApiResponse(responseCode = "500", description = MessageConstants.SERVER_ERROR, content = @Content(schema = @Schema(implementation = RestError.class))),
        @ApiResponse(responseCode = "400", description = MessageConstants.BAD_REQUEST, content = @Content(schema = @Schema(implementation = RestError.class))),
        @ApiResponse(responseCode = "401", description = MessageConstants.UNAUTHORIZED, content = @Content(schema = @Schema(implementation = RestError.class))),
        @ApiResponse(responseCode = "404", description = MessageConstants.NOT_FOUND, content = @Content(schema = @Schema(implementation = RestError.class)))})
public Response updatePartialUser(
        @Parameter(description = "User Id", required = true) @PathParam("id") String id,
        @Parameter(description = "User Update Info", required = true) @Valid PatchOperations<UserPatchOperation> operationList) {

有没有办法可以为getOP、getPath和getValue方法添加多个示例?谢谢。

英文:

In my REST API PATCH operation, I am using v3 swagger-annotation:2.0.6

I was trying to add more examples as swagger schema for my patch operation PATCH /users/id.

Request Body:

{
  &quot;operationList&quot;: [
    {
      &quot;op&quot;: &quot;replace&quot;,
      &quot;path&quot;: &quot;/username&quot;,
      &quot;value&quot;: &quot;john1991&quot;
    }
  ]
}

Currently I have following class for request model.

public class UserPatchOp extends PatchOperation {
    @Override
    @Schema(description = &quot;some description&quot;, example = &quot;replace&quot;, required = true)
    public PatchOperator getOp() {
        return super.getOp();
    }

    @Override
    @Schema(description = &quot;some description&quot;, example = &quot;/username&quot;, required = true)
    public String getPath() {
        return super.getPath();
    }

    @Override
    @Schema(description = &quot;some description&quot;, , example = &quot;john1991&quot;, required = true)
    public Object getValue() {
        return super.getValue();
    }
}

In PatchOperation.java

public class PatchOperation {

    /**
     * {@link PatchOperator} operation to be performed
     */
    @Schema(description = &quot;Operation to be performed&quot;, required = true)
    @JsonProperty
    @NotNull
    private PatchOperator op;

    @Schema(description = &quot;Path to target where operation will be performed&quot;, required = true)
    @JsonProperty
    @Pattern(regexp = &quot;/([/A-Za-z0-9~])*-*&quot;, message = &quot;Invalid path. Please follow regex pattern&quot;)
    private String path;

    @Schema(description = &quot;Value used by operation&quot;)
    @JsonProperty
    private Object value;

    public PatchOperation() {
    }
}

In the swagger document, in UserPatchOp.java I have shown to the end-user that how to replace username.
On swagger, the request bogy comes with this example.

如何在Swagger文档中展示多个示例?

other than username through this patch operation, end-user can update description then path would be /description.

End-user can also update the usergroup from which it belongs to '/usergroups'
So in general, same way I want to add more example to swagger schema.
But I am not able to do it. Because at one time I can show one example only.

I want to show following multiple operations to the client on swagger page.

{
  &quot;operationList&quot;: [
    {
      &quot;op&quot;: &quot;replace&quot;,
      &quot;path&quot;: &quot;/username&quot;,
      &quot;value&quot;: &quot;john1991&quot;
    },
    {
      &quot;op&quot;: &quot;remove&quot;,
      &quot;path&quot;: &quot;/description&quot;
    },
    {
      &quot;op&quot;: &quot;add&quot;,
      &quot;path&quot;: &quot;/memberships&quot;
      &quot;value&quot;:[&quot;1224&quot;,&quot;8907&quot;]
    }
  ]
}

And entry point method is

@PATCH

@Path(&quot;users/{id}&quot;)
@Consumes({MediaType.APPLICATION_JSON, APPLICATION_JSON_PATCH_JSON})
@ApiResponses(value = {
        @ApiResponse(responseCode = &quot;200&quot;, description = MessageConstants.OK, content = @Content(schema = @Schema(implementation = UserInfo.class))),
        @ApiResponse(responseCode = &quot;500&quot;, description = MessageConstants.SERVER_ERROR, content = @Content(schema = @Schema(implementation = RestError.class))),
        @ApiResponse(responseCode = &quot;400&quot;, description = MessageConstants.BAD_REQUEST, content = @Content(schema = @Schema(implementation = RestError.class))),
        @ApiResponse(responseCode = &quot;401&quot;, description = MessageConstants.UNAUTHORIZED, content = @Content(schema = @Schema(implementation = RestError.class))),
        @ApiResponse(responseCode = &quot;404&quot;, description = MessageConstants.NOT_FOUND, content = @Content(schema = @Schema(implementation = RestError.class)))})
public Response updatePartialUser(
        @Parameter(description = &quot;User Id&quot;, required = true) @PathParam(&quot;id&quot;) String id,
        @Parameter(description = &quot;User Update Info&quot;, required = true) @Valid PatchOperations&lt;UserPatchOperation&gt; operationList) {

Is there any way, I can add multiple examples for getOP, getPath and getValue method? Thank you.

答案1

得分: 2

可以创建多个响应示例,其中一个方法可以返回多个响应代码,但每个响应代码只能有一个示例。

@Operation(description = "获取应用程序状态",
           responses = {
                   @ApiResponse(responseCode = "200",
                                description = "一切正常。",
                                content = @Content(mediaType = "application/json",
                                                   examples = @ExampleObject(value = "{\n" +
                                                                                     "  \"success\" : true,\n" +
                                                                                     "  \"message\" : \"OK\"\n" +
                                                                                     "}"))),
                   @ApiResponse(responseCode = "500",
                                description = "应用程序工作不正常。",
                                content = @Content(mediaType = "application/json",
                                                   examples = @ExampleObject(value = "{\n" +
                                                                                     "  \"success\" : false,\n" +
                                                                                     "  \"message\" : \"应用程序工作不正常\"\n" +
                                                                                     "}")))
           })
@GetMapping("haproxy")
ResponseEntity<BaseResponse> getHaProxy();

不确定这是否是您想要的,但我没有看到其他方法。

请记住,Swagger文档应该以一种使他人能够连接到您的API并执行一些操作的方式进行编写。您不需要在那里提供过多的响应。这就是OPTIONS REST方法的作用。OPTIONS方法基本上是一个不需要任何参数的GET方法,在响应中将返回有关特定方法的完整信息以及请求/响应将是什么。在这里,您可以更好地解释这一点:https://stackoverflow.com/questions/6660019/restful-api-methods-head-options

顺便说一下,您应该更新您的依赖项,swagger-annotations 现在已经是 2.1.4 版本了,而 2.0.6 是两年前的版本。

编辑 2020-09-30 关于请求主体:

可以像这样添加多个请求示例:

@Operation(description = "创建用户",
           requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "请求示例",
                                                                               content = @Content(examples = {
                                                                                       @ExampleObject(name = "进行奇怪的操作", value = "http://localhost:7080"),
                                                                                       @ExampleObject(name = "进行最奇怪的操作", value = "{\n\"test\":\"12\"\n}"),
                                                                               })),
           responses = {
                   @ApiResponse(responseCode = "200",
                                description = "一切正常。",
                                content = @Content(mediaType = "application/json",
                                                   schema = @Schema(implementation = UserResponse.class))),
                   @ApiResponse(responseCode = "404",
                                description = "未找到",
                                content = @Content(mediaType = "application/json",
                                                   examples = @ExampleObject(value = "{\"success\":false,\"message\":\"该商店或API版本尚不可访问\",\"httpStatus\":\"NOT_FOUND\"}"))),
                   @ApiResponse(responseCode = "500",
                                description = "出现问题",
                                content = @Content(mediaType = "application/json",
                                                   schema = @Schema(implementation = SomeBasicResponse.class)))
           })
@Parameters({
                @Parameter(in = ParameterIn.HEADER, name = "url",
                           content = @Content(schema = @Schema(type = "string", defaultValue = "localhost:7080")))
        })
@PostMapping
ResponseEntity<UserResponse> createUser(@RequestHeader(name = "login", required = false) String login,
                                        @RequestHeader(name = "password") String password,
                                        @RequestBody UserRequest request);

希望这就是您所寻找的。

英文:

It is possible to create multiple examples of responses which one method can return but it is possible to do only one example for one response code.

@Operation(description = &quot;Retrieves status of application&quot;,
responses = {
@ApiResponse(responseCode = &quot;200&quot;,
description = &quot;Everything works fine.&quot;,
content = @Content(mediaType = &quot;application/json&quot;,
examples = @ExampleObject(value = &quot;{\n&quot; +
&quot;  \&quot;success\&quot; : true,\n&quot; +
&quot;  \&quot;message\&quot; : \&quot;OK\&quot;\n&quot; +
&quot;}&quot;))),
@ApiResponse(responseCode = &quot;500&quot;,
description = &quot;Application not working properly&quot;,
content = @Content(mediaType = &quot;application/json&quot;,
examples = @ExampleObject(value = &quot;{\n&quot; +
&quot;  \&quot;success\&quot; : false,\n&quot; +
&quot;  \&quot;message\&quot; : \&quot;Application not working properly\&quot;\n&quot; +
&quot;}&quot;)))
})
@GetMapping(&quot;haproxy&quot;)
ResponseEntity&lt;BaseResponse&gt; getHaProxy();

I'm not sure if it's what you want but I don't see other way around.

Keep in mind that swagger documentation should be done in a way that someone will be able connect to your api and do some operations. You don't need to provide too much responses there. That's for OPTIONS rest method is. OPTIONS method is basically a GET which don't need any parameters and in response will return complete informations about what certain method can do and what the request/response will be. Here you have better explanation of that: https://stackoverflow.com/questions/6660019/restful-api-methods-head-options

Btw. you should update your dependencies, swagger-annotations is on 2.1.4 now, 2.0.6 is from 2 years ago

<b>EDIT 2020-09-30 About request's body:</b>

It is possible to add multiple requests examples like that:

@Operation(description = &quot;Creates a User&quot;,
requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = &quot;Request examples&quot;,
content = @Content(examples = {
@ExampleObject(name = &quot;doing weird stuff&quot;, value = &quot;http://localhost:7080&quot;),
@ExampleObject(name = &quot;doing weirdest stuff&quot;, value = &quot;{\n\&quot;test\&quot;:\&quot;12\&quot;\n}&quot;),
})),
responses = {
@ApiResponse(responseCode = &quot;200&quot;,
description = &quot;Everything works fine.&quot;,
content = @Content(mediaType = &quot;application/json&quot;,
schema = @Schema(implementation = UserResponse.class))),
@ApiResponse(responseCode = &quot;404&quot;,
description = &quot;Not found&quot;,
content = @Content(mediaType = &quot;application/json&quot;,
examples = @ExampleObject(value = &quot;{\&quot;success\&quot;:false,\&quot;message\&quot;:\&quot;That shop or API version is not accessible yet\&quot;,\&quot;httpStatus\&quot;:\&quot;NOT_FOUND\&quot;}&quot;))),
@ApiResponse(responseCode = &quot;500&quot;,
description = &quot;Something went wrong&quot;,
content = @Content(mediaType = &quot;application/json&quot;,
schema = @Schema(implementation = SomeBasicResponse.class)))
})
@Parameters({
@Parameter(in = ParameterIn.HEADER, name = &quot;url&quot;,
content = @Content(schema = @Schema(type = &quot;string&quot;, defaultValue = &quot;localhost:7080&quot;)))
})
@PostMapping
ResponseEntity&lt;UserResponse&gt; createUser(@RequestHeader(name = &quot;login&quot;, required = false) String login,
@RequestHeader(name = &quot;password&quot;) String password,
@RequestBody UserRequest request);

如何在Swagger文档中展示多个示例?

如何在Swagger文档中展示多个示例?

I hope that's what you are looking for.

答案2

得分: 0

我已在入口点处使用模式添加了示例

    @Parameter(description = "更新用户", required = true, schema = @Schema (example = "{\n  " +
                        "\"operationList\": [\n    " +
                        "{\n      \"op\": \"replace\",\n      \"path\": \"/username\",\n      \"value\": \"john1991\"\n    },\n    " +
                        "{\n      \"op\": \"replace\",\n      \"path\": \"/description\",\n      \"value\": \"NewDescription\"\n    },\n    " +
                        "{\n      \"op\": \"add\",\n      \"path\": \"/memberships\",\n      " +
                        "\"value\":[\"1234\",\"6789\"]\n    " +
                        "{\n      \"op\": \"remove\",\n      \"path\": \"/privileges\",\n      \"value\":[\"148\",\"155\"]\n    " +
                        "}\n  ]\n}") @Valid PatchOperations<UserPatchOperation> operationList) throws RestException
英文:

I have added example at entry point with help of schema

@Parameter(description = &quot;Update User&quot;, required = true, schema = @Schema (example = &quot;{\n  &quot;
+ &quot;\&quot;operationList\&quot;: [\n    &quot;
+ &quot;{\n      \&quot;op\&quot;: \&quot;replace\&quot;,\n      \&quot;path\&quot;: \&quot;/username\&quot;,\n      \&quot;value\&quot;: \&quot;john1991\&quot;\n    },\n    &quot;
+ &quot;{\n      \&quot;op\&quot;: \&quot;replace\&quot;,\n      \&quot;path\&quot;: \&quot;/description\&quot;,\n      \&quot;value\&quot;: \&quot;NewDescription\&quot;\n    },\n    &quot;
+ &quot;{\n      \&quot;op\&quot;: \&quot;add\&quot;,\n      \&quot;path\&quot;: \&quot;/memberships\&quot;,\n      &quot;
+ &quot;\&quot;value\&quot;:[\&quot;1234\&quot;,\&quot;6789\&quot;]\n    &quot;
+ &quot;{\n      \&quot;op\&quot;: \&quot;remove\&quot;,\n      \&quot;path\&quot;: \&quot;/privileges\&quot;,\n      \&quot;value\&quot;:[\&quot;148\&quot;,\&quot;155\&quot;]\n    &quot;
+ &quot;}\n  ]\n}&quot;)) @Valid PatchOperations&lt;UserPatchOperation&gt; operationList) throws RestException

huangapple
  • 本文由 发表于 2020年9月11日 03:41:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63836654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定