Return HTTP 204 on null with spring @RestController

You can use the @ResponseStatus annotation. This way you can have a void method and you don’t have to build a ResponseEntity.

@DeleteMapping(value = HERO_MAPPING)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long heroId) {
    heroService.delete(heroId);
}

BTW returning 200 when the object exists and 204 otherwise it’s a bit unusual regarding API REST design. It’s common to return a 404 (not found) when the requested object is not found. And this can be achieved using a ControllerAdvice.

In Spring REST it’s better to handle Exceptions with a Exception handler instead of putting logic to decide the response status, etc. This is an example using the @ControllerAdvice annotation: http://www.jcombat.com/spring/exception-handling-in-spring-restful-web-service

Leave a Comment