Home > Enterprise >  Why Spring RestController POST method returns 200 instead of 204 when return type is void?
Why Spring RestController POST method returns 200 instead of 204 when return type is void?

Time:12-21

@PostMapping(path = "/test")
public void save(Map payload) {
    testService.save(payload);
}

Spring RestController returns 204 instead of 200 in above scenario. Return type is void & there is no content is response body. It is an established practice to return 204 HTTP code when there is no response body & the processing is successful. I want to know why Spring doesn't do that by default? Is there any particular reason?

I already know how to change the default status code, so that is not a question.

CodePudding user response:

I don't have a direct answer for "why status 204 isn't returned by default" but it makes sense to me that it would return 200 (ok) by default because the status code 204 definition states that

There is no content to send for this request, but the headers may be useful

Yet in the case of returning nothing at all, there is no response entity and therefore are also no useful headers.

With spring boot (and Java in general) being so explicit, we need to also be explicit when we are defining the behaviors we want.

A slightly more explicit version of your endpoint method might be something like the following...

@PostMapping("test")
public ResponseEntity<?> save(@RequestBody Map<?,?> payload) {
    if(payload.isEmpty())
        return ResponseEntity.noContent().build();
    else
        return ResponseEntity.ok().body(testService.save(payload));
}

CodePudding user response:

try this code

@PostMapping(path = "/saveAccident")
    ResponseEntity<AccidentDTO> saveAccident(@RequestBody AccidentDTO accidentDTO) {
        return new ResponseEntity<AccidentDTO>(accidentService.saveAccident(accidentDTO), HttpStatus.OK);
    }
  • Related