In my Spring API I wanted to handle responses from operations like create, put and delete with Spring's annotation @ResponseStatus. Every endpoint works correctly but they always return empty response.
Why response from annotated endpoints is empty?
Controller:
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
@RestController
@RequestMapping(value = "/v1/portfolios")
public class PortfolioController {
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody Portfolio resource) {
repo.save(resource);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") String id) {
repo.removeById(id);
}
}
Why response from annotated endpoints is empty?
Because your methods return void
(means without body). Status code - it's not a body.
You can try this to return response with message explicity:
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> delete(@PathVariable("id") String id) {
repo.removeById(id);
return new ResponseEntity<>("Your message here", HttpStatus.OK);
}
Instead of ResponseEntity<String>
you can put ResponseEntity<YourCustomObject>
and then return new ResponseEntity<>(yourCustomObject instance, HttpStatus.OK);
It will be conver into JSON during response.
You also can make this:
@ResponseStatus(value = HttpStatus.OK, reason = "Some reason")
and in this case you will return something like this:
{
"timestamp": 1504007793776,
"status": 200,
"error": "OK",
"message": "Some reason",
"path": "/yourPath"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With