What is a ResponseEntity class?

What is it?:

ResponseEntity is a class in Spring Boot that represents the entire HTTP response. It allows developers to control the status code, headers, and body of the response, providing a comprehensive way to customize HTTP responses.

Need:

In many scenarios, simply returning an object from a controller method is not enough. There is a need to control various aspects of the HTTP response, such as status codes and headers, to provide more information and better context to the client.

How is it used?:

ResponseEntity is used in controller methods to return customized responses. By using ResponseEntity, developers can set specific HTTP status codes, add headers, and include the response body, offering more control over the response details compared to returning simple objects.

Example Usage of ResponseEntity

Example 1: Basic Usage

Suppose you have an endpoint that returns a simple message along with an HTTP status code.

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 MyController {

@GetMapping("/hello")
public ResponseEntity<String> sayHello() {
return new ResponseEntity<>("Hello, World!", HttpStatus.OK);
}


}  

In this example:

- The /hello endpoint returns a ResponseEntity with the body "Hello, World!" and the status HttpStatus.OK (200 OK).

Example 2: Adding Headers

You might need to add custom headers to the response.

@GetMapping("/greet")
public ResponseEntity<String> greetUser() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "CustomHeaderValue");

return new ResponseEntity<>("Greetings!", headers, HttpStatus.OK);


}  

In this example:

- The /greet endpoint returns a ResponseEntity with a custom header "Custom-Header" and the status HttpStatus.OK.

Example 3: Returning Complex Objects

You can also return complex objects with ResponseEntity.

@GetMapping("/user")
public ResponseEntity<User> getUser() {
    User user = new User("John", "Doe", "john.doe@example.com");

return new ResponseEntity<>(user, HttpStatus.OK);


}  

In this example:

- The /user endpoint returns a ResponseEntity with a User object as the body and the status HttpStatus.OK.