ResponseEntity in Spring Boot
ResponseEntity in Spring Boot is the class you return from a controller method when you want full control over the HTTP response: the status code, the headers and the body. Returning a plain object always gives 200 OK with a JSON body; returning a ResponseEntity lets the same method say 201 Created with a Location header, 204 No Content, 304 Not Modified or 404 Not Found, which is what well-designed REST APIs need.
This tutorial explains what ResponseEntity contains, walks through its builder methods, and builds a complete product API that uses the right status and headers for each operation, including ETag caching and ProblemDetail errors. It finishes with tests written with MockMvcTester and a comparison with @ResponseStatus.
1. What Is ResponseEntity?
ResponseEntity<T> (org.springframework.http) represents a whole HTTP response. It extends HttpEntity<T>, which holds headers and a body, and adds a status code. The type parameter T is the body type: ResponseEntity<ProductResponse> carries a product, ResponseEntity<Void> carries no body.
| Part | Type | Example |
|---|---|---|
| Status code | HttpStatusCode | 201 Created |
| Headers | HttpHeaders | Location: /api/products/KB-100, ETag: "3" |
| Body | T, written as JSON by default | {"sku":"KB-100","name":"Mechanical keyboard"} |
ResponseEntity is like filling in the label yourself: delivery status, special instructions and the parcel, all chosen by you.2. Why Use ResponseEntity
HTTP clients, proxies and browsers act on status codes and headers, not only on the body. A good REST API uses them deliberately:
| Operation | Recommended response | Needs ResponseEntity? |
|---|---|---|
| Read a resource | 200 OK with body, optionally ETag and Cache-Control | Only for headers |
| Create a resource | 201 Created with Location header and body | Yes |
| Update a resource | 200 OK with body, or 204 No Content | For 204, yes (or @ResponseStatus) |
| Delete a resource | 204 No Content | Yes (or @ResponseStatus) |
| Start a long-running job | 202 Accepted with Location of a status resource | Yes |
| Resource unchanged since last read | 304 Not Modified, no body | Yes (ETag) |
The choice of status codes for REST operations is covered in building a REST API.
3. How Spring MVC Writes a ResponseEntity
The automatic 304 handling is a useful bonus: if your GET response has an ETag and the client sends the same value in If-None-Match, Spring answers 304 Not Modified with an empty body, without extra code.
4. ResponseEntity Builder Methods
Create responses with the static builder methods rather than constructors; they read like the HTTP response they produce.
| Method | Status | Notes |
|---|---|---|
ResponseEntity.ok(body) | 200 | Shortcut for ok().body(body) |
ResponseEntity.ok() | 200 | Builder: add headers, then body(...) |
ResponseEntity.created(uri) | 201 | Sets the Location header |
ResponseEntity.accepted() | 202 | For work that continues in the background |
ResponseEntity.noContent() | 204 | Finish with build(); no body |
ResponseEntity.badRequest() | 400 | |
ResponseEntity.notFound() | 404 | Finish with build() |
ResponseEntity.unprocessableContent() | 422 | Spring Framework 7 name; unprocessableEntity() is deprecated |
ResponseEntity.internalServerError() | 500 | |
ResponseEntity.status(code) | Any | Accepts an HttpStatus or an int |
ResponseEntity.of(optional) | 200 or 404 | 200 with the value, or 404 with an empty body if the Optional is empty |
ResponseEntity.ofNullable(body) | 200 or 404 | Same idea for a possibly null value (since Spring Framework 6.0.5) |
ResponseEntity.of(problemDetail) | From the problem | Builds an error response from a ProblemDetail (since 6.0) |
return ResponseEntity.ok(product);
return ResponseEntity.created(location).body(product);
return ResponseEntity.noContent().build();
return ResponseEntity.status(HttpStatus.ACCEPTED)
.location(URI.create("/api/exports/" + jobId))
.build();
5. Setting Response Headers
The builder has shortcuts for common headers and generic methods for anything else:
return ResponseEntity.ok()
.eTag(String.valueOf(product.version())) // quoted automatically
.lastModified(product.updatedAt())
.cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)).cachePublic())
.contentType(MediaType.APPLICATION_JSON)
.header("X-Stock-Level", String.valueOf(product.stock()))
.body(ProductResponse.from(product));
For several headers at once, use headers(h -> ...) with an HttpHeaders consumer. Custom headers should be documented, and should not be needed for anything a standard header already covers.
6. A Complete Example: A Product API
6.1 Domain and DTOs
package com.javabytechie.shop.product;
import java.math.BigDecimal;
public record Product(String sku, String name, BigDecimal price, int stock, long version) {
Product withPriceAndStock(BigDecimal newPrice, int newStock) {
return new Product(sku, name, newPrice, newStock, version + 1);
}
}
package com.javabytechie.shop.product;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.PositiveOrZero;
import java.math.BigDecimal;
public final class ProductDtos {
private ProductDtos() {
}
public record CreateProductRequest(@NotBlank String sku, @NotBlank String name,
@Positive BigDecimal price, @PositiveOrZero int stock) {
}
public record UpdateProductRequest(@Positive BigDecimal price, @PositiveOrZero int stock) {
}
public record ProductResponse(String sku, String name, BigDecimal price, int stock) {
static ProductResponse from(Product product) {
return new ProductResponse(product.sku(), product.name(), product.price(), product.stock());
}
}
}
6.2 Service and Exceptions
package com.javabytechie.shop.product;
import com.javabytechie.shop.product.ProductDtos.CreateProductRequest;
import com.javabytechie.shop.product.ProductDtos.UpdateProductRequest;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
private static final Logger log = LoggerFactory.getLogger(ProductService.class);
private final Map<String, Product> products = new ConcurrentHashMap<>();
public Product create(CreateProductRequest request) {
Product product = new Product(request.sku(), request.name(), request.price(), request.stock(), 1);
if (products.putIfAbsent(product.sku(), product) != null) {
throw new DuplicateProductException(product.sku());
}
log.info("Created product {}", product.sku());
return product;
}
public Product find(String sku) {
return findOptional(sku).orElseThrow(() -> new ProductNotFoundException(sku));
}
public Optional<Product> findOptional(String sku) {
return Optional.ofNullable(products.get(sku));
}
public Product update(String sku, UpdateProductRequest request) {
Product updated = products.computeIfPresent(sku,
(key, current) -> current.withPriceAndStock(request.price(), request.stock()));
if (updated == null) {
throw new ProductNotFoundException(sku);
}
return updated;
}
public void delete(String sku) {
if (products.remove(sku) == null) {
throw new ProductNotFoundException(sku);
}
}
}
package com.javabytechie.shop.product;
class ProductNotFoundException extends RuntimeException {
ProductNotFoundException(String sku) {
super("Product " + sku + " was not found");
}
}
class DuplicateProductException extends RuntimeException {
DuplicateProductException(String sku) {
super("Product " + sku + " already exists");
}
}
6.3 The Controller
package com.javabytechie.shop.product;
import com.javabytechie.shop.product.ProductDtos.CreateProductRequest;
import com.javabytechie.shop.product.ProductDtos.ProductResponse;
import com.javabytechie.shop.product.ProductDtos.UpdateProductRequest;
import jakarta.validation.Valid;
import java.net.URI;
import java.time.Duration;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService service;
public ProductController(ProductService service) {
this.service = service;
}
@PostMapping
public ResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest request) {
Product product = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{sku}")
.buildAndExpand(product.sku())
.toUri();
return ResponseEntity.created(location).body(ProductResponse.from(product));
}
@GetMapping("/{sku}")
public ResponseEntity<ProductResponse> find(@PathVariable String sku) {
Product product = service.find(sku);
return ResponseEntity.ok()
.eTag(String.valueOf(product.version()))
.cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)))
.body(ProductResponse.from(product));
}
@GetMapping("/lookup/{sku}")
public ResponseEntity<ProductResponse> lookup(@PathVariable String sku) {
return ResponseEntity.of(service.findOptional(sku).map(ProductResponse::from));
}
@PutMapping("/{sku}")
public ResponseEntity<ProductResponse> update(@PathVariable String sku,
@Valid @RequestBody UpdateProductRequest request) {
Product product = service.update(sku, request);
return ResponseEntity.ok()
.eTag(String.valueOf(product.version()))
.body(ProductResponse.from(product));
}
@DeleteMapping("/{sku}")
public ResponseEntity<Void> delete(@PathVariable String sku) {
service.delete(sku);
return ResponseEntity.noContent().build();
}
}
ServletUriComponentsBuilder.fromCurrentRequest() builds the Location from the incoming request, so it is correct behind any host name or context path. The lookup endpoint shows ResponseEntity.of(Optional); section 7 explains why the main find endpoint uses an exception instead.
6.4 Try It
curl -i -X POST localhost:8080/api/products -H "Content-Type: application/json" \
-d '{"sku":"KB-100","name":"Mechanical keyboard","price":79.99,"stock":12}'
curl -i localhost:8080/api/products/KB-100
curl -i localhost:8080/api/products/KB-100 -H 'If-None-Match: "1"'
curl -i -X DELETE localhost:8080/api/products/KB-100
HTTP/1.1 201
Location: http://localhost:8080/api/products/KB-100
Content-Type: application/json
{"sku":"KB-100","name":"Mechanical keyboard","price":79.99,"stock":12}
HTTP/1.1 200
ETag: "1"
Cache-Control: max-age=300
Content-Type: application/json
{"sku":"KB-100","name":"Mechanical keyboard","price":79.99,"stock":12}
HTTP/1.1 304
ETag: "1"
HTTP/1.1 204
The third call sent the ETag from the second response, so Spring answered 304 without a body, saving bandwidth. After a PUT, the version and therefore the ETag change, and the next conditional request gets the new data.
7. Returning Errors: Exceptions and ProblemDetail
You could return ResponseEntity.notFound().build() from every method, but then each endpoint decides its own error format, and the service layer must return Optionals everywhere. A cleaner design: the service throws, and one @RestControllerAdvice turns exceptions into ProblemDetail responses (the RFC 9457 format), using ResponseEntity where it needs headers:
package com.javabytechie.shop.product;
import java.net.URI;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
class ProductErrorHandler {
@ExceptionHandler(ProductNotFoundException.class)
ProblemDetail notFound(ProductNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
@ExceptionHandler(DuplicateProductException.class)
ResponseEntity<ProblemDetail> duplicate(DuplicateProductException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
problem.setType(URI.create("https://javabytechie.com/problems/duplicate-product"));
return ResponseEntity.of(problem).header("Retry-After", "0").build();
}
}
HTTP/1.1 404
Content-Type: application/problem+json
{"type":"about:blank","title":"Not Found","status":404,"detail":"Product XX-999 was not found","instance":"/api/products/XX-999"}
Compare this with the lookup endpoint: ResponseEntity.of(Optional) returns a 404 with an empty body, so clients get no explanation. Use it for simple internal endpoints; for public APIs, prefer one error format everywhere. More options are in exception handling in Spring Boot.
8. Testing ResponseEntity Responses
A @WebMvcTest loads only the web layer. MockMvcTester gives fluent AssertJ assertions on status, headers and JSON. The service is replaced with a Mockito mock through @MockitoBean.
package com.javabytechie.shop.product;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import com.javabytechie.shop.product.ProductDtos.CreateProductRequest;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired
MockMvcTester mvc;
@MockitoBean
ProductService service;
private final Product keyboard = new Product("KB-100", "Mechanical keyboard", new BigDecimal("79.99"), 12, 3);
@Test
void createReturns201WithLocation() {
when(service.create(any(CreateProductRequest.class))).thenReturn(keyboard);
assertThat(mvc.post().uri("/api/products").contentType(MediaType.APPLICATION_JSON)
.content("""
{"sku":"KB-100","name":"Mechanical keyboard","price":79.99,"stock":12}
"""))
.hasStatus(HttpStatus.CREATED)
.hasHeader("Location", "http://localhost/api/products/KB-100")
.bodyJson().extractingPath("$.sku").isEqualTo("KB-100");
}
@Test
void getReturnsETagAndThen304ForTheSameETag() {
when(service.find("KB-100")).thenReturn(keyboard);
assertThat(mvc.get().uri("/api/products/KB-100"))
.hasStatus(HttpStatus.OK)
.hasHeader("ETag", "\"3\"");
assertThat(mvc.get().uri("/api/products/KB-100").header("If-None-Match", "\"3\""))
.hasStatus(HttpStatus.NOT_MODIFIED);
}
@Test
void missingProductReturnsProblemDetail() {
when(service.find("XX-999")).thenThrow(new ProductNotFoundException("XX-999"));
assertThat(mvc.get().uri("/api/products/XX-999"))
.hasStatus(HttpStatus.NOT_FOUND)
.bodyJson().extractingPath("$.detail").isEqualTo("Product XX-999 was not found");
}
}
@MockitoBean (Spring Framework 6.2) replaced Spring Boot's @MockBean, which was deprecated in Spring Boot 3.4 and removed in 4.0. In Spring Boot 4, @WebMvcTest is in org.springframework.boot.webmvc.test.autoconfigure and needs the spring-boot-starter-webmvc-test dependency. See Spring Boot testing.9. ResponseEntity vs @ResponseStatus vs Plain Objects
| Approach | Status | Headers | Best for |
|---|---|---|---|
| Return the object | Always 200 | None of your own | Simple reads with no special headers |
@ResponseStatus(HttpStatus.CREATED) on the method | Fixed per method | None of your own | Fixed statuses such as 201 or 204 without headers |
ResponseEntity | Chosen at runtime | Any | Location, ETag, caching, or a status that depends on the outcome |
All three can live in one controller. Pick the simplest one that expresses the response; do not wrap every method in ResponseEntity.ok(...) just for consistency.
10. Common Mistakes
- Returning 200 for everything, including errors with an
"error"field in the body. Clients and monitoring then cannot tell success from failure. - Using
ResponseEntity<?>orResponseEntity<Object>to return a product on success and an error map on failure. Keep the success type specific and handle errors with exceptions. - Building
LocationURLs by hand with a hard-coded host. UseServletUriComponentsBuilder. - Adding a body to
204or304responses. These statuses must not have a body. - Returning
ResponseEntityfrom services. HTTP belongs in the controller; see Spring Boot architecture.
11. Best Practices
- Return
201 Createdwith aLocationheader for every create operation. - Return
204 No Contentfor deletes and for updates that have nothing to return. - Add an
ETagto cacheableGETresponses and let Spring answer304automatically. - Throw exceptions for errors and map them once to
ProblemDetailin a controller advice. - Keep body types specific, such as
ResponseEntity<ProductResponse>, neverResponseEntity<?>. - Use the builder methods instead of constructors for readable code.
- Assert status and headers in tests, not just the body.
12. Summary
ResponseEntity in Spring Boot gives a controller full control over the HTTP status, headers and body. Use its builders to return 201 Created with a Location, 204 No Content for deletes, 202 Accepted for background work and ETag and Cache-Control headers for reads, where Spring answers 304 Not Modified by itself. Keep services free of HTTP types, throw exceptions for errors and translate them once into ProblemDetail responses, and use ResponseEntity.of(Optional) only where an empty 404 is acceptable. Test the status and headers with MockMvcTester, and your API will speak HTTP the way clients expect.
13. References
ResponseEntity in Spring Boot Interview Questions and Answers
Common interview questions on ResponseEntity in Spring Boot, from basic to scenario-based, with short answers you can explain in your own words.
Q. What is ResponseEntity, and which parts of the response does it control?
Answer: ResponseEntity<T> represents the complete HTTP response: an HttpStatusCode, HttpHeaders and an optional body of type T. It extends HttpEntity, which has headers and body, by adding the status. Spring MVC's HttpEntityMethodProcessor applies the status and headers and writes the body with a message converter.
Q. How do you return 201 Created with a Location header for a new resource?
Answer: Build the URI of the new resource, ideally with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri(), and return ResponseEntity.created(uri).body(dto). created() sets both the 201 status and the Location header; the body is optional but convenient for clients.
Q. What do ResponseEntity.of(Optional) and ResponseEntity.ofNullable() return?
Answer: Both return 200 OK with the value as the body when a value is present, and 404 Not Found with an empty body when it is absent: of checks an Optional, ofNullable (Spring Framework 6.0.5 and later) checks for null. They are concise, but the 404 has no explanation, so public APIs often prefer throwing an exception that a controller advice maps to a ProblemDetail.
Q. What does ResponseEntity<Void> mean, and when do you use noContent()?
Answer: ResponseEntity<Void> declares a response with no body. It fits noContent().build() for 204 responses, typically after a successful delete or an update that returns nothing, and status-only responses such as 202 with a Location header. A 204 response must not have a body.
Q. How can a Spring MVC endpoint return 304 Not Modified?
Answer: Set an ETag (or Last-Modified) header on the ResponseEntity of a GET endpoint. When a client sends the same ETag in If-None-Match, Spring MVC compares them and returns 304 with no body automatically. Base the ETag on something that changes with the data, such as a version column. WebRequest.checkNotModified() is an alternative that can skip loading the data entirely.
Q. A controller returns ResponseEntity<?> with a product on success and a Map with an error message on failure. What would you change?
Answer: Make the success type specific, ResponseEntity<ProductResponse>, and stop building error bodies in the controller. Throw meaningful exceptions from the service and handle them in one @RestControllerAdvice that returns ProblemDetail with the right status. Clients then get a consistent error format, API documentation tools can describe the real response type, and controller methods become shorter.