Consuming REST APIs

Harry · 11 Sep 2026 · 13 views

Consuming REST APIs

Most applications both provide and consume REST APIs. Spring Boot offers several tools for making HTTP calls to external services.

RestTemplate (Legacy)

RestTemplate has been the standard for years. It still works but is no longer recommended for new code.

RestTemplate restTemplate = new RestTemplate();

// GET
Product product = restTemplate.getForObject(
    "http://api.example.com/products/42", Product.class);

// POST
Product newProduct = restTemplate.postForObject(
    "http://api.example.com/products",
    productToCreate,
    Product.class);

WebClient (Recommended)

WebClient is the modern reactive alternative. It supports both blocking and non-blocking usage.

WebClient client = WebClient.builder()
    .baseUrl("http://api.example.com")
    .defaultHeader("Accept", "application/json")
    .build();

// Blocking GET
Product product = client.get()
    .uri("/products/{id}", 42)
    .retrieve()
    .bodyToMono(Product.class)
    .block();

// POST with JSON body
Product created = client.post()
    .uri("/products")
    .contentType(MediaType.APPLICATION_JSON)
    .bodyValue(newProduct)
    .retrieve()
    .bodyToMono(Product.class)
    .block();

RestClient (Spring 6.1+)

RestClient is a simpler synchronous alternative introduced in Spring 6.1. It offers a fluent API without reactive complexity:

RestClient client = RestClient.create("http://api.example.com");

Product product = client.get()
    .uri("/products/{id}", 42)
    .retrieve()
    .body(Product.class);

Error Handling

Always handle HTTP errors. WebClient provides onStatus() for custom error handling. Check status codes and throw meaningful exceptions.

WebResponseErrorHandler errorHandler = new WebResponseErrorHandler() {
    @Override
    public boolean hasError(ClientHttpResponse resp) throws IOException {
        return resp.getStatusCode().isError();
    }
    @Override
    public void handleError(ClientHttpResponse resp) throws IOException {
        throw new ExternalApiException(resp.getStatusCode().value());
    }
};

Key Points

  • RestTemplate is legacy; prefer WebClient or RestClient for new projects.
  • WebClient supports both blocking and non-blocking reactive calls.
  • RestClient offers a simple synchronous fluent API (Spring 6.1+).
  • Always handle error responses from external APIs.
  • Set appropriate headers and timeouts for production use.
Share this post:

Comments (0)

Please login or register to comment.