Sub topic 1
From hand-written calls to an interface
Most services call other HTTP services. Spring lets you describe such a call as a Java interface and generates the implementation for you. This chapter shows the problem that idea solves, the shape of the solution, and what happens at runtime when you call an interface method. Later chapters cover each part in detail.
Prerequisites
This chapter assumes you already know:
- Java 17 or later, including records and interfaces.
- Basic Spring Boot: beans,
@Configuration, and dependency injection. - HTTP fundamentals: methods, status codes, headers, and JSON bodies.
- Spring MVC annotations such as
@PathVariableand@RequestParam.
The examples need Spring Framework 6.1 or later (Spring Boot 3.2 or later), because they use RestClient. Spring Framework 6.0 introduced HTTP interfaces, but the RestClient adapter used here arrived in 6.1.
The problem with hand-written calls
Suppose your service needs to read todo items from a remote API. With RestClient, you could write this:
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
@Component
class TodoGateway {
private final RestClient restClient = RestClient.builder()
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
Todo getTodo(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.body(Todo.class);
}
}
record Todo(Long id, Long userId, String title, boolean completed) {}This works. The cost shows up as the client grows. Each remote operation needs its own chain of get(), uri(...), retrieve(), and body(...). Most of that chain is mechanical and says little about what the call means. A remote API with fifteen endpoints produces fifteen of these chains. They are easy to get subtly wrong. For example, a hand-built URL can drop a path variable, a query parameter name can contain a typo, or the wrong type can be passed to body(...).
The code also mixes two concerns:
- What the remote API offers: the HTTP method, the path, the parameters, and the result type.
- How the call is made: the HTTP library, the serialization, and the error handling.
When both live in the same method, you can't read the API's shape at a glance, and you can't swap out the transport without rewriting every method.
The declarative idea
A declarative client separates those two concerns. You write down what the API offers as an interface. Spring supplies how the call is made.
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);
}The interface has no method bodies and no HTTP library imports. Each method is a contract: "calling this method means sending this request and converting the response into this type." This style is called an HTTP interface or HTTP service client.
If you have written Spring MVC controllers, the annotations will look familiar. A controller uses @GetMapping and @PathVariable to say how incoming requests map to methods. An HTTP interface uses @GetExchange and the same @PathVariable to say how method calls map to outgoing requests. The server side and client side read almost the same way.
What happens when you call the method
An interface has no behavior of its own, so something must implement it. At startup, Spring creates a proxy: an object generated at runtime that implements your interface and forwards each method call to other code. A class called HttpServiceProxyFactory builds the proxy.
When you call todoClient.getTodo(1), the proxy does the following:
- Looks up the metadata for the method. It reads the annotations on the interface and method once, then reuses the result.
- Builds a request from the metadata and the arguments. Here that is
GET /todos/1. - Hands the request to an adapter, a thin wrapper around a real HTTP client. For this tutorial that client is
RestClient. - Converts the response body into the declared return type,
Todo.
Your service never sees steps 2 to 4. It sees only a method that takes a long and returns a Todo.
Wiring it up, in brief
Something has to create the proxy and register it as a bean. The next chapters explain this wiring, so treat the following as a preview:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
@Configuration
class TodoClientConfig {
@Bean
TodoClient todoClient(RestClient.Builder builder) {
RestClient restClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
HttpServiceProxyFactory factory = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build();
return factory.createClient(TodoClient.class);
}
}After this, any component can inject TodoClient like any other bean:
import org.springframework.stereotype.Service;
@Service
class TodoService {
private final TodoClient todoClient;
TodoService(TodoClient todoClient) {
this.todoClient = todoClient;
}
String titleOf(long id) {
return todoClient.getTodo(id).title();
}
}The TodoService depends only on the interface. In a unit test you can replace it with a mock, or with a real proxy pointed at a fake server.
What you gain and what you give up
The declarative style is not free. It trades some flexibility for clarity.
| Aspect | Hand-written `RestClient` calls | HTTP interface |
|---|---|---|
| Readability of the API shape | Spread across method bodies | One interface lists every operation |
| Boilerplate per endpoint | A full call chain | One annotated method |
| Swapping the transport | Rewrite every call | Change the adapter |
| Unusual requests | Full control at the call site | Limited to what the annotations express |
| Debugging | Call chain is visible in your code | Behavior lives inside the generated proxy |
Hand-written calls remain the right tool for one-off requests or for requests that need logic the annotations can't express. HTTP interfaces suit stable APIs with many endpoints, where the interface acts as documentation. A later chapter compares the options, including WebClient and OpenFeign.
Common mistakes at this stage
- Forgetting to register the proxy. An interface alone is not a bean. If injection fails with a "no qualifying bean" error, the proxy was never created.
- Using
@GetMappinginstead of@GetExchange. The proxy factory ignores MVC mapping annotations on a client interface. - Compiling parameter names away.
@PathVariable long idwith no explicit name relies on the compiler keeping parameter names. Spring Boot's build plugins enable-parametersby default. A custom build may not, in which case you write@PathVariable("id"). - Expecting compile-time checking of the remote API. The interface records your belief about the API. If the server changes a path or a field name, the compiler can't tell you. Tests against the real or a simulated API can.
- Putting server concerns on the interface. Don't share one interface between a controller and a client. The two sides have different needs, and sharing couples them tightly.
Exercise
A teammate says a declarative client "makes the HTTP calls for you, so the interface is the implementation." Correct this in one or two sentences, naming which object makes the request.
Show answer
The interface only describes the requests. At runtime a proxy generated by HttpServiceProxyFactory implements it, and that proxy passes each call to an adapter around a real HTTP client such as RestClient, which actually sends the request.
Exercise
Given the method below, write the hand-written RestClient chain that produces the same request, assuming a RestClient named restClient with the base URL already set. @GetExchange("/todos") List<Todo> listByUser(@RequestParam long userId);
Show answer
restClient.get().uri(uriBuilder -> uriBuilder.path("/todos").queryParam("userId", userId).build()).retrieve().body(new ParameterizedTypeReference<List<Todo>>() {}); The request is GET /todos?userId=<value>. The ParameterizedTypeReference keeps the generic List<Todo> type, which a plain Todo.class could not express.