ResponseEntity is a class of Spring Framework that accepts generic types of data. As a result, we can respond with all kinds of data types. ResponseEntity represents the whole HTTP response, including the header, body, and HTTP status. Therefore it is most important to HTTP response. We can use it to fully configure the HTTP response.
Below are the ways to respond to HTTP requests as ResponseEntity.
We have created a simple bean class (Student). Where we defined three variables (id, name, and department). We will use this class for every endpoint.
1. Simple Way : Here we are responding the full student information using ok() mothod of ResponseEntity class. ResponseEntity.ok() Provides a 200 OK response with the specified body.
- Method Used : ResponseEntity.ok();
Response in Postman |
2. Simple Way 2: This is the same as above way to response to the body with HTTP Status as 200 OK. Just syntax is different. We can use any one of both to send HTTP status as 200 OK.
Return list of student information |
Response in Postman |
Response in Postman |
Here it is dynamically responding with HTTP status and response body like the above one but we have used here BodyBuilder interface to achieve that. As a result just syntax is different here.
Used Methods :
- ResponseEntity.badRequest().body()
- ResponseEntity.status().body()
Response in Postman |
5. HTTP response with custom header, HTTP status, and response body using BodyBuilder Interface.
- Used Method : ResponseEntity.ok().header().body()
- Used method - ResponseEntity.status(HttpStatus.CREATED).body();
As you have seen, We have described all the way to HTTP response with ResponseEntity's method. The most important to focus on here are the response custom HTTP status code, custom header, dynamic response based on application logic, and uses of BodyBuilder interface to achieve this.
0 Comments