如何使用 Quarkus 在 Swagger 中生成请求示例

How to generate a request example in Swagger with Quarkus

我想使用 Quarkus 和 Swagger 在请求中生成示例值。

Quarkus中有@ApiModelProperty之类的注解吗?或者请求中是否有设置示例的标签?

谢谢

对于 Quarkus,您需要使用 Microprofile Openapi 注释:

https://download.eclipse.org/microprofile/microprofile-open-api-1.0/microprofile-openapi-spec.html

具体来说:@ExampleObject其中

Illustrates an example of a particular content.

https://github.com/eclipse/microprofile-open-api/blob/master/api/src/main/java/org/eclipse/microprofile/openapi/annotations/media/ExampleObject.java

示例:

 public interface ExamplePayloads {
      String NEW_PLAYER = "{\"age\":12, \"username\":\"username\"}";
      String SAVED_PLAYER = "{\"id\":1234, \"age\":12, \"username\":\"username\"}";
      
}

ExampleObjectvalue 属性接受一个字符串:

   /**
     * A string representation of the example.
     * <p>
     * This is mutually exclusive with the externalValue property, and ignored if the externalValue property is
     * specified.
     * </p>
     * If the media type associated with the example allows parsing into an object, it may be converted from a string.
     * 
     * @return the value of the example
     **/
    String value() default "";
    
  

import static yourpackage.ExamplePayloads.*;

@Path("/players")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public class PlayersResource {


      @POST
      @Operation(summary = "save new player", description = "Creates new player with given age and username.")
      @RequestBody(
        required = true,
        content = @Content(
          schema = @Schema(implementation = Player.class, required = true, requiredProperties = {"username", "age"}),
          examples = @ExampleObject(
            name = "new player",
            description = "saves new player with parameters username and age",
            value = NEW_PLAYER
          )
        ))
      @APIResponses(
        value = {
        @APIResponse(
          name = "success",
          responseCode = "200",
          content = @Content(
            schema = @Schema(implementation = Player.class, required = true, requiredProperties = {"id", "username", "age"}),
            examples = @ExampleObject(
              name = "saved player",
              description = "new player with id assigned.",
              value = SAVED_PLAYER
            )
          ))
        ,
        @APIResponse(
          name = "bad request, no username",
          responseCode = "400",
          description = "missing username or age"
        ),
        }
    )
      public Player savePlayer(Player player) {
       
        return playersService.savePlayer(player);
      }


}