Mastodon

Returning an empty Responseentity in Spring MVC

Spring MVC is a great way of creating REST interfaces. Many convenience classes and methods are provided, such as the Response Entity object for returning data:

@GetMapping("/")
public ResponseEntity<List<MyEntity>> getAll() {
 
	return new ResponseEntity<>(myService.getAll(), HttpStatus.CREATED);
}

However, there are endpoints that are not supposed to return anything, like deleting an entity. To keep the controller consistend, I prefer returning a ResponseEntity in every method. For methods that don’t return anything, the Void-object has to be used as type for the ResponseEntity:

@DeleteMapping(value = "/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
 
	try {
		myService.delete(id);
		return new ResponseEntity<>(HttpStatus.NO_CONTENT);
	} catch (Exception e) {
		return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
	}
}