Member-only story
Generic API Response With Spring Boot
In this tutorial, we will learn How to create Generic Response Model structure and used in our spring boot project while returning API response. What are the benefits of using Generic Response model ?
What is Response ?
When a client, Such as a web browser or any application, request a resource from the server. the server process the request and provides a Response.
What is ResponseEntity ?
In Spring boot, ResponseEntity is a class that represents the entire Http Response and is derived from HttpEntity class.
Http Response mainly contains : Status Code, headers and body. we can change these features of the response from our endpoints that is controller methods and use them flexibly.
@GetMapping("/employee")
public ResponseEntity<GenericResponse<List<Employee>>> getAllEmployee(){
return ResponseEntity
.status(HttpStatus.OK)
.header("custome-header", "value")
.body(GenericResponse.success(employeeService.getAllEmployee()," Get all employee successfully."));
}
In this example, we returned a response using the status code, header and body.
Okay Lets Create our Generic Response Model class with overloaded method :