Sub topic 8
Controlling responses with ResponseEntity
This chapter assumes you can write a basic @RestController with @GetMapping and @PostMapping methods. It also assumes you know common HTTP status codes and headers. By the end, you will know when returning a plain object is enough and when you need ResponseEntity to control the status code and headers.
What Spring does by default
When a controller method returns an object, Spring serializes it to JSON and sends status 200 OK. That works for simple reads. It is not enough when the correct response is 201 Created, 204 No Content, or a response that carries a header.
ResponseEntity<T> represents the whole HTTP response: status, headers, and body. The type parameter T is the type of the body.
| Situation | Plain return value | ResponseEntity |
|---|---|---|
| Read returns data | 200 with body | 200 with body |
| Create a resource | 200 only | 201 plus `Location` header |
| Delete a resource | 200 with empty body | 204 No Content |
| Conditional result | Not possible | 200 or 404 chosen at runtime |
Returning 201 Created with a Location header
A successful POST that creates a resource should return 201 Created. It should also include a Location header that points to the new resource. Clients can follow that URL to fetch what they created.
@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 template segment, and buildAndExpand fills it in. The result is http://localhost:8080/api/books/42. Building the URI from the request avoids hard-coding the host and port.
ResponseEntity.created(location) sets the status to 201 and adds the header. The .body(created) call adds the JSON body and finishes the response.
Other common responses
ResponseEntity has static factory methods for the common statuses:
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable long id) {
service.delete(id);
return ResponseEntity.noContent().build();
}
@GetMapping("/{id}/cover")
public ResponseEntity<BookResponse> getWithCache(@PathVariable long id) {
BookResponse book = service.get(id);
return ResponseEntity.ok()
.header("Cache-Control", "max-age=60")
.body(book);
}
@PutMapping("/{id}")
public ResponseEntity<Void> accept(@PathVariable long id) {
return ResponseEntity.status(HttpStatus.ACCEPTED).build();
}Use ResponseEntity<Void> when there is no body. Call build() to finish a response without a body, and body(...) to finish one with a body.
Choosing the status code
The diagram shows how a controller method typically decides what to return.
Common mistakes
- Returning
ResponseEntity.ok(null)for a missing resource. Signal a missing resource with a 404 instead. The next chapters show how to do that with an exception handler. - Using the raw type
ResponseEntityinstead ofResponseEntity<BookResponse>. The raw type loses type information. - Hard-coding the
LocationURL. This breaks behind proxies and in other environments. - Returning
ResponseEntityfrom every method. When the answer is always 200 with a body, a plain return type is simpler and reads better.
Exercise
A DELETE endpoint removes a book and has nothing to return. Which ResponseEntity call produces the right response, and what status code does it send?
Show answer
ResponseEntity.noContent().build() with return type ResponseEntity<Void>. It sends status 204 No Content with an empty body.
Exercise
Why does the create method build the Location header with ServletUriComponentsBuilder.fromCurrentRequest() instead of a hard-coded string?
Show answer
The builder derives the scheme, host, port and path from the incoming request, so the URL stays correct in every environment and behind proxies. A hard-coded string would break when any of those change.