Designing a Unified API Response Structure for Backend Services
This article explains how to design a unified API response format for backend services, covering JSON structure, status code conventions, message handling, data payload, a Result wrapper class, controller simplifications, custom annotations, interceptors, and global exception handling to achieve clean and maintainable code.
In modern micro‑service architectures, a consistent API response format is essential for front‑end and back‑end interaction. The article proposes a JSON wrapper with three fields: a numeric code , a descriptive message , and a data object.
Example JSON structure:
{
"code": integer,
"message": "string",
"data": object
}To avoid chaotic custom codes, the design recommends grouping status codes similar to HTTP conventions, e.g., 1000‑1999 for parameter errors, 2000‑2999 for user errors, and 3000‑3999 for interface exceptions.
200 - Request succeeded
301 - Resource permanently moved
404 - Resource not found
500 - Internal server errorThe Result class encapsulates these fields and provides static factory methods such as Result.success(data) and Result.failure(code, message) to simplify controller code.
Controller methods can return business objects directly, and the response will be automatically wrapped by a custom @ResponseResult annotation processed through a ResponseBodyAdvice implementation and a ControllerAdvice interceptor.
The workflow includes:
Defining the @ResponseResult annotation to mark endpoints that need wrapping.
Implementing an interceptor that checks for the annotation and sets a request attribute.
Using ResponseBodyAdvice to wrap the returned object into the standard JSON structure when required.
Handling exceptions globally by detecting error types in the advice and converting them to the same wrapper format.
Additional refinements such as static helper methods in Result , caching of annotation checks, and clearer separation of success and error handling are discussed to make the codebase more elegant and maintainable.
The article concludes that while the presented solution already streamlines API responses, further optimizations like caching reflection results can improve performance.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.