Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @ResponseStatus returns empty response

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

}
like image 216
Michael Dz Avatar asked Aug 29 '17 10:08

Michael Dz


1 Answers

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"
}
like image 77
Optio Avatar answered Oct 29 '22 13:10

Optio