Backend Development 6 min read

Standardizing Backend API Responses with a JSON Result Wrapper and Global Interceptor

This article explains how to design a unified JSON response format for backend APIs, define systematic status codes, and implement a Spring @ResponseResult annotation with a global interceptor and ResponseBodyAdvice to automatically wrap controller results, improving consistency and error handling across micro‑service projects.

Architecture Digest
Architecture Digest
Architecture Digest
Standardizing Backend API Responses with a JSON Result Wrapper and Global Interceptor

In modern micro‑service projects with front‑end/back‑end separation, a consistent API response format is essential.

The article proposes using a JSON wrapper with fields code (integer status), message (string description), and data (object) to return results from the backend to the front‑end.

{
  #返回状态码
  code: integer,
  #返回信息描述
  message: string,
  #返回值
  data: object
}

It discusses the drawbacks of ad‑hoc status codes and suggests adopting a range‑based scheme similar to HTTP codes (e.g., 1000‑1999 for parameter errors, 2000‑2999 for user errors, 3000‑3999 for interface exceptions).

200 - 请求成功
301 - 资源(网页等)被永久转移到其它URL
404 - 请求的资源(网页等)不存在
500 - 内部服务器错误

The message field should provide a user‑friendly description, while the data field carries the actual business payload, often encapsulated in a Result class.

To avoid repetitive boilerplate, the article introduces a custom @ResponseResult annotation together with a Spring ResponseBodyAdvice implementation that automatically wraps controller return values into the unified Result object.

It also shows how to create a global interceptor that detects the annotation, sets a request attribute, and how the advice rewrites the response, handling both successful results and exceptions.

Finally, the article suggests further refinements such as returning raw business objects when appropriate, caching annotation look‑ups, and extending the pattern for more advanced error handling.

backendJavaSpringJSONAPIInterceptorresponse
Architecture Digest
Written by

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.

0 followers
Reader feedback

How this landed with the community

login 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.