Sub topic 8
Controlling Responses with ResponseEntity
This chapter assumes you know Java records, basic HTTP (methods, status codes, headers), and how to write a @RestController with @GetMapping and @PostMapping. You should also know how @RequestBody binds JSON to a DTO. Here you learn how to control the status code, headers, and body of a response.
Why a plain return value is not enough
When a controller method returns a plain object, Spring MVC serializes it to JSON and sends status 200 OK. That fits simple reads. It does not fit many other cases:
- Creating a resource should return
201 Createdwith aLocationheader. - A delete usually returns
204 No Contentwith no body. - A conditional read may return
304 Not Modified. - A missing resource should return
404 Not Found.
ResponseEntity<T> represents the whole HTTP response: status line, headers, and body. The type parameter T is the body type. Returning it tells Spring to use exactly what you built instead of the defaults.
@GetMapping("/{id}")
public ResponseEntity<BookResponse> get(@PathVariable long id) {
BookResponse book = service.get(id);
return ResponseEntity.ok(book);
}This behaves the same as returning BookResponse directly. The value appears when you need something other than the default.
How Spring handles the return value
Spring MVC picks a return value handler based on the method's return type. For ResponseEntity, the handler copies the status and headers to the response. Then it passes the body to an HttpMessageConverter. For JSON, that converter is Jackson's.
The diagram shows the path.
The handler class is HttpEntityMethodProcessor. You rarely use it directly, but knowing it exists explains one behavior: the Content-Type header comes from content negotiation, unless you set it yourself in the ResponseEntity.
Building responses with the builder API
ResponseEntity has static factory methods and a fluent builder. The common ones are below.
| Goal | Code | Status |
|---|---|---|
| Return a body | `ResponseEntity.ok(body)` | 200 |
| Created resource | `ResponseEntity.created(uri).body(body)` | 201 |
| Accepted for later processing | `ResponseEntity.accepted().build()` | 202 |
| No body | `ResponseEntity.noContent().build()` | 204 |
| Bad request | `ResponseEntity.badRequest().body(body)` | 400 |
| Not found | `ResponseEntity.notFound().build()` | 404 |
| Any status | `ResponseEntity.status(HttpStatus.CONFLICT).body(body)` | your choice |
Use .build() when there is no body. Use .body(x) when there is one. Both end the chain and return the ResponseEntity.
Creating resources: 201 and Location
A successful POST that creates something should return 201 Created. It should also include a Location header with the URI of the new resource. This lets clients find the resource without guessing its URL.
@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody CreateBookRequest request) {
BookResponse created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location).body(created);
}fromCurrentRequest() starts from the URL of the current request, for example http://localhost:8080/api/books. The .path("/{id}") call appends a segment, and buildAndExpand fills in the new id. The result is http://localhost:8080/api/books/42.
Building the URI from the current request avoids hard-coding host names and ports. It also keeps the URI correct behind a proxy when the application is configured to honor forwarded headers (for example with server.forward-headers-strategy=framework).
A response from this endpoint looks like this:
HTTP/1.1 201
Location: http://localhost:8080/api/books/42
Content-Type: application/json
{"id":42,"title":"Dune","author":"Frank Herbert"}Deleting resources: 204
A successful delete has nothing useful to return. Use 204 No Content with no body.
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable long id) {
service.delete(id);
return ResponseEntity.noContent().build();
}The type ResponseEntity<Void> documents that there is no body. Do not return 200 with an empty body instead. Clients and tools read 204 as an explicit statement that the body is intentionally empty.
Adding headers
You can add any header with .header(name, value), or pass a full HttpHeaders object. Constants in HttpHeaders avoid typos in header names.
@GetMapping("/{id}/export")
public ResponseEntity<byte[]> export(@PathVariable long id) {
byte[] content = service.exportAsCsv(id);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"book-" + id + ".csv\"")
.contentType(MediaType.parseMediaType("text/csv"))
.body(content);
}Here ResponseEntity.ok() returns a builder, not a finished response. The chain ends with .body(content). The byte[] body is written as-is by ByteArrayHttpMessageConverter. Jackson is not involved.
Returning 404 when something is missing
If a lookup may find nothing, you have two common styles.
The first style uses Optional and returns 404 from the controller:
@GetMapping("/{id}")
public ResponseEntity<BookResponse> get(@PathVariable long id) {
return service.find(id)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}The second style has the service throw BookNotFoundException, and a @RestControllerAdvice converts it to a ProblemDetail with status 404. The controller then stays short and always returns the success case:
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id); // throws BookNotFoundException if missing
}Prefer the second style for most APIs. The first style gives a 404 with an empty body, while the exception handler gives a structured error body with a title and detail. It also keeps the error format the same across all endpoints. Chapter content on @RestControllerAdvice covers the handler in detail.
Setting the status without ResponseEntity
ResponseEntity is not required when only the status differs from 200. The @ResponseStatus annotation sets a fixed status:
@PostMapping("/archive")
@ResponseStatus(HttpStatus.ACCEPTED)
public void archiveAll() {
service.archiveAll();
}Choose between the two like this:
| Situation | Better choice |
|---|---|
| Status is always the same, no custom headers | `@ResponseStatus` |
| Status or headers depend on runtime logic | `ResponseEntity` |
| You need a `Location` header | `ResponseEntity` |
| Body type differs by outcome | `ResponseEntity<?>` or exceptions |
@ResponseStatus cannot set headers, and it cannot change the status per call.
Common errors
Returning `ResponseEntity<Object>` or `<?>` everywhere
Using ResponseEntity<?> lets a method return different body types, but it hides the contract. Generated API documentation and other developers cannot see what the endpoint returns. Prefer a specific type, and let exceptions handle the error cases.
Mixing `ResponseEntity` with `@ResponseStatus`
If a method returns ResponseEntity, the status in the entity wins. A @ResponseStatus on the same method does not override it. Use one mechanism per method.
Sending a body with 204 or 304
Status 204 and 304 must not carry a body. If you call ResponseEntity.status(204).body(x), the server may drop the body or the client may reject the response. Use .build() for these statuses.
Wrong status for create and update
A frequent mistake is to return 200 from a POST that creates a resource. Use 201 with a Location header. For PUT that replaces an existing resource, return 200 with the updated body or 204 with none. Both are valid. Choose one and use it consistently.
Forgetting that `ResponseEntity` is not validated
Spring does not check that your status and body make sense together. Returning ResponseEntity.ok(null) sends 200 with an empty body. If you meant "not found", say so explicitly.
Caching headers
ResponseEntity also gives you access to HTTP caching. The cacheControl method takes a CacheControl object:
@GetMapping("/{id}/cover")
public ResponseEntity<byte[]> cover(@PathVariable long id) {
byte[] image = service.coverImage(id);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePublic())
.contentType(MediaType.IMAGE_JPEG)
.body(image);
}This sends Cache-Control: max-age=3600, public. A browser or proxy can reuse the response for an hour without calling your server. The builder also has eTag(...) and lastModified(...) for conditional requests.
A complete example
This controller combines the patterns above. It assumes BookService, CreateBookRequest, and BookResponse from earlier chapters, and that BookService has update and delete methods.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}
@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody CreateBookRequest request) {
BookResponse created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location).body(created);
}
@PutMapping("/{id}")
public BookResponse update(@PathVariable long id,
@Valid @RequestBody CreateBookRequest request) {
return service.update(id, request);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable long id) {
service.delete(id);
return ResponseEntity.noContent().build();
}
}Only the methods that need a non-default response use ResponseEntity. The get and update methods return the DTO directly, because 200 is correct for them.
Exercise
A client sends POST /api/books and your controller creates the book with id 7. Which status code and header should the response contain, and which ResponseEntity call produces them?
Show answer
Status 201 Created with a Location header pointing to the new resource, for example http://localhost:8080/api/books/7. Build the URI (for example with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(7).toUri()) and return ResponseEntity.created(uri).body(created).
Exercise
Why is ResponseEntity.status(HttpStatus.NO_CONTENT).body(book) a poor choice, and what should you write instead?
Show answer
A 204 response must not have a body, so the body may be dropped or cause client errors. Write ResponseEntity.noContent().build(), or return 200 with the body if the client needs the data.
Exercise
A method is annotated with @ResponseStatus(HttpStatus.ACCEPTED) but returns ResponseEntity.ok(result). What status does the client receive?
Show answer
200 OK. When a method returns ResponseEntity, the status inside the entity is used, and @ResponseStatus does not override it. Use only one of the two mechanisms.