Designing Clean API Response Wrappers with Annotations and Interceptors
This article explains how to structure API responses in a microservice environment by using a standard JSON format, custom status code ranges, a Result wrapper class, and Spring annotations with interceptors to automatically package and handle responses and errors in a clean, maintainable way.
The article discusses API response design in modern microservice architectures, emphasizing clear separation between front‑end and back‑end responsibilities.
Below is a typical overall architecture diagram:
For API interfaces, the response is usually a JSON object with three fields: code (status code), message (description), and data (payload).
{
# return status code
code: integer,
# return message
message: string,
# return data
data: object
}Custom status codes can follow HTTP conventions (e.g., 200, 301, 404, 500) and be grouped into ranges for easier classification:
# 1000‑1999 parameter errors
# 2000‑2999 user errors
# 3000‑3999 interface exceptionsThe message field provides a user‑friendly description of the error.
A Result class is introduced to encapsulate these fields, as shown in the diagram:
In a controller, business logic (e.g., an order request) can be wrapped with Result.success() before returning to the front‑end. The article suggests simplifying this by returning the business object directly when possible.
Implementation steps:
Define a custom annotation @ResponseResult to mark methods whose return values need wrapping.
Create an interceptor that checks for this annotation on incoming requests.
Implement ResponseBodyAdvice together with @ControllerAdvice to rewrite the response body into a Result object when required, and to handle exceptions by wrapping them similarly.
Annotation class diagram:
Interceptor diagram:
Response rewrite diagram:
The approach makes response handling concise and elegant, while allowing further optimization such as caching the annotation lookup to avoid repeated reflection.
In summary, using a standard JSON wrapper, custom status code ranges, and Spring’s annotation‑driven interception provides a clean, maintainable way to manage API responses and errors.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
