ResponseEntity is a Spring framework class used to build and customize HTTP responses. It gives developers full control over the response body, HTTP status code, and headers, making it ideal for creating REST APIs with clear and meaningful responses.
Why Use ResponseEntity?
@GetMapping("/employee")
public Employee getEmployee() {
return employee;
}ResponseEntity solves this limitation.
Basic Usage
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return ResponseEntity.ok(
"Hello World");
}Status: 200 OK
Hello World
Returning Custom Status Codes
@PostMapping("/employee")
public ResponseEntity<String> createEmployee() {
return ResponseEntity
.status(HttpStatus.CREATED)
.body("Employee Created");
}Status: 201 Created
Employee Created
Returning Java Objects
@GetMapping("/{id}")
public ResponseEntity<Employee>
getEmployee(
@PathVariable Long id) {
Employee employee =
new Employee(
101L,
"John");
return ResponseEntity.ok(employee);
}{
"id": 101,
name": "John
}
Spring automatically converts the object into JSON.
Adding Custom Headers
@GetMapping("/download")
public ResponseEntity<String> download() {
HttpHeaders headers =
new HttpHeaders();
headers.add(
"Application",
"Employee Service");
return ResponseEntity
.ok()
.headers(headers)
.body("Download Started");
}Application: Employee Service
Download Started
Handling Errors
ResponseEntity is commonly used for error responses.
@GetMapping("/{id}")
public ResponseEntity<String>
getEmployee(
@PathVariable Long id) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body("Employee Not Found");
}Status: 404 Not Found
Employee Not Found
Common Factory Methods
ResponseEntity.ok()
200 OK
ResponseEntity.created()
201 Created
ResponseEntity.badRequest()
400 Bad Request
ResponseEntity.notFound()
404 Not Found
ResponseEntity.noContent()
204 No Content
These methods simplify response creation.
How ResponseEntity Works
Client Request
|
Controller Method
|
ResponseEntity Created
|
Status + Headers + Body
|
HTTP Response Sent
Spring converts the ResponseEntity object into a complete HTTP response.
Suppose an Employee API performs CRUD operations.
Status: 200 OK
Status: 201 Created
Status: 400 Bad Request
Status: 404 Not Found
Using ResponseEntity allows each scenario to return the most appropriate HTTP response.
Benefits
Real-World Example
GET /products/101
200 OK
404 Not Found
400 Bad Request
ResponseEntity helps return the correct status and response body for each situation, improving API usability.
A concise interview answer is
ResponseEntity is used in Spring Boot to build customized HTTP responses. It allows developers to control the response body, status code, and headers. It is commonly used in REST APIs to return appropriate success and error responses such as 200 OK, 201 Created, 400 Bad Request, and 404 Not Found.
Last updated: 11 November 2026
Previous question: What are REST API best practices?
Next question: Which HTTP status code should a DELETE API return?