A lightweight, zero-configuration REST API Response wrapper for Spring Boot applications
A lightweight, type-safe API Response wrapper for Spring Boot applications. Standardize your REST API responses with consistent structure, automatic timestamps, distributed tracing support, and clean factory methods. Features zero-configuration Spring Boot auto-configuration, opt-in automatic response wrapping (@AutoResponse), and production-ready exception handling with comprehensive RFC 9457 ProblemDetail support covering 10 common error scenarios. No external dependencies required - uses pure Java with a custom builder pattern.
- π¦ Maven Central Repository
- π JavaDoc Documentation
- π Report Issues
- π‘ Feature Requests
- π€ Contributing Guide
- Quick Links
- Key Highlights
- Features
- Requirements
- What Makes This Different?
- Installation
- Project Structure
- Quick Start
- Auto-Configuration
- Opt-in Automatic Wrapping (@AutoResponse)
- Built-in Security Features
- Built-in Exception Handling
- Usage
- Real-World Examples
- API Reference
- Response Structure
- Best Practices
- Testing
- Architecture & Design
- OpenAPI/Swagger Integration
- Compatibility Matrix
- Troubleshooting
- FAQ
- Performance & Best Practices
- Migration Guide
- Security Considerations
- Contributing
- License
- Contact
- Acknowledgments
- Version History
- π Truly Zero Configuration - Spring Boot 3.x/4.x auto-configuration with META-INF imports
- π Zero Boilerplate - Opt-in
@AutoResponseto automatically wrap raw return types (Class or Method level) - π― Production-Ready - Built-in RFC 9457 ProblemDetail with 10 comprehensive exception handlers
- π‘οΈ Complete Error Coverage - Handles validation, JSON parsing, 404s, method mismatches, media types, and more
- π Trace IDs in Errors - Error responses include traceId for debugging
- π Type-Safe & Immutable - Thread-safe design with generic type support
- π¦ Ultra-Lightweight - Only ~10KB JAR size with provided dependencies
- π Microservices-Ready - Built-in trace IDs for distributed tracing
- β Battle-Tested - Used in production Spring Boot applications
- π Professional-Grade Javadoc - 100% coverage with comprehensive method documentation
- π Opt-in Security Features - Fine-grained control with field and class-level annotations
- π« Zero External Dependencies - Pure Java, no Lombok required
- π― Consistent Structure - All responses follow the same format:
status,message,content,timestamp - π @AutoResponse Wrapping - Return plain DTOs; let the library wrap them automatically (Opt-in)
- π Type-Safe - Full generic type support with compile-time type checking
- π Distributed Tracing - Trace IDs in error responses with MDC integration for request tracking
- β° Auto Timestamps - Automatic RFC 3339 UTC formatted timestamps on every response
- π Factory Methods - Clean static methods:
success(),created(),status() - π Zero Config - Spring Boot Auto-Configuration for instant setup
- πͺΆ Lightweight - Only ~10KB JAR with single provided dependency (Spring Web)
- π¦ Immutable - Thread-safe with final fields
- π Spring Native - Built on
ResponseEntityandHttpStatus - π RFC 9457 Compliance - Standard ProblemDetail format (supersedes RFC 7807)
- π Complete JavaDoc - Every class and method fully documented with comprehensive examples
- π Opt-in Security Features - Fine-grained JSON request protection via field and class-level annotations
- β Strict JSON Validation - Rejects unknown properties to prevent mass assignment attacks (automatic)
- β
XSS Prevention - HTML tag detection and rejection via
@XssCheckannotation (opt-in) - β
Smart String Trimming - Whitespace trimming via
@AutoTrimannotation (opt-in) - β Case-Insensitive Enums - Flexible enum handling for better API usability (automatic)
- π‘οΈ Comprehensive Exception Handling - 10 built-in handlers covering all common scenarios
- Java 17 or higher
- Spring Boot 3.2.0 or higher (tested up to 4.0.3)
- No additional dependencies required (pure Java implementation)
Unlike other response wrapper libraries, this one offers:
- β Native Spring Boot 3.x/4.x Auto-Configuration - No manual setup required
- β Zero-Boilerplate @AutoResponse - Return raw objects, let the library wrap them automatically while preserving your HTTP Status codes. Supports both Class-level and Method-level granularity.
- β
Intelligent String Handling - Safely wraps raw
Stringreturns into JSON without throwingClassCastException. - β RFC 9457 ProblemDetail Support - Industry-standard error responses (latest RFC)
- β
Opt-in Security Features - Fine-grained control via field and class-level annotations (
@XssCheck,@AutoTrim) - β Zero External Dependencies - Pure Java implementation, won't conflict with your application
- β Extensible Exception Handling - Create custom business exceptions easily
- β Trace ID Support - Built-in distributed tracing capabilities
- β Professional-Grade Documentation - 100% Javadoc coverage
<dependency>
<groupId>io.github.og4dev</groupId>
<artifactId>og4dev-spring-response</artifactId>
<version>1.4.0</version>
</dependency>
implementation 'io.github.og4dev:og4dev-spring-response:1.4.0'
implementation("io.github.og4dev:og4dev-spring-response:1.4.0")
The library is organized into six main packages:
io.github.og4dev
βββ advice/
β βββ GlobalResponseWrapper.java # Automatic response wrapper interceptor
βββ annotation/
β βββ AutoResponse.java # Opt-in annotation for automatic wrapping
β βββ AutoTrim.java # Opt-in annotation for string trimming
β βββ XssCheck.java # Opt-in annotation for XSS validation
βββ config/
β βββ ApiResponseAutoConfiguration.java # Spring Boot auto-configuration
βββ dto/
β βββ ApiResponse.java # Generic response wrapper
βββ exception/
β βββ ApiException.java # Abstract base for custom exceptions
β βββ GlobalExceptionHandler.java # RFC 9457 exception handler
βββ filter/
βββ TraceIdFilter.java # Request trace ID generation
You can use the library in two ways: Explicit Factory Methods or Automatic Wrapping.
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public ResponseEntity<ApiResponse<User>> getUser(@PathVariable Long id) {
User user = userService.findById(id);
return ApiResponse.success("User retrieved successfully", user);
}
}Tired of typing ResponseEntity<ApiResponse<T>>? Use @AutoResponse! You can apply it to the whole class, or just specific methods.
@RestController
@RequestMapping("/api/users")
// @AutoResponse // Uncomment this to apply to ALL methods in the controller
public class UserController {
@AutoResponse // Applied ONLY to this specific method
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
// Just return the raw object!
return userService.findById(id);
}
@AutoResponse
@PostMapping
@ResponseStatus(HttpStatus.CREATED) // Preserves custom status codes!
public User createUser(@RequestBody UserDto dto) {
return userService.create(dto);
}
@AutoResponse
@GetMapping("/greeting")
public String greeting() {
// Raw strings are safely converted to JSON ApiResponse too!
return "Hello World";
}
}Both methods produce the exact same JSON:
{
"status": 200,
// or 201 for POST
"message": "Success",
"content": {
"id": 1,
"name": "John Doe"
},
"timestamp": "2026-02-28T10:30:45.123Z"
}
The library features Spring Boot Auto-Configuration for truly zero-config setup!
β
GlobalExceptionHandler - Automatic exception handling
β
GlobalResponseWrapper - Automatic payload wrapping via @AutoResponse
β
Security Customizers - Jackson configuration for @AutoTrim and @XssCheck
No configuration needed! Just add the dependency.
Introduced in v1.4.0, you can eliminate boilerplate code by letting the library wrap your controller responses automatically.
- Class Level (
@Target(ElementType.TYPE)): Apply@AutoResponseto your controller class to automatically wrap all endpoint responses within it. - Method Level (
@Target(ElementType.METHOD)): Apply@AutoResponseto specific request mapping methods for fine-grained, opt-in control over exactly which endpoints get wrapped.
- β
Status Code Preservation: Intelligently reads custom HTTP status codes set via
@ResponseStatus(e.g., 201 Created) and reflects them in theApiResponse. - β
Double-Wrap Prevention: Safely skips wrapping if you explicitly return an
ApiResponseorResponseEntity. - β
Error Compatibility: Bypasses
ProblemDetailresponses, ensuring standard error handling is never broken. - β
Intelligent String Handling: Uses the injected
ObjectMapperto serialize rawStringreturns into JSON format safely, preventingClassCastExceptionconflicts with Spring's nativeStringHttpMessageConverter.
The library provides fine-grained security and data processing features through field-level annotations. By default, fields are NOT modified unless explicitly annotated.
New in v1.4.0: You can now apply @AutoTrim and @XssCheck to entire classes to protect all string fields at once!
Rejects JSON payloads containing unexpected fields to prevent mass assignment attacks.
Fail-fast HTML tag detection and rejection using regex pattern (?s).*<\s*[a-zA-Z/!].*.
@XssCheck
private String comment; // Rejects "<script>alert(1)</script>"Automatic whitespace removal for specific fields.
@AutoTrim
private String username; // " john_doe " -> "john_doe"Apply annotations to the class level to automatically protect ALL string fields within that class!
@AutoTrim
@XssCheck
public class SecureRegistrationDTO {
// Both of these fields will be automatically trimmed and XSS-validated!
private String username;
private String email;
private String bio;
}(See full Security details in the Javadocs and examples above).
The library includes a **production-ready GlobalExceptionHandler** that automatically handles 10 common exceptions using Spring Boot's ProblemDetail (RFC 9457) standard.
- Automatic Logging: SLF4J integration for all errors.
- Trace ID Consistency: Logs and responses always have matching trace IDs.
- Custom Business Exceptions: Extend the abstract
ApiExceptionclass to create domain-specific exceptions.
public class ResourceNotFoundException extends ApiException {
public ResourceNotFoundException(String resource, Long id) {
super(String.format("%s not found with ID: %d", resource, id), HttpStatus.NOT_FOUND);
}
}@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
@AutoResponse // β¨ Zero boilerplate for the whole controller!
public class ProductController {
private final ProductService productService;
@GetMapping
public Page<Product> getAllProducts(Pageable pageable) {
return productService.findAll(pageable);
}
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
return productService.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product", id));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED) // β¨ 201 Created preserved automatically
public Product createProduct(@Valid @RequestBody ProductDto dto) {
return productService.create(dto);
}
@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable Long id) {
productService.delete(id);
// Returns empty content with 200 OK automatically
}
}(Refer to Javadoc for full details)
β¨ New Features & Improvements:
-
@AutoResponse Annotation & GlobalResponseWrapper
-
Opt-in automatic response wrapping to eliminate boilerplate code.
-
Improved Granularity: Fully supports both Class-level (
ElementType.TYPE) and Method-level (ElementType.METHOD) placement for precision control over which endpoints are wrapped. -
Returns raw DTOs from controllers and automatically wraps them in
ApiResponse<T>. -
Preserves HTTP status codes from
@ResponseStatus. -
Intelligently skips
ResponseEntity,ApiResponse, andProblemDetailto prevent double-wrapping. -
Intelligent String Handling: Uses Spring's
ObjectMapperto safely serialize rawStringreturns to JSON, avoidingClassCastExceptionwith native converters. -
Class-Level Security Annotations
-
@AutoTrimand@XssCheckcan now be applied at the Class level (ElementType.TYPE) to automatically protect all String fields within the DTO at once. -
Documentation
-
package-info.javadocumentation added for the newadvicepackage.
- Security Philosophy Change: Complete redesign from automatic to opt-in approach for JSON sanitization.
- Added @AutoTrim annotation for explicit string trimming.
- Added @XssCheck annotation for explicit fail-fast XSS validation.
- Extensive Javadoc and README updates regarding the new security model.
- Added
@NoTrimannotation (Legacy - removed in 1.3.0 in favor of opt-in model). - Enhanced Advanced String Deserializer.
- Added
GlobalExceptionHandlerand RFC 9457 Support. - Added
TraceIdFilterand MDC Integration. - Verified Spring Boot 4.0.3 Compatibility.
- Initial Release. Core
ApiResponsewrapper.
We welcome contributions! Please see the Contributing section above for details on our Apache 2.0 license terms and PR process.
Licensed under the Apache License 2.0.
Pasindu OG | pasinduogdev@gmail.com | GitHub: @pasinduog
β If you find this library helpful, please give it a star on GitHub!