Response Status & ResponseEntity
A good REST API communicates through status codes and headers, not only through the body. By default every successful handler returns 200 OK. This lesson shows the three ways to control the response: @ResponseStatus, ResponseEntity, and exceptions.
The status codes you will use most
| Code | Name | When |
|---|---|---|
| 200 | OK | successful GET, PUT, PATCH with a body |
| 201 | Created | POST created a resource; include a Location header |
| 204 | No Content | success without a body (typical for DELETE) |
| 400 | Bad Request | invalid input |
| 401 | Unauthorized | not logged in |
| 403 | Forbidden | logged in, but not allowed |
| 404 | Not Found | the resource does not exist |
| 409 | Conflict | state conflict, e.g. duplicate name or version clash |
| 422 | Unprocessable Content | well-formed but semantically invalid (some APIs use it instead of 400) |
| 500 | Internal Server Error | a bug — never return it on purpose |
@ResponseStatus: a fixed status
When an endpoint always succeeds with the same status, annotate it:
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Task create(@RequestBody NewTask body) { return service.create(body); }
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
void delete(@PathVariable long id) { service.delete(id); }ResponseEntity: full control
ResponseEntity<T> represents the whole response — status, headers and body — and lets you decide at runtime:
@GetMapping("/{id}")
ResponseEntity<Task> get(@PathVariable long id) {
return service.find(id) // Optional<Task>
.map(ResponseEntity::ok) // 200 + body
.orElse(ResponseEntity.notFound().build()); // 404, no body
}
@PostMapping
ResponseEntity<Task> create(@RequestBody NewTask body, UriComponentsBuilder uri) {
Task saved = service.create(body);
URI location = uri.path("/api/tasks/{id}").buildAndExpand(saved.id()).toUri();
return ResponseEntity.created(location).body(saved); // 201 + Location header
}
@GetMapping("/{id}/export")
ResponseEntity<String> export(@PathVariable long id) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"task-" + id + ".csv\"")
.contentType(MediaType.parseMediaType("text/csv"))
.body(service.toCsv(id));
}curl -s -i -X POST localhost:8080/api/tasks -H "Content-Type: application/json" -d '{"title":"Ship v1"}'HTTP/1.1 201
Location: http://localhost:8080/api/tasks/5
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 16 Oct 2025 04:05:12 GMT
{"id":5,"title":"Ship v1","done":false}
curl -s -i localhost:8080/api/tasks/999HTTP/1.1 404
Content-Length: 0
Date: Thu, 16 Oct 2025 04:05:30 GMT
Builder methods
| Method | Result |
|---|---|
ResponseEntity.ok(body) |
200 with body |
ResponseEntity.created(uri).body(b) |
201 with Location |
ResponseEntity.accepted().build() |
202, work queued |
ResponseEntity.noContent().build() |
204 |
ResponseEntity.badRequest().body(b) |
400 |
ResponseEntity.notFound().build() |
404 |
ResponseEntity.status(HttpStatus.CONFLICT).body(b) |
any status |
ResponseEntity.of(optional) |
200 if present, 404 if empty |
ResponseEntity.of(service.find(id)) is the shortest way to write the get method above.
Modelling the response in plain Java
ResponseEntity is essentially an immutable value: status + headers + body. Here is a small model with the same factory style, used by a handler that decides the outcome:
import java.util.*;
record Response<T>(int status, Map<String, String> headers, T body) {
static <T> Response<T> ok(T body) { return new Response<>(200, Map.of(), body); }
static <T> Response<T> created(String location, T body) { return new Response<>(201, Map.of("Location", location), body); }
static <T> Response<T> notFound() { return new Response<>(404, Map.of(), null); }
static <T> Response<T> of(Optional<T> maybe) { return maybe.map(Response::ok).orElseGet(Response::notFound); }
}
record Task(long id, String title) {}
class TaskApi {
private final Map<Long, Task> store = new TreeMap<>();
private long nextId = 1;
Response<Task> create(String title) {
Task t = new Task(nextId++, title);
store.put(t.id(), t);
return Response.created("/api/tasks/" + t.id(), t);
}
Response<Task> get(long id) { return Response.of(Optional.ofNullable(store.get(id))); }
Response<Void> delete(long id) {
return store.remove(id) != null ? new Response<>(204, Map.of(), null) : Response.notFound();
}
}
class Main {
public static void main(String[] args) {
TaskApi api = new TaskApi();
System.out.println(api.create("Ship v1"));
System.out.println(api.get(1));
System.out.println(api.get(99));
System.out.println(api.delete(1));
System.out.println(api.delete(1));
}
}Response[status=201, headers={Location=/api/tasks/1}, body=Task[id=1, title=Ship v1]]
Response[status=200, headers={}, body=Task[id=1, title=Ship v1]]
Response[status=404, headers={}, body=null]
Response[status=204, headers={}, body=null]
Response[status=404, headers={}, body=null]
Notice the second DELETE returns 404. Some APIs prefer to return 204 again, because DELETE is idempotent (repeating it leaves the server in the same state) — both choices are acceptable, just be consistent.
Exceptions with a status
For error paths, throwing is often cleaner than building a ResponseEntity deep inside a service. ResponseStatusException carries a status and reason:
Task get(long id) {
return repository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Task " + id + " not found"));
}The next lessons on validation and exception handling show how to turn exceptions into consistent JSON error bodies.
Tip: Choose
@ResponseStatuswhen the status never changes,ResponseEntitywhen headers or the status depend on runtime data, and exceptions for errors.
Test yourself
Which status and header should a successful POST that creates a resource return?
- 200 and
Content-Location - 201 and
Location - 204 and
Location - 202 and
Link
What does ResponseEntity.of(Optional.empty()) produce?
- 200 with null body
- 204 No Content
- 404 Not Found
- An exception
Which status code fits a request that tries to create a user whose email is already taken?
- 200
- 404
- 409 Conflict
- 500