How to Use Spring ResponseEntity to Manipulate the HTTP Response?
Last Updated :
22 Aug, 2024
ResponseEntity is a powerful class in the Spring Framework that provides a flexible way to handle HTTP responses. It allows us to customize the HTTP response, including the status code, headers, and body, giving you complete control over what is sent back to the client. This class is particularly useful in RESTful APIs where fine-grained control over HTTP responses is often required.
ResponseEntity
ResponseEntity is the class in the Spring Framework that represents the entire HTTP response, including the status code, headers, and body. It is a part of the org.springframework.http package and is a powerful tool for controlling the output of the RESTful services. When you return the ResponseEntity from a controller method, we can fully customize the HTTP response sent to the client. It includes:
- Status Code: The HTTP status code indicating the result of the request. (eg.., 200 OK, 404 Not Found, 500 Internal Server Error).
- Headers: It is a Key-value pair containing the metadata about the responses. (e.g., content type, cache-control).
- Body: The actual content of the response typically in the JSON, XML, or plain text format.
Components of ResponseEntity
ResponseEntity is composed of the three main parts:
1. HTTP Status Code: This is the standard HTTP response code that indicates the result of the HTTP request. Examples include:
- 200 OK: The request was successful and the server is returning the request data.
- 201 Created: The new resource has been created as the result of the request.
- 204 No Content: The request was successful but there is no content to send in the response as a result of the request.
- 400 Bad Request: The server cannot be process the request due to the client error.
- 404 Not Found: The requested resource is not available on the server.
- 500 Internal Server Error: The generic error message when the server fails to fulfill the request.
2. HTTP Headers: It can provide the metadata about the response. Some of the common header include:
- Content-Type: It can specifies the media type of the response (eg.., application/json, text/html).
- Authorization: It can be used for passing the credientials in the APIs that require the authentication.
- Custom Headers: We can define the own headers to pass the additional information, like X-Custom-Header.
3. Response Body: The body contains the actual content of the response. It can be:
- The JSON object can representing the data requested.
- The plain text message indicating the result of the operation.
- HTML content if returning the web page.
- No Content if the operation does not require the response body.
Implementation of Using Spring ResponseEntity to Manipulate the HTTP Response
Step 1: Create a New Spring Boot Project
Create a new Spring Boot Project using IntelliJ Idea. Choose the below options:
- Name: response-entity-example
- Language: Java
- Type: Maven
- Packaging: Jar
Click on the Next button.
Step 2: Add the dependencies
Add the following dependencies into the project.
Step 3: Project Structure
Once created the project then the file structure looks like the below image.
Step 4: Create the ExampleController Class
Create the simple controller class with the various endpoint to demonstrates the responseEntity to manipulate the HTTP response of the Spring application.
Java
package com.gfg.responseentityexample;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ExampleController {
@GetMapping("/success")
public ResponseEntity<String> successResponse() {
String responseBody = "Request was successful!";
return new ResponseEntity<>(responseBody, HttpStatus.OK);
}
@GetMapping("/notfound")
public ResponseEntity<String> notFoundResponse() {
String responseBody = "Resource not found!";
return new ResponseEntity<>(responseBody, HttpStatus.NOT_FOUND);
}
@GetMapping("/customheader")
public ResponseEntity<String> customHeaderResponse() {
String responseBody = "Response with custom header!";
return ResponseEntity
.status(HttpStatus.OK)
.header("Custom-Header", "CustomValue")
.body(responseBody);
}
}
Explanation:
- successResponse(): It can be returns the successful response with HTTP 200 OK status and a simple message.
- notFoundResponse(): It can be returns the response with HTTP 404 Not Found status and indicating the resource was not found.
- customHeaderResponse(): It can be returns with HTTP 200 OK status and the custom header.
Step 5: Main Class
No changes are required in the main class.
Java
package com.gfg.responseentityexample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ResponseEntityExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ResponseEntityExampleApplication.class, args);
}
}
pom.xml file:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg</groupId>
<artifactId>response-entity-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>response-entity-example</name>
<description>response-entity-example</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 6: Run the application
Once completed the project, it will start and run at port 8080.
Step 7: Testing the Endpoints
1. Request and Response for /api/success
GET http://localhost:8080/api/success
Output:
2. Request and Response for /api/notfound
GET http://localhost:8080/api/notfound
Output:
3. Request and Response for /api/customheader
GET http://localhost:8080/api/customheader
Output:
This project provides the basic setup for using the ResponseEntity in the Spring Boot application, showcasing how to handle the different HTTP responses and customize headers of the Spring Boot application.
Similar Reads
How to Use Spring @ResponseStatus to Set HTTP Status Code? In a Spring Boot application, handling HTTP responses with the appropriate status code is crucial for communicating the outcome of a request to the client. The @ResponseStatus annotation in Spring allows developers to set the HTTP status code directly from a controller or exception handler. This app
4 min read
Get the Response Body in Spring Boot Filter In a Spring Boot application, filters can be used to intercept requests and responses, allowing you to manipulate them before reaching the controller or after the response is generated. A common requirement is capturing or logging the response body in the Spring Boot filter, especially for monitorin
5 min read
Spring @ResponseBody Annotation with Example Spring Annotations allow us to configure dependencies and implement dependency injection through java programs. Those are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compil
4 min read
How to Log Request and Response Bodies in Spring WebFlux? To log request and response bodies in Spring WebFlux, we need to use filters or logging mechanisms that can intercept and log the necessary information. In this article, we use WebFilter to filter the request types in the Spring application. Intercepting the Request Body:The getRequest().getBody() m
5 min read
How to Make Post Request in Java Spring? Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc
4 min read
Spring - REST JSON Response REST APIs have become increasingly popular due to their advantages in application development. They operate on a client-server architecture, where the client makes a request, and the server (REST API) responds with data. Clients can be front-end frameworks like Angular, React, or even another Spring
6 min read