Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ApiResponse with empty response body (Spring Boot)

I'm looking for a way to tell swagger that a certain API response code doesn't have a response body. A get response, for example, that can either return a 200 code with the actual object as a response or a 404 if the object associated with the passed ID doesn't exist:

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

This is the closest thing I could figure out but it's not perfect, I still get an annoying "Media type" under the description of the 404 response. Thanks!

like image 636
valmarv Avatar asked Feb 20 '20 11:02

valmarv


People also ask

What is @responsebody in Spring Boot?

@ResponseBody is a Spring annotation which binds a method return value to the web response body. It is not interpreted as a view name. It uses HTTP Message converters to convert the return value to HTTP response body, based on the content-type in the request HTTP header.

How do I get JSON from Spring Boot response body?

Spring @ResponseBody example The following example creates a Spring Boot web application which returns JSON data to the client. The home page is handled with the MVC mechanism; FreeMarker is used to create the template for the home page. The home page contains a button which sends a request to get JSON data.

What does the @requestbody annotation do in spring?

Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object. First, let's have a look at a Spring controller method: Spring automatically deserializes the JSON into a Java type, assuming an appropriate one is specified.

How to understand the REST API with Spring Boot?

This is the basic example to understand the REST API with Spring Boot using Http Get and Post method. In the above example : I am using DAO and Model classes to add the student and retrieve the students through web services.


2 Answers

This is probably the better (and shorter) way:

@ApiResponse(
   responseCode = "404", 
   description = "Not found", 
   content = @Content(schema = @Schema(hidden = true))) 
like image 127
skeeks Avatar answered Oct 04 '22 07:10

skeeks


If you are not specifying the content attribute of @ApiResponse annotation the return type of the controller method will be your response content. To prevent this define content explicitly:

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

Or you can simply return ResponseEntity<Void>.

like image 25
Vladas Maier Avatar answered Oct 04 '22 06:10

Vladas Maier