Skip to content
Advertisement

JSON Custom response in all my REST API, I might not know what it is called?

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 @ResponseBody or a ResponseEntity controller method but before the body is written with an HttpMessageConverter.

Implementations may be registered directly with RequestMappingHandlerAdapter and ExceptionHandlerExceptionResolver or more likely annotated with @ControllerAdvice in 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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement