Why need to use @ResponseEntity, first let's see what problem we might have when we don't use it.
@RestController public class ProductsRestController { @Autowired private ProductRepository productRepository; @GetMapping("/products") public List<Product> getProducts() { List<Product> products = new ArrayList<>(); productRepository.findAll().forEach(p -> products.add(p)); return products; } }
If the products is not exist. When it returns
Response: {status: 200, body: {}}
which is a misleading http status code.
@GetMapping("/products") public ResponseEntity getProductsByRequestParam(@RequestParam("name") String name) { List<Product> products = productRepository.searchByName(name); return new ResponseEntity<>(products, HttpStatus.OK); }