Designing a Unified API Response Format for Java Backend Services

This article explains how to create a consistent JSON response structure for Java backend APIs, covering status‑code conventions, a Result wrapper class, static helper methods, a custom @ResponseResult annotation, response‑body advice, and tips for simplifying controller code and handling exceptions.

Top Architect
Top Architect
Top Architect
Designing a Unified API Response Format for Java Backend Services

In modern microservice architectures where front‑end and back‑end are separated, a unified API response format is crucial for clear communication between client and server.

The author proposes a JSON response body that includes three fields: { code: integer, message: string, data: object }. To keep status codes organized, they suggest using ranges similar to HTTP codes (e.g., 1000‑1999 for parameter errors, 2000‑2999 for user errors, 3000‑3999 for interface exceptions) and optionally extending to four‑digit codes.

A Result wrapper class is introduced with static methods such as Result.success() and Result.failure() to simplify controller return values, reducing boilerplate and improving readability.

To automate response wrapping, a custom @ResponseResult annotation is defined. A ResponseBodyAdvice implementation together with @ControllerAdvice intercepts annotated methods, checks the annotation at runtime, and wraps the original return value into the unified Result structure. The same mechanism can handle exceptions by detecting error objects and converting them to the standard format.

The article also notes further optimizations, such as caching annotation lookups to avoid repeated reflection and considering returning raw business objects when appropriate.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javaspringapi-designannotationsresponse-format
Top Architect
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.