All about ResponseEntity in Spring Boot - java
What is the ResponseEntity in spring boot?
- Response Body:
"Hello, World!" - Status Code:
200 OK
Setting HTTP Headers:
You can add custom headers to the response:
@GetMapping("/customHeaders")
public ResponseEntity<String> getCustomHeaders
() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "CustomHeaderValue");
return new ResponseEntity<>("Response with custom header", headers, HttpStatus.OK);
}
- Custom Header:
"Custom-Header: CustomHeaderValue" - Status Code:
200 OK
Using ResponseEntity with Builders:
ResponseEntity provides a fluent API for building responses, which improves readability:
java
@GetMapping("/builderExample")
public ResponseEntity<String> builderExample() {
return ResponseEntity
.status(HttpStatus.CREATED)
.header("Custom-Header", "CustomValue")
.body("Resource created successfully");
}
- Response Body:
"Resource created successfully" - Status Code:
201 Created
Handling Errors:
You can use ResponseEntity to return custom error messages and status codes:
java@GetMapping("/notFound")
public ResponseEntity<String> handleNotFound() {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body("The requested resource was not found.");
}
- Response Body:
"The requested resource was not found." - Status Code:
404 Not Found
Generic Type Responses:
ResponseEntity can return more complex objects, including collections and custom types:
java
@GetMapping("/listUsers")
public ResponseEntity<List<User>> listUsers() {
List<User> users = userService.getAllUsers();
return ResponseEntity.ok(users);
}
- Response Body: A list of
Userobjects serialized as JSON or XML. - Status Code:
200 OK
When to Use ResponseEntity?
Use ResponseEntity when you need:
- Custom HTTP Status Codes: To return specific HTTP status codes based on business logic.
- Custom Headers: To add HTTP headers that are not set automatically by Spring.
- Complete Control: When you need full control over the HTTP response that is sent to the client.
- Error Handling: To provide specific error messages and codes in response to client requests.
Conclusion
ResponseEntity is a versatile and essential part of building RESTful web services in Spring Boot. It provides the necessary tools to control the HTTP responses in terms of status codes, headers, and body content, allowing developers to create robust and flexible APIs.
Comments
Post a Comment