I am currently trying to create a REST API using Spring Boot.
I am using ResponseEntity to provide responses and additionally creating an object for consolidated responses.
The code currently looks like this
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RestResponse<T> {
private Integer status;
private HttpStatus httpStatus;
private String path;
private String message;
private T data;
}
If in the service layer
DeviceEntity resultCreate = deviceMapper.getDeviceByDeviceIndex(deviceEntity.getDeviceIndex());
Send the result to
return RestResponse.builder()
.status(200)
.httpStatus(HttpStatus.OK)
.message("Success")
.data("")
.build();
return RestResponse.builder()
.status(ase.statusCode())
.httpStatus(HttpStatus.valueOf(ase.statusCode()))
.message(ase.awsErrorDetails().errorCode())
.data("")
.build();
When we use a try catch to return a RestResponse and the controller puts it in a responseEntity and returns it to us, we can use the
Is this the right structure?
Isn't the wrapping supposed to be done at the controller layer?
If we need to modify it, how can we do it?
I am currently thinking that I need to create a RestResponse object in the controller layer.
Here's a comprehensive response to your query, combining best practices and addressing your concerns:
Key Points:
RestResponseobjects within controllers.Recommended Structure:
Controller Layer:
RestResponseobjects based on service results and HTTP status codes.RestResponseinResponseEntityand return it.Service Layer:
Exception Handling:
@ExceptionHandlerin controllers to handle exceptions and construct appropriateRestResponseobjects.Additional Considerations:
RestResponsefields to your API's needs.By following this structure, you'll create well-structured, adaptable, and user-friendly REST APIs with Spring Boot.