TExcelTAD
Home › Spring Boot › Calling Other APIs with RestClient

Calling Other APIs with RestClient

Services rarely live alone: your task tracker may need exchange rates, a user directory or a notification service. RestClient, introduced in Spring Framework 6.1, is the modern synchronous HTTP client: a fluent API with the same JSON conversion as your controllers. It replaces the older RestTemplate for new code (which still works but is in maintenance mode).

Creating a client

Spring Boot auto-configures a RestClient.Builder with the same Jackson settings as the rest of your application. Inject it and build a client per remote service:

java
@Configuration
class ClientsConfig {

    @Bean
    RestClient usersClient(RestClient.Builder builder,
                           @Value("${clients.users.base-url}") String baseUrl) {
        return builder
                .baseUrl(baseUrl)
                .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
                .build();
    }
}
properties
clients.users.base-url=https://users.internal.example.com
spring.http.client.connect-timeout=2s
spring.http.client.read-timeout=5s

Note: Always set timeouts. Without them a slow remote service can block your request threads indefinitely and take your own service down with it.

Making requests

java
public record UserDto(long id, String name, String email) {}

@Service
class UserDirectory {
    private final RestClient client;
    UserDirectory(@Qualifier("usersClient") RestClient client) { this.client = client; }

    UserDto find(long id) {
        return client.get()
                .uri("/users/{id}", id)                 // URI template, values are encoded
                .retrieve()
                .body(UserDto.class);                   // JSON -> record
    }

    List<UserDto> search(String name) {
        return client.get()
                .uri(b -> b.path("/users").queryParam("name", name).build())
                .retrieve()
                .body(new ParameterizedTypeReference<List<UserDto>>() {});
    }

    UserDto create(UserDto newUser) {
        return client.post()
                .uri("/users")
                .contentType(MediaType.APPLICATION_JSON)
                .body(newUser)                          // record -> JSON
                .retrieve()
                .body(UserDto.class);
    }
}

The remote service answers like this:

bash · try it yourself
curl -s https://users.internal.example.com/users/42
{"id":42,"name":"Mai Nguyen","email":"mai@example.com","department":"Engineering"}

department is not part of UserDto; Jackson ignores it, so your client keeps working when the remote API adds fields.

Handling errors

retrieve() throws for 4xx and 5xx responses: HttpClientErrorException (e.g. .NotFound) and HttpServerErrorException. You can translate them into your own exceptions:

java
UserDto find(long id) {
    return client.get().uri("/users/{id}", id)
            .retrieve()
            .onStatus(status -> status.value() == 404, (req, res) -> {
                throw new UserNotFoundException(id);
            })
            .body(UserDto.class);
}

For full control over the response (status, headers and body together), use .retrieve().toEntity(UserDto.class) which returns a ResponseEntity<UserDto>.

Resilience: retry with backoff

Network calls fail occasionally. A common pattern is to retry transient failures (timeouts, 503) a few times, waiting longer each time, and never retry client errors such as 404. This plain-Java program models that policy with a fake remote service — no real waiting, the delays are only computed and printed:

java · try it yourself
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;

class RemoteException extends RuntimeException {
    final int status;
    RemoteException(int status) { super("HTTP " + status); this.status = status; }
}

class FakeUsersApi {
    private final Deque<Integer> script;
    FakeUsersApi(List<Integer> statuses) { script = new ArrayDeque<>(statuses); }
    String getUser(long id) {
        int status = script.isEmpty() ? 200 : script.poll();
        if (status != 200) throw new RemoteException(status);
        return "{\"id\":" + id + ",\"name\":\"Mai Nguyen\"}";
    }
}

class Retry {
    static String call(FakeUsersApi api, long id, int maxAttempts) {
        long delayMs = 200;
        for (int attempt = 1; ; attempt++) {
            try {
                String body = api.getUser(id);
                System.out.println("  attempt " + attempt + ": 200 OK");
                return body;
            } catch (RemoteException e) {
                boolean transientError = e.status == 503 || e.status == 504;
                System.out.println("  attempt " + attempt + ": " + e.getMessage()
                        + (transientError ? "" : " (not retryable)"));
                if (!transientError || attempt == maxAttempts) throw e;
                System.out.println("  waiting " + delayMs + " ms");
                delayMs *= 2;
            }
        }
    }
}

class Main {
    public static void main(String[] args) {
        List<List<Integer>> scenarios = List.of(List.of(503, 503), List.of(404), List.of(503, 504, 503));
        for (List<Integer> s : scenarios) {
            System.out.println("Remote answers " + s + " then 200:");
            try {
                System.out.println("  result " + Retry.call(new FakeUsersApi(s), 42, 3));
            } catch (RemoteException e) {
                System.out.println("  gave up: " + e.getMessage());
            }
        }
    }
}
Remote answers [503, 503] then 200:
  attempt 1: HTTP 503
  waiting 200 ms
  attempt 2: HTTP 503
  waiting 400 ms
  attempt 3: 200 OK
  result {"id":42,"name":"Mai Nguyen"}
Remote answers [404] then 200:
  attempt 1: HTTP 404 (not retryable)
  gave up: HTTP 404
Remote answers [503, 504, 503] then 200:
  attempt 1: HTTP 503
  waiting 200 ms
  attempt 2: HTTP 504
  waiting 400 ms
  attempt 3: HTTP 503
  gave up: HTTP 503

In a real project you would use Spring Retry or Resilience4j rather than hand-written loops, but the policy decisions — which errors, how many attempts, what backoff — are exactly these.

Declarative clients with @HttpExchange

For larger remote APIs you can declare an interface and let Spring generate the implementation:

java
@HttpExchange("/users")
interface UsersApi {
    @GetExchange("/{id}")
    UserDto get(@PathVariable long id);

    @PostExchange
    UserDto create(@RequestBody UserDto user);
}

@Bean
UsersApi usersApi(RestClient usersClient) {
    return HttpServiceProxyFactory.builderFor(RestClientAdapter.create(usersClient))
            .build().createClient(UsersApi.class);
}

Comparing Spring's HTTP clients

Client Style Use for
RestClient synchronous, fluent new code in Spring MVC apps
@HttpExchange interfaces declarative many endpoints of one API
WebClient reactive, non-blocking WebFlux applications, streaming
RestTemplate synchronous, template methods existing code only

Tip: With Java 21 virtual threads (spring.threads.virtual.enabled=true), blocking calls with RestClient become cheap, so you rarely need the reactive WebClient just for scalability.

Test yourself

Which client is recommended for new synchronous HTTP calls in Spring Framework 6.1+?

  1. RestTemplate
  2. RestClient
  3. HttpURLConnection
  4. WebClient always

What does retrieve().body(UserDto.class) do when the server answers 404?

  1. Returns null
  2. Returns an empty UserDto
  3. Throws an HttpClientErrorException (NotFound)
  4. Retries automatically

Which failures should a retry policy usually retry?

  1. 400 Bad Request
  2. 404 Not Found
  3. 503 Service Unavailable and timeouts
  4. All errors indefinitely