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

20 min

Lesson 5 of 11

1d streak

The 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 OperationRecommended StatusResponseEntity PatternHeaders
Resource Created201 CreatedResponseEntity.created(locationUri).body(dto)Location: /api/tasks/{id}
Resource Read200 OKResponseEntity.ok(dto)ETag, Cache-Control
Resource Deleted204 No ContentResponseEntity.noContent().build()None
Asynchronous Accepted202 AcceptedResponseEntity.accepted().body(taskReference)Location: /api/jobs/{id}

Setting response headers, Location URIs, and RFC 9457 ProblemDetail

TaskCreationController.java
@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

When a POST creates a new resource, HTTP recommends 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

  1. Break: Return 200 OK with a body after deleting a resource
  2. Observe: Clients retry deletes and treat stale response bodies as live resources
  3. 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

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

Supplementary Module Resources