Skip to content

Call External APIs with WebClient

Interactive Diagram

새 탭 ↗

External API calls need to account for connection delays, response delays, and HTTP errors as well as successful responses. Configure WebClient as a bean and separate configuration from calls that return a single object or a list.

The base project in lab setup includes spring-boot-starter-webflux. This chapter targets Java 17 source and Spring Boot 3.5.16. Replace the illustrative api.example.com address with your API address.

WebClient is a reactive HTTP client that builds a request and executes it on subscription. Mono<T> emits zero or one value, while Flux<T> emits zero or more. Either can terminate with an error signal instead of a value.

Spring MVC can process reactive return values as asynchronous responses. Using WebClient does not turn database calls or other controller code into non-blocking operations.

src/main/resources/application.properties
partner.base-url=https://api.example.com
src/main/java/com/example/tutorial/PartnerClientConfiguration.java
package com.example.tutorial;
import java.time.Duration;
import io.netty.channel.ChannelOption;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
@Configuration
public class PartnerClientConfiguration {
@Bean
public WebClient partnerWebClient(@Value("${partner.base-url}") String baseUrl) {
var httpClient = HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.responseTimeout(Duration.ofSeconds(5));
return WebClient.builder()
.baseUrl(baseUrl)
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
}
}

The 3-second connection timeout limits TCP connection establishment. The 5-second response timeout is the maximum interval between network-level reads while Reactor Netty reads the response, rather than a limit on total request duration. DNS resolution, connection pool acquisition, and the TLS handshake also have their own settings and failure modes.

Keep default certificate validation for HTTPS. If a private CA is used, register the trusted CA through a trust store or equivalent configuration. Do not disable all certificate checks in the shared client. If the API needs a token, define a separate secret injection path and keep the value out of logs.

This code assumes that the external GET /profiles/{id} endpoint returns an object such as {"id":1,"name":"Alex"} and GET /profiles returns a JSON array of those objects.

src/main/java/com/example/tutorial/ProfileClient.java
package com.example.tutorial;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class ProfileClient {
public record Profile(long id, String name) {}
private final WebClient client;
public ProfileClient(@Qualifier("partnerWebClient") WebClient client) {
this.client = client;
}
public Mono<Profile> find(long id) {
return client.get().uri("/profiles/{id}", id).retrieve()
.bodyToMono(Profile.class).timeout(Duration.ofSeconds(8));
}
public Flux<Profile> list() {
return client.get().uri("/profiles").retrieve().bodyToFlux(Profile.class);
}
}

The timeout in find() allows 8 seconds from subscription until the object is received. On expiry it emits an error and cancels the subscription. list() does not use this operator. Applied to a Flux, it can limit the interval between signals rather than the total duration of the list.

By default, retrieve() forwards 4xx and 5xx responses as errors in the WebClientResponseException family. Do not turn failures into empty objects or successful responses. Define any business-specific error distinctions in the calling layer.

src/main/java/com/example/tutorial/ProfileController.java
package com.example.tutorial;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
public class ProfileController {
private final ProfileClient client;
public ProfileController(ProfileClient client) {
this.client = client;
}
@GetMapping("/profiles/{id}")
public Mono<ProfileClient.Profile> find(@PathVariable("id") long id) {
return client.find(id);
}
@GetMapping("/profiles")
public Flux<ProfileClient.Profile> list() {
return client.list();
}
}

Spring MVC subscribes to the returned publisher and continues HTTP response processing. Do not call subscribe() yourself or wait with block() on this path. Define a separate error response contract for translating upstream errors into your service’s HTTP statuses and bodies.

WebClient can help combine multiple external calls or maintain an asynchronous flow. For straightforward synchronous calls, also compare synchronous HTTP clients. Consider concurrency, connection pools, upstream latency, and the application’s threading model together.

This example describes the calling structure; it does not supply a real external service, authentication, or a retry policy. Judge performance using a separate measurement with defined load conditions and comparison targets.