So the problem goes like this, for all my REST API endpoints there should be 3 fields always there in my RESPONSE Body like for eg:
{
"status": "SUCCESS",
"message": "A list of a recent post",
"data" : [LIST OF POSTS]
}
or
{
"status" : "NOT_AUTHORIZED",
"message": "User does not have previledge to access this resource",
"errors": ["User does not have Admin access"]
}
So you can get the idea, I want this message status error or data field to be there in all response in my REST API.
Advertisement
Answer
It could be achieved with a ResponseBodyAdvice:
Allows customizing the response after the execution of an
@ResponseBodyor aResponseEntitycontroller method but before the body is written with anHttpMessageConverter.Implementations may be registered directly with
RequestMappingHandlerAdapterandExceptionHandlerExceptionResolveror more likely annotated with@ControllerAdvicein which case they will be auto-detected by both.
So you could have something like:
@ControllerAdvice
public class MyResponseBodyAdvisor implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
return converterType.isAssignableFrom(MappingJackson2HttpMessageConverter.class);
}
@Override
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
MyResponseWrapper wrapper = new MyResponseWrapper();
wrapper.setData(body);
return wrapper;
}
}
Where MyResponseWrapper is your class used to wrap the response payload.