What are the uses of ResponseEntity?

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.

Key Points: • ResponseEntity allows customization of HTTP status codes. • It can include custom response headers. • It supports returning Java objects, JSON data, or error messages. • It improves API response clarity and flexibility. • It is commonly used in REST controllers.

Why Use ResponseEntity?

Without ResponseEntity:

Code Example:

@GetMapping("/employee")
public Employee getEmployee() {

    return employee;
}

Spring automatically returns:

• Response Body • Status 200 OK

However, we cannot easily customize:

• HTTP status • Response headers • Error responses

ResponseEntity solves this limitation.

Basic Usage

Code Example:

@GetMapping("/hello")
public ResponseEntity<String> hello() {

return ResponseEntity.ok(

            "Hello World");
}

Response:

Status: 200 OK

Body:

Hello World

Returning Custom Status Codes

Code Example:

@PostMapping("/employee")
public ResponseEntity<String> createEmployee() {

return ResponseEntity .status(HttpStatus.CREATED)

            .body("Employee Created");
}

Response:

Status: 201 Created

Body:

Employee Created

Returning Java Objects

Code Example:

@GetMapping("/{id}")
public ResponseEntity<Employee>
        getEmployee(
                @PathVariable Long id) {

    Employee employee =
            new Employee(
                    101L,
                    "John");

    return ResponseEntity.ok(employee);
}

Response:

{ "id": 101, "name": "John" }

Spring automatically converts the object into JSON.

Adding Custom Headers

Code Example:

@GetMapping("/download")
public ResponseEntity<String> download() {

    HttpHeaders headers =
            new HttpHeaders();

    headers.add(
            "Application",
            "Employee Service");

return ResponseEntity .ok() .headers(headers)

            .body("Download Started");
}

Response:

Application: Employee Service

Body:

Download Started

Handling Errors

ResponseEntity is commonly used for error responses.

Code Example:

@GetMapping("/{id}")
public ResponseEntity<String>
        getEmployee(
                @PathVariable Long id) {

return ResponseEntity .status(HttpStatus.NOT_FOUND)

            .body("Employee Not Found");
}

Response:

Status: 404 Not Found

Body:

Employee Not Found

Common Factory Methods

ResponseEntity.ok()

Returns:

200 OK

ResponseEntity.created()

Returns:

201 Created

ResponseEntity.badRequest()

Returns:

400 Bad Request

ResponseEntity.notFound()

Returns:

404 Not Found

ResponseEntity.noContent()

Returns:

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.

Example: Suppose an Employee API performs CRUD operations.

Successful Retrieval:

Status: 200 OK

Employee Created:

Status: 201 Created

Invalid Request:

Status: 400 Bad Request

Employee Not Found:

Status: 404 Not Found

Using ResponseEntity allows each scenario to return the most appropriate HTTP response.

Benefits

• Full control over HTTP responses • Better REST API design • Easy status code management • Custom header support • Consistent error handling

Real-World Example

In an e-commerce application:

GET /products/101

If the product exists:

200 OK

If the product is unavailable:

404 Not Found

If validation fails:

400 Bad Request

ResponseEntity helps return the correct status and response body for each situation, improving API usability.

Interview Tip: 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."