Handling Responses
About
ResponseEntity: The Preferred Wrapper
ResponseEntity<T> {
HttpStatus statusCode;
HttpHeaders headers;
T body;
}ResponseEntity<UserDto> response = restTemplate.getForEntity(
"https://api.example.com/users/{id}",
UserDto.class,
userId
);Mapping Response to Domain Object
Example
Handling JSON Arrays / Lists
Approach 1: Using ResponseEntity<T[]>
ResponseEntity<T[]>Approach 2: Using ParameterizedTypeReference<List<T>>
ParameterizedTypeReference<List<T>>Dynamic Responses (Map or Raw JSON)
Approach 1: Using Map<String, Object>
Map<String, Object>Nested Access Example
Approach 2: Using JsonNode (Jackson Tree Model)
JsonNode (Jackson Tree Model)Status Code Checks
Approach 1: Using ResponseEntity
ResponseEntityExample with switch-style logic
Approach 2: Custom ResponseErrorHandler
ResponseErrorHandlerRegister it with RestTemplate
Extracting & Logging Response Headers
Accessing Headers with ResponseEntity
ResponseEntityIterating Over All Headers
Example: Handling Rate Limit Headers
Accessing Headers in POST, PUT, DELETE Requests
Structured Header Logging
Handling Empty Responses
Typical HTTP Scenarios
Handling with ResponseEntity
ResponseEntityHandling with String.class to Safely Inspect Body
String.class to Safely Inspect BodyUsing ParameterizedTypeReference with Exchange
ParameterizedTypeReference with ExchangeAvoiding HttpMessageNotReadableException
HttpMessageNotReadableExceptionOption 1: Use String.class and parse only if not empty
String.class and parse only if not emptyOption 2: Catch parsing exceptions
Centralized Response Handling Using Utility
Basic Utility Design
Variation for Optional Use Cases
Example Use: Optional Behavior
Deserializing Nested Responses
Common Real-World API Pattern
Approach 1: Wrapper POJO Mapping
Approach 2: Deserialize Using ObjectMapper and Extract Inner Field
ObjectMapper and Extract Inner FieldHandling Lists in Nested Structure
With Generic Wrapper
Advanced Use Case: Pagination with Metadata
Last updated