ResponseEntity lets you send back a full HTTP response with status, headers, and body. It gives you full control over what the client receives.
0
0
ResponseEntity for full response control in Spring Boot
Introduction
When you want to set a specific HTTP status code like 404 or 201.
When you need to add custom headers to the response.
When you want to return a response body along with status and headers.
When handling errors and want to send detailed info with status.
When building REST APIs that require precise HTTP responses.
Syntax
Spring Boot
ResponseEntity<T> response = ResponseEntity.status(HttpStatus.STATUS_CODE)
.header("Header-Name", "value")
.body(bodyObject);You can chain methods like status(), header(), and body() to build the response.
The generic T is the type of the response body.
Examples
Returns HTTP 200 with a simple text body.
Spring Boot
return ResponseEntity.ok("Success message");
Returns HTTP 404 with a message in the body.
Spring Boot
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Item not found");
Returns HTTP 201 with a Location header and a JSON body.
Spring Boot
return ResponseEntity.status(HttpStatus.CREATED) .header("Location", "/items/123") .body(newItem);
Sample Program
This Spring Boot controller has two endpoints. The first returns HTTP 200 with a custom header and a greeting message. The second returns HTTP 404 with a simple error message.
Spring Boot
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { @GetMapping("/greet") public ResponseEntity<String> greetUser() { return ResponseEntity.status(HttpStatus.OK) .header("Custom-Header", "HelloHeader") .body("Hello, user!"); } @GetMapping("/notfound") public ResponseEntity<String> notFound() { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body("Resource not found"); } }
OutputSuccess
Important Notes
Use ResponseEntity when you need more than just a response body.
Headers can be added multiple times if needed.
Returning just an object without ResponseEntity defaults to HTTP 200.
Summary
ResponseEntity lets you control status, headers, and body in HTTP responses.
It is useful for REST APIs needing precise HTTP responses.
You build it by chaining status(), header(), and body() methods.