Designing a Unified API Response Format with Result Wrapper and @ResponseResult Annotation
This article explains how to standardize backend API responses by defining a JSON result structure, categorizing status codes, and using a custom @ResponseResult annotation with Spring's ResponseBodyAdvice to automatically wrap controller outputs, improving readability and error handling for front‑end developers.
Preface
In today's mobile‑first, distributed, micro‑service world, most projects adopt a micro‑service framework and a front‑back separation architecture. Front‑end responsibilities have become clearer, evolving into "big front‑end" with a mature ecosystem, while back‑end developers need to recognize the growing importance of front‑end work.
Interface Interaction
The front‑end calls the back‑end using agreed URL paths and parameters; the back‑end processes the request and returns data.
Details such as RESTful URL conventions and common request headers (e.g., app_version, api_version, device) are omitted for brevity.
The focus here is on how the back‑end returns data to the front‑end.
Return Format
We usually return a JSON body defined as follows:
{
// return status code
code: integer,
// return message description
message: string,
// return payload
data: object
}CODE Status Codes
Instead of inventing arbitrary codes, we can reference HTTP status codes and design our own ranges:
200 - Request succeeded
301 - Resource permanently moved
404 - Resource not found
500 - Internal server errorWe then categorize custom codes, for example:
#1000–1999 Parameter errors
#2000–2999 User errors
#3000–3999 Interface exceptionsThis classification lets developers quickly infer the error type from the code and use the accompanying message for precise troubleshooting.
Message
The message field provides a user‑friendly description of the error, typically defined alongside the code in an enumeration.
Data
The data field contains the actual payload, varying per business scenario. We encapsulate it in a Result class.
Controller Layer
In a typical controller method (e.g., handling an order request), we wrap the result using Result before returning it. This can become verbose, so we aim to simplify it.
Visual Optimization
By adding static helper methods to Result, the code becomes more readable.
Elegant Optimization
However, always returning a Result object hides the real business meaning, adds boilerplate, and duplicates validation logic that could be handled by frameworks like Hibernate Validator.
1. Every method returns a generic Result without business semantics. 2. Using Result.success and Result.failure is redundant. 3. Null checks can be replaced by validation annotations.
Returning the actual business object directly is cleaner.
Implementation Plan
We introduce a custom annotation @ResponseResult to mark methods whose return values should be wrapped.
1. Define @ResponseResult . 2. Intercept requests to check for the annotation. 3. Implement ResponseBodyAdvice and @ControllerAdvice to wrap the response when needed.
Annotation Class
The annotation simply marks a method or class for response wrapping.
Interceptor
The interceptor examines the incoming request to see if the target method carries @ResponseResult and sets a flag accordingly.
Response Body Rewrite
The ResponseBodyAdvice implementation checks the flag; if wrapping is required, it creates a Result.success(body) object. Exceptions can be handled similarly by detecting an exception type.
Controller Rewrite
Apply @ResponseResult on a controller class or method, and the framework will automatically wrap the return value.
Summary
The proposed solution standardizes API responses while keeping controller code clean. Further improvements could include caching the annotation lookup to avoid reflection on every request.
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.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow 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.
