Spring Boot: RequestEntity vs ResponseEntity | RequestBody vs ResponseBody

Daryl Goh
4 min readFeb 4, 2023

--

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.

Today, let’s go through some terms that you will see very often while creating your applications through Spring Boot.

Let’s start with ResponseEntity and RequestEntity.

ResponseEntity and RequestEntity are both classes from the Spring framework used for handling HTTP requests and responses. They provide a way to represent HTTP requests and responses as objects, which makes it easier to work with them in your code.

ResponseEntity is used to represent an HTTP response, including headers, status code, and body. It's commonly used when you want to return a custom HTTP response from a Spring controller. For example, if you want to return a 201 (created) status code along with a newly created resource, you could use ResponseEntity like this:

@PostMapping("/resources")
public ResponseEntity<Resource> createResource(@RequestBody Resource resource) {
Resource createdResource = resourceService.create(resource);
return ResponseEntity.status(HttpStatus.CREATED).body(createdResource);
}

You can use ResponseEntity to customize the HTTP response that your Spring application sends to the client. For example, you can set the HTTP status code, set custom headers, and include a response body.

ResponseEntity<String> response = ResponseEntity
.status(HttpStatus.OK)
.header("Custom-Header", "Custom-Value")
.body("Response Body");

RequestEntity, on the other hand, is used to represent an HTTP request, including headers, method, URI, and body. It's commonly used when you want to make an HTTP request from within your application, for example when you want to consume a REST API. You could use RequestEntity like this:

@GetMapping("/resources/{id}")
public Resource getResource(@PathVariable("id") String id) {
RequestEntity<Void> request = RequestEntity
.get(URI.create("https://api.example.com/resources/" + id))
.accept(MediaType.APPLICATION_JSON)
.build();
ResponseEntity<Resource> response = restTemplate.exchange(request, Resource.class);
return response.getBody();
}

In this example, the RequestEntity is used to construct an HTTP GET request to retrieve a Resource from an external API. The ResponseEntity is used to represent the HTTP response and extract the Resource from it through the ‘restTemplate.exchange()’ method, which is used to execute the request and retrieve the response.

Diving a little deeper, let’s look at what RequestBody and ResponseBody are.

The RequestBody and ResponseBody annotations are used to indicate the request and response body content in a REST API. They can be used in conjunction with ResponseEntity and RequestEntity.

Here’s an example that shows how to use the RequestBody and ResponseBody annotations with ResponseEntity and RequestEntity:

@PostMapping("/resources")
public ResponseEntity<Resource> createResource(@RequestBody Resource resource) {
// Create the resource
Resource createdResource = resourceService.create(resource);

// Return the created resource with a 201 (created) status code
return ResponseEntity
.status(HttpStatus.CREATED)
.body(createdResource);
}

@GetMapping("/resources/{id}")
public ResponseEntity<Resource> getResource(@PathVariable("id") String id) {
// Make a GET request to retrieve the resource from an external API
RequestEntity<Void> request = RequestEntity
.get(URI.create("https://api.example.com/resources/" + id))
.accept(MediaType.APPLICATION_JSON)
.build();
ResponseEntity<Resource> response = restTemplate.exchange(request, Resource.class);

// Return the resource
return response;
}

In this example, the @RequestBody annotation is used in the createResource method to indicate that the request body content should be bound to the Resource object. The createResourcemethod uses the ResponseEntity class to return the created Resource object with a 201 (created) HTTP status code.

The getResource method uses the RequestEntity class to make a GET request to an external API to retrieve a Resource object. The ResponseEntity class is used to represent the response from the API, which includes the Resource object in the response body.

In both cases, the ResponseBody annotation is implicit, as the response body content is being set using the ResponseEntity.body() method. The RequestBody annotation is also implicit, as the request body content is being bound to the Resource object using the @RequestBody annotation.

Here are more examples that can be used in CRUD operations.

@PostMapping("/resources")
public ResponseEntity<Resource> createResource(@RequestBody Resource resource) {
// Save the resource to the database
Resource createdResource = resourceRepository.save(resource);

// Return the created resource with a 201 (created) status code
return ResponseEntity
.status(HttpStatus.CREATED)
.body(createdResource);
}

@GetMapping("/resources/{id}")
public ResponseEntity<Resource> getResource(@PathVariable("id") String id) {
// Retrieve the resource from the database
Optional<Resource> resourceOptional = resourceRepository.findById(id);

// If the resource is not found, return a 404 (not found) status code
if (!resourceOptional.isPresent()) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.build();
}

// Return the resource with a 200 (OK) status code
return ResponseEntity
.status(HttpStatus.OK)
.body(resourceOptional.get());
}

@PutMapping("/resources/{id}")
public ResponseEntity<Resource> updateResource(@PathVariable("id") String id, @RequestBody Resource resource) {
// Retrieve the resource from the database
Optional<Resource> resourceOptional = resourceRepository.findById(id);

// If the resource is not found, return a 404 (not found) status code
if (!resourceOptional.isPresent()) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.build();
}

// Update the resource
resource.setId(id);
Resource updatedResource = resourceRepository.save(resource);

// Return the updated resource with a 200 (OK) status code
return ResponseEntity
.status(HttpStatus.OK)
.body(updatedResource);
}

@DeleteMapping("/resources/{id}")
public ResponseEntity<Void> deleteResource(@PathVariable("id") String id) {
// Retrieve the resource from the database
Optional<Resource> resourceOptional = resourceRepository.findById(id);

// If the resource is not found, return a 404 (not found) status code
if (!resourceOptional.isPresent()) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.build();
}

// Delete the resource
resourceRepository.delete(resourceOptional.get());

// Return a 204 (no content) status code
return ResponseEntity
.status(HttpStatus.NO_CONTENT)
.build();
}

In this example, the ResponseEntity method uses the RequestBody annotation to bind the request body content to the Resource object. The method then saves the Resource object to the database and returns it with a 201 (created) HTTP status code using ResponseEntity.

The getResource, updateResource and deleteResource methods use the ResponseEntity class to handle the HTTP responses for retrieving, updating, and deleting Resource objects.

I hope that you have managed to get a clearing understanding of these terms after reading this article. If you have found this article helpful, please follow me on Medium, like and share this article as it wil greatly help me to reach out to a wider audience.

Please follow me on Medium so that you will be the first to be notified in my weekly sharing of my knowledge in tech.

Want to see what I am working on?

Check out my Personal Website and GitHub

Want to reach out to me?

Connect with me on LinkedIn.

--

--

Daryl Goh

Systems Engineer at Visa | AWS Certified Solutions Architect Associate | Red Hat Certified Engineer | Certified Kubernetes Administrator. Views My Own Only.