Foundation · Build
Response Handling
ResponseEntity controls status, headers, and body together; @ResponseStatus suits fixed codes, and bare returns suit 200-only endpoints.
Primary source: Spring MVC: Response Handling and ResponseEntity
Lesson 5 of 11
1d streakThe Architectural Question
Answering everything with 200 flattens HTTP semantics: clients cannot distinguish creation from reading, caches misbehave, and monitoring dashboards lie.
What this guide proves
- ResponseEntity
- @ResponseStatus
- Location Header
ResponseEntity: Full HTTP response control
While returning a raw DTO from a @RestController defaults to 200 OK, production REST APIs must explicitly control HTTP status codes, headers (such as Location for created resources), and caching directives using ResponseEntity<T>.
| HTTP Operation | Recommended Status | ResponseEntity Pattern | Headers |
|---|---|---|---|
| Resource Created | 201 Created | ResponseEntity.created(locationUri).body(dto) | Location: /api/tasks/{id} |
| Resource Read | 200 OK | ResponseEntity.ok(dto) | ETag, Cache-Control |
| Resource Deleted | 204 No Content | ResponseEntity.noContent().build() | None |
| Asynchronous Accepted | 202 Accepted | ResponseEntity.accepted().body(taskReference) | Location: /api/jobs/{id} |
Setting response headers, Location URIs, and RFC 9457 ProblemDetail
@PostMapping
public ResponseEntity<TaskResponse> createTask(
@RequestBody @Valid CreateTaskRequest request,
UriComponentsBuilder uriBuilder
) {
TaskResponse created = taskService.create(request);
URI location = uriBuilder
.path("/api/v1/tasks/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity
.created(location) // Sets 201 Created and Location header!
.body(created);
}Spring Framework 6 introduced ProblemDetail and the RFC 9457 error-response model (which supersedes RFC 7807). In Spring Boot 3.5, the built-in MVC Problem Details handling is opt-in through spring.mvc.problemdetails.enabled=true, or you can expose a deliberate contract from @RestControllerAdvice.
Break it deliberately: Returning 200 OK for resource creation
Returning 200 OK without a Location header on a POST creation violates REST constraints and breaks client cache invalidation.
REST Architectural Constraint
201 Created with a Location header identifying the primary resource. The protocol also permits the target URI to identify the resource when Location is absent, so choose and document one consistent API contract rather than treating the header as an unconditional requirement.Check your understanding
Active Recall Checkpoint
Which modern RFC defines the Problem Details model used by Spring Framework 6?
Hint: Problem Details for HTTP APIs.
Show answer & explanation
RFC 9457, which supersedes RFC 7807. Spring Framework 6 represents it with ProblemDetail; Boot still needs the relevant MVC handling enabled or customized.
Active Recall Checkpoint
What should an API document about the Location header when it returns 201 Created?
Hint: Where is the newly created resource located?
Show answer & explanation
Whether the API sends Location for the primary created resource. HTTP recommends the header, but the target URI can identify the resource when Location is omitted.
Synthesis & Production Verification
Deliberate Failure Condition
- Break: Return 200 OK with a body after deleting a resource
- Observe: Clients retry deletes and treat stale response bodies as live resources
- Repair: Answer deletions with 204 No Content; pick statuses by what happened on the server, not by convenience.
Production Acceptance Criteria
- Return 201 Created with a Location header after creation
- Answer a successful deletion with 204 No Content
- Set a custom response header alongside a JSON body
Key Takeaway
ResponseEntity provides complete control over HTTP status codes, headers, and bodies; returning accurate semantics enables caching and automated client error handling.
Architectural & Technical Review
Core Interview Questions
Q01Why is returning 200 OK for every outcome considered an antipattern?Show answer
It forces clients to inspect arbitrary JSON payloads to detect errors, prevents HTTP intermediaries from caching, and breaks automated retry logic.
Q02What headers should accompany a 201 Created response?Show answer
A Location header pointing to the canonical URI of the newly created resource.
Q03Can a 204 No Content response contain a response body?Show answer
No. RFC 9110 specifies that a 204 response must not include a message body.
Production Pitfalls
Critical Anti-Patterns
- Pitfall: Returning 200 on DELETE with a JSON status message — Returning 200 OK requires clients to parse custom JSON; 204 No Content provides standard, language-agnostic confirmation of deletion.
- Pitfall: Omitting Location headers on resource creation — Without Location headers, clients must manually construct resource URIs, creating brittle coupling to route patterns.
Primary Documentation & Specifications
Lesson Primary References
Supplementary Module Resources