RestTemplate and WebClient are the two main options for consuming an external REST API from Spring Boot -- RestTemplate is the classic, blocking client, and WebClient is the modern, non-blocking, reactive client.
Key Points: • RestTemplate is defined as a @Bean and called with methods like getForObject() or exchange(), blocking the calling thread until the response arrives. • WebClient is built with WebClient.builder() and used with a fluent chain: get(), uri(), retrieve(). • WebClient returns Mono (single value) or Flux (stream of values) instead of a raw object, fitting reactive pipelines. • RestTemplate is now in maintenance mode; new code, especially anything performance-sensitive, should prefer WebClient or the newer RestClient. • Both need timeout and error-handling configuration to avoid hanging on a slow or failing downstream service.
Example: Fetching a user profile from an external service with RestTemplate returns a UserDto directly, while the same call with WebClient returns a Mono<UserDto> that you subscribe to or map further downstream.
Code Example:
// RestTemplate
UserDto user = restTemplate.getForObject("/api/users/{id}", UserDto.class, id);
// WebClient
Mono<UserDto> user = webClient.get()
.uri("/api/users/{id}", id)
.retrieve()
.bodyToMono(UserDto.class);Interview Tip: A concise interview answer is:
"For a blocking call I'd define a RestTemplate bean and use getForObject() or exchange(). For a non-blocking, reactive flow I'd use WebClient, chaining get().uri().retrieve() and mapping the result with bodyToMono() or bodyToFlux(). Since RestTemplate is in maintenance mode, I'd default to WebClient for new code."