【问题标题】:How to add an example in @ApiResponse with Swagger?如何使用 Swagger 在 @ApiResponse 中添加示例?
【发布时间】:2023-01-19 13:13:06
【问题描述】:

我想在我的方法中添加一个带有 Swagger 的示例,我尝试了一些方法,但它们没有用。

我有我的接口,我在其中定义了方法:

@Api(value = "test API")
@RequestMapping("/api/v1/product")
public interface TestController {

    @ApiOperation(
            value = "Service that return a Product",
            notes = "This service returns a Product by the ID",
            nickname = "getProductById",
            response = ProductResponse.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "The request has succeeded.", response = ProductResponse.class),
            @ApiResponse(code = 500, message = "Internal server error.", response = ProductResponse.class) })
    @GetMapping(
            value = "/productById",
            produces = { "application/json" }
    )
    ResponseEntity<ProductResponse> getProductById(@RequestParam(value = "productId", required = true) String productId);

ProductResponse 类如下:

@Getter
@Setter
@AllArgsConstructor
public class ProductResponse {

    private Product product;
    private CustomException customException;

}

产品类别如下:

@Getter
@Setter
@AllArgsConstructor
public class Product {

    @JsonProperty("id")
    private String id;

    @JsonProperty("productName")
    private String productName;

    @JsonProperty("productDescription")
    private String productDescription;

    @JsonProperty("unitPrice")
    private Double unitPrice;

CustomException 类如下:

@Getter
public class CustomException {

    private final String message;
    private final String errorCode;
    private final String errorType;
    private final Exception exceptionDetail;
    
    public CustomException(String message, String errorCode, String errorType, Exception exceptionDetail) {
        this.message = message;
        this.errorCode = errorCode;
        this.errorType = errorType;
        this.exceptionDetail = exceptionDetail;
    }

当响应为 200 时,响应类似于:

{
  "product": {
    "id": "12345",
    "productName": "Product name",
    "productDescription": "This is a description",
    "unitPrice": 3.25
  },
  "customException": null
}

但是当响应是 500 时,响应是这样的:

{
  "product": "null,",
  "customException": {
    "message": "/ by zero",
    "errorCode": "500",
    "errorType": "Internal server error",
    "exceptionDetail": null,
    "cause": null,
    "stackTrace": [
      {
        "classLoaderName": "app",
        "moduleName": null,
        "moduleVersion": null,
        "methodName": "getProductById",
        "fileName": "TestControllerImpl.java",
        "lineNumber": 33,
        "className": "com.myproject.testmicroservice.controller.impl.TestControllerImpl",
        "nativeMethod": false
      }
    ]
  }
}

如何在@ApiResponse 注释中添加自定义示例?

【问题讨论】:

    标签: java spring swagger swagger-ui swagger-2.0


    【解决方案1】:

    您可能缺少 @Operation 注释,您在其中放置了 @ApiResponse

    例子:

      import io.swagger.v3.oas.annotations.responses.ApiResponse;
      import io.swagger.v3.oas.annotations.Operation;
    
      @Operation(responses = {
          @ApiResponse(responseCode = "200", content = @Content(examples = {
              @ExampleObject(name = "getUserAttribute",
                             summary = "Retrieves a User's attributes.",
                             description = "Retrieves a User's attributes.",
                             value = "[{"value": ["area1", "area2", "area3"], "key":"GENERAL_AREAS"}, {"value":"933933933", "key":"FONyE"}]")
          }, mediaType = MediaType.APPLICATION_JSON_VALUE))})
      public ResponseEntity<List<UserPreferenceDto>> getUserPreferenceByCode(
          @Pattern(regexp = "\w+") @PathVariable String userCode, @Parameter(hidden = true) Pageable pageable) {
    
         ...
      }
    

    【讨论】:

      【解决方案2】:

      晚上好,希望你过得好。在你描述的情况下,我会做这样的事情

      @ApiResponses(value = { 
        @ApiResponse(responseCode = "200", description = "Found the book", 
          content = { @Content(mediaType = "application/json", 
            schema = @Schema(implementation = Book.class)) }),
        @ApiResponse(responseCode = "400", description = "Invalid id supplied", 
          content = @Content),
      

      所描述的方法在 here 中进行了解释。我认为第 9 段。使用@Operation 和@ApiResponses 生成文档对您的案例特别感兴趣。我希望这会有所帮助,祝你晚安

      【讨论】:

        【解决方案3】:

        你可以试试this之类的东西。在您的控制器中,您已经有了 @ApiResponses 注释。您需要做的是将 @ApiModel 添加到您的 Product 类,然后添加

        @ApiModelProperty(notes = "Your comments", required = true, example = "example value")
        

        Product班级的成员,即ProductResponseCustomException。您需要验证的一件事是 @ApiModelProperty 是否可以设置在自定义对象上,如 ProductResponseCustomException。如果不是,您将需要设置@ApiModelProperty 1 级深。

        如文章中所示,示例会自动从模型属性填充到响应。

        PS:截至目前,我还没有设置 swagger 项目,所以只能在理论上帮助你。

        【讨论】:

          【解决方案4】:

          可能是这个迟到的答案,但万一有人需要它,您可以在 @Operation 中添加 requestBody 描述和内容类型

          @io.swagger.v3.oas.annotations.Operation(summary = "", description = "",
                  requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE)))
          

          【讨论】:

            猜你喜欢
            • 2020-06-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-01-20
            • 2020-06-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多