Sub topic 14
When to choose HTTP interfaces over other options
This chapter helps you decide when a declarative HTTP interface is the right tool and when a different client fits better. It assumes you have read the earlier chapters. You should know how @HttpExchange interfaces, HttpServiceProxyFactory, and RestClient fit together. You should also be comfortable with Spring beans and basic HTTP.
The options on the table
A Spring Boot application that calls another HTTP service has four common choices.
- HTTP interface over RestClient. You write an interface annotated with
@HttpExchange. Spring generates the implementation. Calls block the calling thread. - RestClient used directly. You build each request with a fluent API and read the response yourself.
- RestTemplate. This is the older blocking client. It is in maintenance mode, and Spring recommends
RestClientfor new code. - OpenFeign (Spring Cloud OpenFeign). This is a separate declarative client from the Spring Cloud project. It uses its own annotations and its own configuration model.
WebClient is a fifth option. It is the reactive client, and it can also sit under an HTTP interface. That case is covered later in this chapter.
What HTTP interfaces give you
An HTTP interface describes a remote API once, as a Java type. The rest of the application depends on that type, not on HTTP details.
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
@HttpExchange("/todos")
public interface TodoClient {
@GetExchange("/{id}")
Todo getTodo(@PathVariable long id);
@GetExchange
List<Todo> listByUser(@RequestParam long userId);
}
record Todo(Long id, Long userId, String title, boolean completed) {}Compare this with the same two calls written against RestClient.
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.client.RestClient;
class TodoRestClientCalls {
private final RestClient restClient;
TodoRestClientCalls(RestClient restClient) {
this.restClient = restClient;
}
Todo getTodo(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.body(Todo.class);
}
List<Todo> listByUser(long userId) {
return restClient.get()
.uri(uriBuilder -> uriBuilder.path("/todos")
.queryParam("userId", userId)
.build())
.retrieve()
.body(new ParameterizedTypeReference<List<Todo>>() {});
}
}Both versions do the same work. The interface version is shorter, and each method reads like a signature in the API's documentation. The RestClient version shows every step, and you can change any step at any call site.
Here is what you gain from the interface:
- A narrow seam. Services depend on
TodoClient. You can replace it with a mock or stub in a unit test without touching HTTP. - Less repeated code. URI templates, header names, and return types are written once per endpoint.
- A familiar model. The annotations mirror Spring MVC (
@PathVariable,@RequestParam,@RequestBody). Teams that already write controllers read these interfaces quickly. - Transport independence. The same interface can run on
RestClient,WebClient, orRestTemplateby changing the adapter passed toHttpServiceProxyFactory.
What you give up
The interface hides the request. That is the point, and it is also the cost.
- Per-call control is limited. If one call needs a special status handler, a streamed body, or a custom
ClientHttpRequestInterceptor, the interface offers fewer hooks. Many things you can only configure on the client, which applies to every method of that interface. - Errors surface as exceptions. With the default
RestClientbehavior, a 404 becomesHttpClientErrorException.NotFoundthrown from a plain method call. That is fine for many cases. It is awkward when a 404 is a normal outcome that you want to handle without atryblock. ReturningResponseEntity<T>does not prevent the exception under the default handler. It only helps once you register a status handler that suppresses it. - Mistakes appear late. An annotation typo or an unsupported argument type is found when the proxy is created or the method runs. It is not found by the compiler. Cover each client with at least one test.
- Debugging goes through a proxy. Stack traces pass through generated proxy and invoker classes. This is rarely a real problem, but it is one more layer to read past.
When to use each option
HTTP interface over RestClient
Choose this when most of the following hold:
- The remote API is stable and you call a set of well-defined endpoints.
- Each call maps cleanly to one method with simple arguments and a typed result.
- Several services or teams call the same API, and you want one shared description of it.
- You want to mock the client in unit tests with ordinary mocking tools.
This is the default choice for a typical service-to-service integration in a blocking Spring Boot application.
RestClient directly
Choose this when:
- You make one or two calls and an interface would be more ceremony than value.
- The request is built dynamically, for example the path, headers, and body shape all depend on runtime data.
- You need fine control of one request, such as an exchange with access to the raw response, or a streaming body.
- You are exploring an API and the shape of the calls is still changing.
A mixed approach is normal. The same RestClient can back an HTTP interface for the stable endpoints, and you can use it directly for the odd ones.
RestTemplate
Keep RestTemplate in code that already uses it. A rewrite is not required. For new code, prefer RestClient, which has a fluent API and shares the same message converters and request factories. If you have a large RestTemplate codebase, note that an HTTP interface can also run on top of a RestTemplate through RestTemplateAdapter. This allows a gradual move.
OpenFeign
OpenFeign solves the same problem with a different model. Compare the two on the dimensions that matter.
| Aspect | HTTP interface | OpenFeign |
|---|---|---|
| Part of | Spring Framework | Spring Cloud OpenFeign |
| Annotations | `@HttpExchange` and Spring MVC argument annotations | Feign's own, or Spring MVC annotations through a contract |
| Extra dependency | None beyond Spring Web | Spring Cloud and the Feign starter |
| Transport | `RestClient`, `WebClient`, `RestTemplate` | Feign's client (HTTP client of your choice) |
| Reactive support | Yes, through `WebClient` | Not in the standard blocking Feign client |
| Service discovery and load balancing | Configure separately | Integrated with Spring Cloud |
| Retries and circuit breakers | Add separately | Integrated with Spring Cloud tooling |
Choose OpenFeign when you already run Spring Cloud and rely on its load balancing, discovery, and resilience integration, or when a codebase already has many Feign clients. Choose HTTP interfaces when you want a client that comes from the core framework and uses the same RestClient configuration as the rest of your application. Do not migrate working Feign clients only for fashion. Migrate when you want to remove the Spring Cloud dependency or to share one HTTP configuration.
WebClient
If the application is reactive, use an HTTP interface with a WebClient adapter. Methods then return Mono<T> or Flux<T>.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
@Configuration
class ReactiveTodoConfig {
@Bean
ReactiveTodoClient reactiveTodoClient(WebClient.Builder builder) {
WebClient webClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
return HttpServiceProxyFactory
.builderFor(WebClientAdapter.create(webClient))
.build()
.createClient(ReactiveTodoClient.class);
}
}import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import reactor.core.publisher.Mono;
@HttpExchange("/todos")
interface ReactiveTodoClient {
@GetExchange("/{id}")
Mono<Todo> getTodo(@PathVariable long id);
}Do not use a reactive return type in a blocking application only to get WebClient. In a servlet-based application with no other reactive code, RestClient is simpler. Blocking on a Mono with block() in request threads defeats the point of the reactive client.
Failure modes to plan for
Whichever option you pick, remote calls fail. The decision between clients does not remove this work.
- Timeouts. Set connect and read timeouts on the underlying HTTP client. Default timeouts may be infinite or very long, depending on the request factory. An interface does not add timeouts for you.
- Retries. Retrying a non-idempotent call such as a POST can create duplicates. Retry only calls that are safe to repeat.
- Error mapping. Decide whether a 4xx is an exception, a value, or a domain error, and apply that decision in one place. A shared status handler on the client keeps this consistent.
- Version drift. If the remote API changes, the interface compiles but fails at runtime. A contract test or a recorded-response test catches this earlier.
A practical checklist
Use this list when you review a new integration.
- Is the stack blocking or reactive? Reactive points to a
WebClientadapter. - Does the integration already depend on Spring Cloud features? If yes, keep or consider OpenFeign.
- Do the calls map to a small set of typed methods? If yes, use an HTTP interface.
- Do you need to control individual requests in unusual ways? If yes, use
RestClientdirectly for those calls. - Are timeouts, authentication, and error handling set on the client? If not, fix that before shipping.
- Is there at least one test per interface, using
MockRestServiceServeror an equivalent?
Exercise
Your team has a blocking Spring Boot 3 service that calls a partner API at six stable endpoints, and a seventh endpoint that streams a large response and needs custom request handling. Which client approach would you pick, and why?
Show answer
Use an HTTP interface over RestClient for the six stable endpoints, because each maps cleanly to a typed method and the interface gives a narrow seam for testing. Use the same RestClient directly for the streaming endpoint, because it needs per-request control that the interface offers less of. Both share one RestClient configuration for base URL, timeouts, and authentication.
Exercise
A colleague proposes rewriting 40 working OpenFeign clients as HTTP interfaces. The service also uses Spring Cloud load balancing and circuit breakers. What would you ask before agreeing?
Show answer
Ask what problem the rewrite solves. Feign clients are integrated with Spring Cloud load balancing and resilience tooling, and HTTP interfaces would need those wired separately. A migration is justified if the team wants to drop the Spring Cloud dependency or share one RestClient configuration. Otherwise the rewrite adds risk without a clear gain.