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

5uzkadbs  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(148)

我想用Quarkus和Swagger在请求中生成一个示例值。
Quarkus中是否有类似@ApiModelProperty的注解?或者在请求中是否有任何标记来设置示例?

谢谢

ryhaxcpt

ryhaxcpt1#

对于Quarkus,您需要使用Microprofile Openapi Annotations:
https://download.eclipse.org/microprofile/microprofile-open-api-1.0/microprofile-openapi-spec.html
具体而言:@ExampleObject哪个
说明了特定内容的示例。
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属性接受一个String:

/**
     * 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);
      }

}
mhd8tkvw

mhd8tkvw2#

您可以在字段上使用@Schema注解来定义其openapi示例。

import org.eclipse.microprofile.openapi.annotations.media.Schema;

public class Fruit {

    @Schema(example = "apple")
    public String name;

    @Schema(example = "the red fruit")
    public String description;
}

这将产生以下的 Swagger :

注解可以在org.eclipse.microprofile.openapi:microprofile-openapi-api:X.X依赖项中找到。

相关问题