ReviseAlgo Logo

Building REST APIs

ResponseEntity — Full Control Over HTTP Responses

Configuring custom HTTP headers, response bodies, and status codes.

Last Updated: June 15, 2026 10 min read

Introduction

When building REST endpoints, returning a raw Java object (like a list or DTO) defaults the HTTP response status to 200 OK. While simple, real-world APIs must return semantic HTTP status codes, customized response headers, and bodies dynamically. Spring provides ResponseEntity<T>, a generic wrapper, to give developers full control over the HTTP response.

Why It Matters

Proper status codes are the backbone of RESTful communication. Returning 201 Created when a resource is added, 204 No Content when a resource is deleted, or 404 Not Found when a query is missing makes your API predictable and compliant with HTTP standards. It also allows setting security headers or client routing indicators dynamically.

Real-World Analogy

Think of ResponseEntity like a **certified letter with metadata attachments**:

If you send a standard document (raw object), the recipient receives just the paper. If you wrap it in a certified carrier pouch (ResponseEntity), you can stamp the front with official processing status codes (e.g., "Received & Filed", "Access Denied"), add validation stamps, and clip instructions to the header detailing how long they must retain the file.

How It Works

ResponseEntity inherits from HttpEntity, which contains the request/response headers and body. ResponseEntity adds the HTTP status code. Spring offers two ways to build responses:

  1. Constructor-based: new ResponseEntity<>(body, headers, HttpStatus.CREATED).
  2. Builder pattern API (Preferred): ResponseEntity.status(HttpStatus.CREATED).headers(customHeaders).body(body). The builder pattern offers a fluent, type-safe API with shortcuts for common statuses like ok(), created(uri), noContent(), and notFound().

Practical Example

Here is a controller showing proper HTTP responses for creating and retrieving resources:

Quick Quiz

Q1: Which HTTP status code is represented by the builder method ResponseEntity.noContent().build()?

A) HTTP 200 OK

B) HTTP 201 Created

C) HTTP 204 No Content

D) HTTP 404 Not Found

Answer: C — ResponseEntity.noContent() creates a builder initialized with HTTP 204 No Content, which indicates success but sends no body payload.

Q2: What is the primary advantage of the builder API over raw constructor instantiation?

A) Faster execution performance at runtime

B) Readability, fluent builder design, and type-safety validations during development

C) Bypassing the conversion filter layer

D) Forcing the servlet to flush database transactions

Answer: B — Builder APIs are more readable and prevent developer syntax errors from mismatching constructor parameters.

Scenario-Based Challenge

Production Scenario:

Your client wants an API to download invoice PDFs. If the invoice is missing, they expect an HTTP 404 response. If it exists, they expect the response headers configured to force a file download dialog in the browser. How would you design this handler method?

View Solution

Use ResponseEntity mapping to return a byte array or Resource. If the file is missing, return ResponseEntity.notFound().build(). If it exists, set headers:

Interview Questions

1. How does using @ResponseStatus differ from returning a ResponseEntity?

@ResponseStatus is a static annotation used above methods or exception classes to configure a default status code. It is simple, but cannot dynamically adjust status codes based on code branches. ResponseEntity is an object representation returned dynamically, allowing different status codes (e.g. 200 vs 404) based on runtime business checks.

2. Can you return generic headers like Cache-Control using ResponseEntity?

Yes. You can use the builder's .cacheControl(CacheControl.maxAge(...)) method or add custom values directly to the HttpHeaders object, which supports standard helper properties.

Production Considerations

Avoid using wildcard definitions like ResponseEntity<?>. Doing so prevents API documentation tooling (like Swagger/OpenAPI) from identifying the actual resource structure, resulting in blank or undocumented client SDK payloads. Standardize return definitions as ResponseEntity<YourDtoClass>.