API Response Models
A response wrapper provides a consistent format for all API responses, making it easier for clients to handle success and error cases.
Basic Response Wrapper
public class ApiResponse<T> {
private boolean success;
private String message;
private T data;
private LocalDateTime timestamp;
public static <T> ApiResponse<T> success(T data) {
ApiResponse<T> response = new ApiResponse<>();
response.success = true;
response.message = "Success";
response.data = data;
response.timestamp = LocalDateTime.now();
return response;
}
public static <T> ApiResponse<T> success(String message, T data) {
ApiResponse<T> response = new ApiResponse<>();
response.success = true;
response.message = message;
response.data = data;
response.timestamp = LocalDateTime.now();
return response;
}
public static <T> ApiResponse<T> error(String message) {
ApiResponse<T> response = new ApiResponse<>();
response.success = false;
response.message = message;
response.timestamp = LocalDateTime.now();
return response;
}
// Getters and Setters
}
Usage in Controller
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping("/{id}")
public ResponseEntity<ApiResponse<ProductDto>> getProduct(@PathVariable Long id) {
ProductDto product = productService.getProduct(id);
return ResponseEntity.ok(ApiResponse.success(product));
}
@PostMapping
public ResponseEntity<ApiResponse<ProductDto>> createProduct(
@Valid @RequestBody CreateProductRequest request) {
ProductDto created = productService.createProduct(request);
return ResponseEntity.status(HttpStatus.CREATED)
.body(ApiResponse.success("Product created", created));
}
@DeleteMapping("/{id}")
public ResponseEntity<ApiResponse<Void>> deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
return ResponseEntity.ok(ApiResponse.success("Product deleted", null));
}
}
Paginated Response
public class PagedResponse<T> {
private List<T> content;
private int page;
private int size;
private long totalElements;
private int totalPages;
private boolean first;
private boolean last;
public static <T> PagedResponse<T> of(Page<T> page) {
PagedResponse<T> response = new PagedResponse<>();
response.content = page.getContent();
response.page = page.getNumber();
response.size = page.getSize();
response.totalElements = page.getTotalElements();
response.totalPages = page.getTotalPages();
response.first = page.isFirst();
response.last = page.isLast();
return response;
}
}
Standard JSON Format
// Success
{
"success": true,
"message": "Success",
"data": {
"id": 1,
"name": "Widget",
"price": 29.99
},
"timestamp": "2024-01-15T10:30:00"
}
// Paginated
{
"content": [...],
"page": 0,
"size": 20,
"totalElements": 150,
"totalPages": 8,
"first": true,
"last": false
}
// Error
{
"success": false,
"message": "Validation failed",
"details": ["name: is required", "price: must be positive"],
"timestamp": "2024-01-15T10:30:00"
}
API Best Practices
Design Principles
- Use nouns, not verbs
- Plural resource names
- Consistent naming conventions
- Proper HTTP status codes
Versioning
- URI versioning (/v1/resource)
- Header versioning
- Deprecation policy
Documentation
- OpenAPI/Swagger specs
- Request/Response examples
- Error code documentation
- Rate limit documentation
Key Points
- Understanding API Response Models is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for API Response Models in a backend system. Consider scalability, error handling, and production readiness.
Solution
// API Response Models implementation
// Key aspects: validation, error handling, logging, testing
public class APIResponseModels {
// Production-ready implementation
}Identify and handle edge cases for API Response Models. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for API Response Models. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. Why use a response wrapper class?
2. How do you handle paginated responses in the wrapper?
3. What is the primary purpose of API Response Models?
4. What is a common mistake when implementing API Response Models?
Flashcards
Question
What is an API response wrapper?
Click to reveal answer
Answer
A class providing consistent success/error format for all API responses
Question
What does a paginated response include?
Click to reveal answer
Answer
content, page, size, totalElements, totalPages, first, last
Question
What is API Response Models?
Click to reveal answer
Answer
API Response Models is a key concept in backend development.
Question
When to use API Response Models?
Click to reveal answer
Answer
Use API Response Models when building production systems that require reliability, scalability, and maintainability.
Question
API Response Models best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.Response wrapper provides consistent format (success, message, data, timestamp)
- 2.Use static factory methods: ApiResponse.success(), ApiResponse.error()
- 3.PagedResponse wraps Spring Page for pagination
- 4.Error responses include error code, message, and details
- 5.Consistent responses make client-side handling predictable
Interview Tips
- •Be ready to design a response wrapper class
- •Know how to handle paginated responses
- •Understand why consistency matters in API design
Cheat Sheet
API Response Models
- ApiResponse
: success + message + data + timestamp - PagedResponse
: content + page + size + totalElements - Static Methods: ApiResponse.success(data), ApiResponse.error(msg)
- Error Format: errorCode + message + details + timestamp