提问者:小点点

@带空响应体的ApiResponse(Spring靴)


我正在寻找一种方法来告诉斯威格,某个API响应代码没有响应体。例如,一个get响应,可以返回一个200代码,将实际对象作为响应,或者如果与传递的ID关联的对象不存在,则返回一个404:

@ApiResponses(value = {
    @ApiResponse(responseCode = "200", description = "Object found"),
    @ApiResponse(responseCode = "404", description = "Invalid object ID", content = @Content)
})

这是我能想到的最接近的事情,但它并不完美,在404响应的描述下,我仍然得到了一个恼人的“媒体类型”。谢谢


共3个答案

匿名用户

这可能是更好(也更短)的方法:

@ApiResponse(
   responseCode = "404", 
   description = "Not found", 
   content = @Content(schema = @Schema(hidden = true))) 

匿名用户

如果未指定@apisresponse注释的内容属性,则控制器方法的返回类型将是您的响应内容。要防止出现这种情况,请明确定义内容

@ApiResponse(responseCode = "200", description = "OK",
             content = @Content(schema = @Schema(implementation = Void.class)))

或者只需返回ResponseEntity即可

匿名用户

您可以在v2中的方法之上使用以下内容

@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Success", response = YourObject.class),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message="Forbidden"),
        @ApiResponse(code = 404, message = "Not Found"),
        @ApiResponse(code = 500, message = "Failure")
})

对于V3,您可以尝试类似的方法,以防您的方法返回某些对象

@Operation(summary = "Add a new object", description = "", tags = { "yourObject" })
@ApiResponses(value = { 
        @ApiResponse(responseCode = "201", description = "Object created",content = @Content(schema = @Schema(implementation = YourObject.class))), 
        @ApiResponse(responseCode = "400", description = "Invalid input"), 
        @ApiResponse(responseCode = "409", description = "Object already exists") })    
        @PostMapping(value = "/your-url", consumes = {"application/json","application/xml" })
        public ResponseEntity<YourObject> addObject(
            ...
            return ...
        }

如果您的方法返回无效,请尝试此方法

@Operation(summary = "Update an existing object", description = "", tags = { "yourObject" })
@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "successful operation"),
        @ApiResponse(responseCode = "400", description = "Invalid ID supplied"),
        @ApiResponse(responseCode = "404", description = "Object not found"),
        @ApiResponse(responseCode = "405", description = "Validation exception") })  
        @PutMapping(value = "/your-url/{id}", consumes = { "application/json", "application/xml" })  
        public ResponseEntity<Void> addObject(
            ...
            return ...
        }