What Is ResponseEntity?
ResponseEntity is Spring's way of giving you full control over the HTTP response. Instead of just returning a Java object and letting Spring decide everything, you wrap your response in a ResponseEntity and specify the status code, headers, and body yourself.
Think of it as a response builder. It lets you craft exactly what gets sent back to the client โ the data, the status code, and any metadata you want to include.
Setting HTTP Status Codes
The status code tells the client what happened. A 200 means success, 201 means created, 404 means not found. With ResponseEntity, you choose the exact code that fits the situation.
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
User saved = userService.save(user);
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
}
Spring provides ResponseEntity.ok() for 200 responses and ResponseEntity.notFound() for 404s. These shorthand methods make common cases even simpler.
Custom Headers
Sometimes you need to include extra information in the response โ a total count, a pagination link, or a cache directive. ResponseEntity lets you add custom headers easily.
@GetMapping("/products")
public ResponseEntity<List<Product>> getProducts() {
List<Product> products = productService.findAll();
HttpHeaders headers = new HttpHeaders();
headers.add("X-Total-Count", String.valueOf(products.size()));
return ResponseEntity.ok().headers(headers).body(products);
}
Headers can carry metadata that helps clients understand the response beyond just the data. It's like the fine print on a receipt โ not the main item, but important context.
Building Responses
The builder pattern in ResponseEntity makes it easy to chain calls. Start with a factory method, set the status, add headers, and finish with the body. Each step returns a builder, so the flow reads naturally.
Use ResponseEntity when you need precise control. For simple endpoints where the default 200 status works fine, just return the object directly โ Spring wraps it automatically. Save ResponseEntity for when you truly need to customize the response.