What is the difference between returning a ResponseEntity vs directly returning an object in a REST API?

Returning ResponseEntity from a REST controller gives explicit control over the HTTP status code, headers, and body, while returning a plain object lets Spring Boot handle those details automatically with a default 200 OK response.

Key Points: • ResponseEntity is used when the response needs a specific status code, such as 201 Created or 404 Not Found. • ResponseEntity supports adding custom headers, like Location for a newly created resource. • Returning a plain object is simpler and sufficient when every response is a straightforward 200 OK with just a body. • Both approaches are automatically serialized to JSON by Spring's HttpMessageConverter machinery. • Overusing ResponseEntity for every trivial endpoint adds unnecessary boilerplate; it's best reserved for cases needing real customization.

Example: A POST endpoint that creates a resource typically returns ResponseEntity.status(HttpStatus.CREATED).body(resource) so clients get a 201 with a Location header, whereas a simple GET endpoint can just return the resource object directly.

Code Example:

@PostMapping("/orders")
public ResponseEntity<Order> createOrder(@RequestBody OrderDto dto) {
    Order created = orderService.create(dto);
    return ResponseEntity.status(HttpStatus.CREATED).body(created);
}

@GetMapping("/orders/{id}")
public Order getOrder(@PathVariable Long id) {
    return orderService.findById(id);
}

Interview Tip: A concise interview answer is:

"I return ResponseEntity when I need to control the status code or headers explicitly, like a 201 with a Location header on creation. For straightforward 200 OK responses where no customization is needed, returning the object directly is simpler and Spring wraps it automatically."