Quick revision
The short answer
I would use a ResponseBodyAdvice, because it sees every @ResponseBody and ResponseEntity body just before a converter writes it, and its beforeBodyWrite method can return a wrapper such as Envelope(data). A custom return value handler is the wrong tool, since Spring's own body processor claims those return values before any custom handler is asked. The pitfalls are wrapping ProblemDetail and error bodies, breaking String return values that use StringHttpMessageConverter, and wrapping actuator or other responses, so we limit the advice with basePackages or an annotation; and we should first ask whether the wrapper is needed at all.
What to remember
In this answer, we saw that a ResponseBodyAdvice is the right place to wrap JSON bodies, because it runs just before the converter writes, while a custom return value handler is never consulted for @ResponseBody methods. We wrote a scoped advice that returns Envelope(body), and went through the pitfalls: error bodies like ProblemDetail must stay unwrapped, String return values use StringHttpMessageConverter and fail with a ClassCastException if wrapped, and an unscoped advice wraps actuator and library endpoints. Finally, we asked whether the envelope adds anything beyond what HTTP already provides.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would use a ResponseBodyAdvice, because it sees every @ResponseBody and ResponseEntity body just before a converter writes it, and its beforeBodyWrite method can return a wrapper such as Envelope(data). A custom return value handler is the wrong tool, since Spring's own body processor claims those return values before any custom handler is asked. The pitfalls are wrapping ProblemDetail and error bodies, breaking String return values that use StringHttpMessageConverter, and wrapping actuator or other responses, so we limit the advice with basePackages or an annotation; and we should first ask whether the wrapper is needed at all.
Why this question is asked
Envelope formats like {"data": ...} are common in mobile APIs, often because a client library expects them. Adding the wrapper by hand in every controller is repetitive and easy to forget, so teams look for one place to do it. Spring MVC offers two candidates, and only one of them works well. Interviewers ask this to see whether we know where response bodies are written and what breaks when we intercept them. In this answer, we will recap how a @ResponseBody value becomes JSON, write the advice, go through each pitfall with the failure it causes, and then question whether the envelope is a good idea.
1A Quick Recap of How a Response Body Is Written
When a @RestController method returns an object, RequestResponseBodyMethodProcessor takes it, chooses a media type from the request's Accept header and the method's produces attribute, and picks the first HttpMessageConverter that can write that type and media type. Just before the converter writes, the processor calls every ResponseBodyAdvice that applies, and each one may replace the body.
A ResponseBodyAdvice has two methods. supports() decides whether it applies to a given return type and converter. beforeBodyWrite() receives the body, the chosen media type, the chosen converter class and the request and response, and returns the body to write. That makes it the natural place to wrap.
2Why Not a Custom Return Value Handler?
A HandlerMethodReturnValueHandler processes a controller's return value. It looks like the right hook, but RequestMappingHandlerAdapter asks the built-in handlers first, and RequestResponseBodyMethodProcessor claims every method annotated @ResponseBody, which includes every @RestController method. Our handler would never be asked.
To make it work we would have to replace or decorate Spring's processor inside the adapter's list, for example from a BeanPostProcessor. That works, but it reaches into framework internals, has to reimplement content negotiation, and is the kind of extension that breaks on upgrades. The advice uses a public, documented hook, so it is the better choice.
3Writing the Advice
We limit the advice to the mobile API with an annotation, define a small record for the envelope, and skip the bodies that must not be wrapped.
6 messages in order. Play them, or step through them one at a time.
The converter is chosen before the advice runs, which is the root of the String pitfall.
Notice that a ResponseEntity<Profile> return value works too: the advice receives the Profile inside it, so status and headers set on the ResponseEntity are kept and only the body is wrapped. A null body becomes {"data":null}, which is usually what a mobile client expects for an empty result.
4Pitfall 1: Wrapping Error Bodies
Error responses also pass through ResponseBodyAdvice when they are written by an @ExceptionHandler that returns a body. If we wrap a ProblemDetail, the client receives {"data":{"type":...,"status":400}} with a 400 status, which looks like data and confuses every client that checks for the standard problem format.
So the advice returns error bodies untouched: ProblemDetail, ErrorResponse types, and any error class of our own. Errors produced by Spring Boot's /error endpoint come from BasicErrorController, which is not marked @MobileApi, so the annotation limit already keeps them out.
5Pitfall 2: String Return Values
This is the failure people meet first. When a method returns String, Spring picks StringHttpMessageConverter before the advice runs, because a String can be written as text by that converter. If the advice then returns an Envelope, the String converter receives an object it cannot write.
We have three choices: skip Strings, as our supports() does; serialise the envelope to a JSON string ourselves inside beforeBodyWrite with the ObjectMapper; or tell teams to return a small record instead of a raw String on mobile endpoints. The last is the cleanest, because it makes every mobile response a real JSON object.
6Pitfall 3: Wrapping What Is Not Ours
An advice without any limit applies to every controller in the application, including endpoints that come from libraries: actuator, OpenAPI documentation, admin tools. Wrapping /actuator/health breaks the load balancer's health check, and wrapping the OpenAPI JSON breaks the documentation page.
So we always scope the advice, either with basePackages = "com.example.mobile" or, as above, with annotations = MobileApi.class. The annotation is more explicit: a reader of the controller can see that its responses are wrapped. A test per mobile endpoint and one for /actuator/health keeps the scope honest.
7Do We Need the Envelope at All?
Before building any of this, it is worth asking why the client wants it. HTTP already carries the status, the content type and headers for metadata such as pagination links. Wrapping every body in data adds a layer that repeats what HTTP says and makes the API differ from every other API the client consumes.
Envelopes are justified when they carry something real alongside the data, such as pagination cursors or warnings, and then a typed response class like Page<T>(data, nextCursor) is better than a generic wrapper added by magic. If a client library simply expects data, the advice is a reasonable, contained solution; we just document it and keep the scope narrow.
8Follow-up questions
Does the advice also apply to ResponseEntity return values?
Yes. RequestResponseBodyMethodProcessor and HttpEntityMethodProcessor both call ResponseBodyAdvice, so a ResponseEntity<Profile> has its body wrapped while its status and headers are kept. A ResponseEntity with no body gives null to the advice, which we can wrap or leave empty depending on the contract.
How would you exclude a single endpoint from wrapping?
Add a marker annotation such as @NoEnvelope and check it in supports() with returnType.hasMethodAnnotation(NoEnvelope.class). This keeps the exclusion visible next to the method, rather than in a list of paths inside the advice.
Can the advice change headers too?
Yes, beforeBodyWrite receives the ServerHttpResponse, and headers set there are still applied because the body has not been written yet. This is one of the few reliable places to add a header for @ResponseBody methods, since an interceptor's postHandle runs after the response is already committed.
9Conclusion
In this answer, we saw that a ResponseBodyAdvice is the right place to wrap JSON bodies, because it runs just before the converter writes, while a custom return value handler is never consulted for @ResponseBody methods. We wrote a scoped advice that returns Envelope(body), and went through the pitfalls: error bodies like ProblemDetail must stay unwrapped, String return values use StringHttpMessageConverter and fail with a ClassCastException if wrapped, and an unscoped advice wraps actuator and library endpoints. Finally, we asked whether the envelope adds anything beyond what HTTP already provides.
Open with
I'd use a ResponseBodyAdvice, not a custom return value handler. The reason is that RequestResponseBodyMethodProcessor handles every @ResponseBody method, so it's asked before any custom handler and mine would never run unless I hacked the adapter's handler list.
Then, if they want more
The advice is the documented hook: beforeBodyWrite gets the body, the selected media type and converter, and can return new Envelope(body). I'd scope it, either with basePackages or better with a marker annotation like @MobileApi, so it doesn't wrap actuator health, OpenAPI docs or other library endpoints, which would break load balancer checks. Then the pitfalls.
Error bodies: a ProblemDetail returned from an exception handler goes through the advice too, and wrapping it hides the error format, so I return those untouched. Strings: if a method returns String, StringHttpMessageConverter is already chosen before the advice runs, and returning an Envelope gives a ClassCastException and a 500.
So I either skip that converter in supports, serialise the envelope myself, or ask teams to return a record. ResponseEntity works fine, the body is wrapped and status and headers stay. Finally, I'd ask whether we need the wrapper at all. HTTP already carries status and metadata, so a generic data wrapper is mostly redundant.
If there's real extra content like pagination cursors, I'd prefer a typed response class over a magic wrapper.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring Web MVC
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Every JSON response must be wrapped in {"data": ...} for a mobile API. Would you use a...": https://scrivio-interview-library.netlify.app/spring-boot/mvc-architecture/173ee2013d/