Designing a Unified API Response Structure for Backend Services
This article explains how to design a consistent JSON response format for backend APIs, covering status‑code conventions, message handling, data payloads, a Result wrapper class, controller implementation, a @ResponseResult annotation, interceptor logic, and suggestions for further optimization.
In modern micro‑service architectures, backend services need a uniform way to return data to front‑end clients. The article introduces a JSON response body consisting of { code: integer, message: string, data: object } , and discusses how to define meaningful status‑code ranges (e.g., 1000‑1999 for parameter errors, 2000‑2999 for user errors, 3000‑3999 for interface exceptions).
It then describes the Result class that encapsulates these fields, shows how to construct success and failure responses, and demonstrates how to simplify controller code by using static helper methods.
The author proposes an annotation @ResponseResult to mark controller methods whose return values should be automatically wrapped. An interceptor examines the annotation, and a ResponseBodyAdvice implementation rewrites the response body when needed.
Implementation steps include creating the annotation class, configuring the interceptor to set a request attribute, and overriding the response body advice to produce the unified Result object. The article also touches on global exception handling, suggesting that exception objects can be wrapped similarly.
Finally, the piece offers practical tips such as caching reflection results for performance, and encourages developers to extend the pattern to suit their own projects.
Top Architecture Tech Stack
Sharing Java and Python tech insights, with occasional practical development tool tips.
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.