ResponseEntity in Spring MVC — Full HTTP Response Control
Fast recall
Quick revision
Core answer
Understanding of HTTP response control beyond default Spring behavior
Only using ResponseEntity.ok() without knowing the builder API for status codes, headers, and conditional responses
Demonstrate the created() method with Location header for proper 201 responses following REST conventions
Interview-ready guide
Interview answer
For example, GET /orders/42 can return ResponseEntity.ok(order) or notFound().build(). A create endpoint can return created(uri).body(response) when a resource now exists at that URI. An asynchronous POST may instead return 202 Accepted, showing why 'every POST is 201' is incorrect.
ResponseEntity in Spring MVC — Full HTTP Response Control
Direct Answer
ResponseEntity represents an HTTP response's status, headers, and optional body. Use it when a controller needs dynamic status selection, explicit headers, or an empty response. Returning an ordinary @ResponseBody value commonly yields 200, but annotations and exception handling can choose other statuses, so it is not an unconditional wrapper rule.
Code Example
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@Autowired
private OrderService orderService;
@PostMapping
public ResponseEntity<Order> createOrder(@RequestBody OrderRequest request) {
var order = orderService.create(request);
var location = URI.create("/api/orders/" + order.id());
return ResponseEntity.created(location).body(order); // 201 with Location header
}
@GetMapping("/{id}")
public ResponseEntity<Order> getOrder(@PathVariable Long id) {
return orderService.findById(id)
.map(ResponseEntity::ok) // 200 if found
.orElse(ResponseEntity.notFound().build()); // 404 if missing
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteOrder(@PathVariable Long id) {
orderService.delete(id);
return ResponseEntity.noContent().build(); // 204 No Content
}
}
Common Mistakes & Pitfalls
- Always returning 200 OK: Freshers often use ResponseEntity.ok() for everything including POST and DELETE. REST clients expect 201 for creates and 204 for deletes—using 200 breaks HTTP conventions and confuses client code.
- Not using the builder API: Writing new ResponseEntity(body, HttpStatus.OK) instead of ResponseEntity.ok(body) is verbose and ignores Spring's fluent API designed for readability.
- Mixing ResponseEntity with @ResponseStatus: Annotating a method with @ResponseStatus(CREATED) and also returning ResponseEntity creates ambiguity—pick one approach and stick with it across the controller.
Check your understanding
Answer these without looking back at the article.
- What is the difference between ResponseEntity and @ResponseStatus?
- What is the Location header and when should you set it?
- How do you return a 204 No Content from a DELETE endpoint?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.