Designing a Unified API Response Structure with Custom Annotations and Interceptors
This article explains how to design a clean, unified API response format for backend services by defining a standard JSON wrapper, categorizing status codes, adding descriptive messages, and using custom @ResponseResult annotations together with interceptors and controller advice to automatically wrap and handle responses in a Spring‑based application.
The author, a senior architect, outlines a typical system architecture focused on API interfaces and emphasizes the need for a consistent response format between front‑end and back‑end.
Front‑end requests a URL with parameters; back‑end processes the request and returns data in JSON. The recommended JSON wrapper is:
{
code: integer, // status code
message: string, // description
data: object // payload
}To avoid chaotic custom codes, the article suggests grouping status codes similar to HTTP conventions, e.g., 200 for success, 404 for not found, and defining custom ranges such as 1000‑1999 for parameter errors, 2000‑2999 for user errors, and 3000‑3999 for interface exceptions.
The Message field provides a user‑friendly description, while the Data field carries the actual business payload. A Result class can encapsulate these fields.
For a cleaner controller implementation, the article proposes adding a static factory method in Result (e.g., Result.success(data) ) to simplify return statements.
To automate wrapping, a custom annotation @ResponseResult is introduced. Methods or classes annotated with it indicate that their return values should be wrapped.
An interceptor examines incoming requests, checks for the presence of @ResponseResult , and marks the request for response wrapping.
The core implementation uses ResponseBodyAdvice and @ControllerAdvice to intercept the response body; if wrapping is required, it replaces the original return value with a Result instance. Exception handling can also be integrated by detecting exception types in the body.
Further optimizations include caching annotation look‑ups to avoid repeated reflection and extending the wrapper to handle additional scenarios.
Overall, the design provides a concise, maintainable way to standardize API responses in Java Spring back‑end projects.
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.