Backend Development 7 min read

Designing a Unified API Response Structure with Status Codes, Annotations, and Interceptors in Spring Boot

This article explains how to create a consistent JSON API response format—including custom status codes, message fields, and a Result wrapper—by using a @ResponseResult annotation, an interceptor, and ResponseBodyAdvice in Spring Boot, while also offering tips for optimization and error handling.

Architect
Architect
Architect
Designing a Unified API Response Structure with Status Codes, Annotations, and Interceptors in Spring Boot

In modern micro‑service projects the API layer often returns a unified JSON structure consisting of a status code, a message and a data object.

The article first defines a simple JSON format:

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

It then discusses designing custom status codes, referencing HTTP status ranges and grouping errors (e.g., 1000‑1999 for parameter errors, 2000‑2999 for user errors, 3000‑3999 for interface exceptions).

The Message field is used to give a friendly description of the error.

A Result class is introduced to encapsulate the response, with static helper methods such as Result.success(...) and Result.failure(...) . The article shows how to simplify controller code by returning the business object directly and letting the wrapper be applied automatically.

To achieve automatic wrapping, a custom annotation @ResponseResult is defined, an interceptor records whether a request needs wrapping, and a ResponseBodyAdvice implementation rewrites the response body into the Result format. The same mechanism can handle exceptions by checking the body type.

Finally, the article suggests further optimizations such as caching annotation look‑ups and emphasizes that the presented approach makes API responses concise, consistent and easier for front‑end developers to interpret.

backend developmentSpring BootAPI designAnnotationsInterceptorsResponse Wrapper
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

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.