Designing a Unified API Response Structure with Custom Annotations and Interceptors
This article explains how to build a clean, maintainable backend API response format by defining a standard JSON wrapper, categorizing status codes, using a Result class with static helpers, and automatically applying the wrapper through a custom @ResponseResult annotation, interceptor, and ResponseBodyAdvice in a Spring‑based service.
The author first outlines a typical system architecture where the front‑end calls a URL with parameters and the back‑end processes the request and returns data.
To standardize the response, a JSON wrapper is defined:
{
"code": integer, // status code
"message": string, // description
"data": object // payload
}Instead of arbitrarily adding status codes, the article suggests grouping them similar to HTTP codes, e.g., 1000‑1999 for parameter errors, 2000‑2999 for user errors, 3000‑3999 for interface exceptions.
The Message field provides a friendly description of the error, while the Data field carries the business‑specific payload.
A Result class is introduced with static methods such as Result.success(data) and Result.failure(code, message) to simplify controller code. Example:
Result result = new Result();
result.setCode(200);
result.setMessage("OK");
result.setData(order);
return result;To avoid repetitive wrapping, a custom annotation @ResponseResult is created. An interceptor checks whether the current request’s handler method is annotated, and a ResponseBodyAdvice implementation automatically wraps the method’s return value into the standard JSON structure when needed.
The article also discusses potential pitfalls of always returning a Result object, such as loss of business meaning, and recommends returning the actual business object when possible, letting the advice layer handle the wrapping.
Finally, the author provides implementation steps: define the annotation class, implement the interceptor to set a request attribute, and write the ResponseBodyAdvice that checks the attribute, wraps the response, and handles exceptions uniformly.
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.