Backend Development 10 min read

Designing a Unified API Response Structure in Spring Boot with @ResponseResult

This article explains how to standardize API responses in Spring Boot by defining a JSON result format, using custom annotations, interceptors, and ResponseBodyAdvice to automatically wrap controller return values, while also discussing status code design, message handling, and code simplification techniques.

Top Architect
Top Architect
Top Architect
Designing a Unified API Response Structure in Spring Boot with @ResponseResult

In modern micro‑service architectures, front‑end and back‑end systems communicate via HTTP APIs, and a consistent JSON response format simplifies client handling.

Interface Interaction

The front‑end calls a URL with parameters; the back‑end processes the request and returns data.

Return Format

A typical JSON response includes code (integer status), message (string description), and data (object payload).

{
  // return status code
  code: integer,
  // return message description
  message: string,
  // return data
  data: object
}

Standard HTTP status codes (200, 301, 404, 500) can be referenced, and custom ranges such as 1000‑1999 for parameter errors, 2000‑2999 for user errors, and 3000‑3999 for interface exceptions are suggested.

Controller Layer

Controllers handle business requests and return Result objects. The article shows how to simplify this by adding static helper methods to the Result class.

// Example of a simplified controller method
@GetMapping("/order/{id}")
public Result getOrder(@PathVariable Long id) {
    Order order = orderService.findById(id);
    return Result.success(order);
}

Optimization

Issues with the original approach include generic Result return types lacking business meaning, redundant success/failure calls, and manual null checks that could be replaced by validation frameworks.

Implementation Plan

Define a custom annotation @ResponseResult to mark methods whose return values need wrapping.

Create an interceptor that detects the annotation and sets a request attribute.

Implement ResponseBodyAdvice and @ControllerAdvice to wrap the response when the attribute is present, handling both normal results and exceptions.

Annotation Example

// @ResponseResult annotation definition
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ResponseResult { }

Interceptor Example

// Interceptor checks for @ResponseResult
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    if (handler instanceof HandlerMethod) {
        HandlerMethod hm = (HandlerMethod) handler;
        boolean needWrap = hm.getMethodAnnotation(ResponseResult.class) != null ||
                           hm.getBeanType().isAnnotationPresent(ResponseResult.class);
        request.setAttribute("needWrap", needWrap);
    }
    return true;
}

ResponseBodyAdvice Example

// Advice wraps the body into Result when needed
@Around
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                            Class
> selectedConverterType,
                            ServerHttpRequest request, ServerHttpResponse response) {
    Boolean needWrap = (Boolean) ((ServletServerHttpRequest) request).getServletRequest().getAttribute("needWrap");
    if (Boolean.TRUE.equals(needWrap)) {
        if (body instanceof Result) return body;
        return Result.success(body);
    }
    return body;
}

The article concludes that this approach makes API responses concise and elegant, and suggests further optimizations such as caching the annotation lookup.

Overall, the guide provides a practical method for Java back‑end developers to enforce a uniform API contract using Spring Boot.

backendJavaSpring BootAPI designAnnotationsResponse Wrapper
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

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.