Understanding RequestEntity and ResponseEntity in Spring Boot
Written on
Chapter 1: Introduction to Spring Boot Entities
Spring Boot simplifies the process of developing stand-alone, production-ready applications based on the Spring framework, allowing you to deploy them effortlessly.
In this article, we will examine some key concepts that are commonly encountered while building applications with Spring Boot. We’ll begin with the classes ResponseEntity and RequestEntity.
ResponseEntity and RequestEntity are both integral components of the Spring framework designed for managing HTTP requests and responses. They allow developers to represent these HTTP interactions as objects, streamlining code management.
ResponseEntity is utilized to represent an HTTP response, encompassing headers, status codes, and body content. It is particularly useful when you need to return a custom HTTP response from a Spring controller. For instance, if you need to send a 201 (Created) status along with a newly created resource, you would implement it as follows:
@PostMapping("/resources")
public ResponseEntity<Resource> createResource(@RequestBody Resource resource) {
Resource createdResource = resourceService.create(resource);
return ResponseEntity.status(HttpStatus.CREATED).body(createdResource);
}
This approach allows you to tailor the HTTP response sent by your Spring application. You can specify the HTTP status code, add custom headers, and include a response body as needed.
ResponseEntity<String> response = ResponseEntity
.status(HttpStatus.OK)
.header("Custom-Header", "Custom-Value")
.body("Response Body");
On the flip side, RequestEntity is employed to signify an HTTP request, which includes headers, method, URI, and body. It is frequently used when your application needs to make an HTTP request, such as consuming an external REST API. Here’s how you can use RequestEntity:
@GetMapping("/resources/{id}")
public Resource getResource(@PathVariable("id") String id) {
RequestEntity<Void> request = RequestEntity
.accept(MediaType.APPLICATION_JSON)
.build();
ResponseEntity<Resource> response = restTemplate.exchange(request, Resource.class);
return response.getBody();
}
In this scenario, RequestEntity constructs an HTTP GET request to obtain a Resource from an external API. The ResponseEntity is then employed to represent the HTTP response and retrieve the Resource through the restTemplate.exchange() method.
Chapter 2: Understanding RequestBody and ResponseBody
Now, let’s delve into the concepts of RequestBody and ResponseBody annotations.
These annotations are pivotal in defining the body content for requests and responses in a REST API. They are often used alongside ResponseEntity and RequestEntity.
Here’s an example illustrating how to utilize RequestBody and ResponseBody with ResponseEntity and RequestEntity:
@PostMapping("/resources")
public ResponseEntity<Resource> createResource(@RequestBody Resource resource) {
Resource createdResource = resourceService.create(resource);
return ResponseEntity
.status(HttpStatus.CREATED)
.body(createdResource);
}
In this method, the @RequestBody annotation indicates that the incoming request body should be mapped to the Resource object. The ResponseEntity class is then used to return the created Resource with a 201 (Created) HTTP status.
@GetMapping("/resources/{id}")
public ResponseEntity<Resource> getResource(@PathVariable("id") String id) {
RequestEntity<Void> request = RequestEntity
.accept(MediaType.APPLICATION_JSON)
.build();
ResponseEntity<Resource> response = restTemplate.exchange(request, Resource.class);
return response;
}
In this example, the getResource method constructs a GET request to retrieve a Resource from an external API using RequestEntity. The ResponseEntity class is then applied to manage the API's response, which contains the requested Resource.
Additional Examples for CRUD Operations
@PostMapping("/resources")
public ResponseEntity<Resource> createResource(@RequestBody Resource resource) {
Resource createdResource = resourceRepository.save(resource);
return ResponseEntity
.status(HttpStatus.CREATED)
.body(createdResource);
}
In this case, the resource is saved to the database, and the created resource is returned with a 201 status code.
@GetMapping("/resources/{id}")
public ResponseEntity<Resource> getResource(@PathVariable("id") String id) {
Optional<Resource> resourceOptional = resourceRepository.findById(id);
if (!resourceOptional.isPresent()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();}
return ResponseEntity.status(HttpStatus.OK).body(resourceOptional.get());
}
This method retrieves the resource from the database. If not found, a 404 (Not Found) status is returned.
@PutMapping("/resources/{id}")
public ResponseEntity<Resource> updateResource(@PathVariable("id") String id, @RequestBody Resource resource) {
Optional<Resource> resourceOptional = resourceRepository.findById(id);
if (!resourceOptional.isPresent()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();}
resource.setId(id);
Resource updatedResource = resourceRepository.save(resource);
return ResponseEntity.status(HttpStatus.OK).body(updatedResource);
}
Here, the updateResource method updates the existing resource and returns it with a 200 (OK) status code.
@DeleteMapping("/resources/{id}")
public ResponseEntity<Void> deleteResource(@PathVariable("id") String id) {
Optional<Resource> resourceOptional = resourceRepository.findById(id);
if (!resourceOptional.isPresent()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();}
resourceRepository.delete(resourceOptional.get());
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
This method deletes the resource from the database and returns a 204 (No Content) status.
Conclusion
In summary, I hope this article has clarified the distinctions and uses of RequestEntity, ResponseEntity, RequestBody, and ResponseBody in Spring Boot. If you found this information valuable, please consider following me on Medium and sharing this article with others. Your support helps me continue creating content like this.
For updates on my latest projects, including a web application developed with Angular, Spring Boot, Firebase, Docker, and Kubernetes, feel free to check out my personal website or connect with me on LinkedIn.
The first video delves into the differences between @RequestBody and @ResponseBody, highlighting frequently asked questions in interviews related to Spring Boot annotations.
The second video also explores the distinctions between @RequestBody and @ResponseBody, providing insights and interview questions relevant to these Spring Boot concepts.