Sub topic 1
From hand-written calls to an interface
Prerequisites
This chapter assumes you know the following:
- 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 problem with hand-written calls
Most Spring applications call other HTTP services. With RestClient, a call to a todo API looks like this:
import java.util.List;
import org.springframework.web.client.RestClient;
class TodoGateway {
private final RestClient restClient;
TodoGateway(RestClient.Builder builder) {
this.restClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
}
Todo getTodo(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.body(Todo.class);
}
List<Todo> listByUser(long userId) {
return restClient.get()
.uri(uri -> uri.path("/todos").queryParam("userId", userId).build())
.retrieve()
.body(new org.springframework.core.ParameterizedTypeReference<List<Todo>>() {});
}
}
record Todo(Long id, Long userId, String title, boolean completed) {}This works. The cost shows up as the API grows. Every endpoint repeats the same steps: pick the method, build the URI, call retrieve(), and convert the body. The URI strings and the type information sit inside method bodies. The class mixes two concerns: what the remote API looks like, and how to send requests to it.
The declarative idea
A declarative HTTP client separates those concerns. You describe the remote API as a Java interface. Spring generates the implementation at runtime.
The same two operations become:
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);
}There is no method body and no implementation class. The annotations carry the HTTP method and the path. The /todos on the interface is a prefix for every method path. The parameter annotations are the ones you already know from Spring MVC, but here they work in the opposite direction. In a controller they read values from an incoming request. In a client interface they write values into an outgoing request.
The interface can also be read as a contract. A reader sees the whole API surface in one short file, without scanning through request-building code.
How it works
Spring creates a JDK dynamic proxy for the interface. When your code calls todoClient.getTodo(1), the proxy does the following:
- It reads the annotations on the method and its parameters.
- It builds a request: the HTTP method, the URI with
1substituted for{id}, and any headers or body. - It hands the request to an adapter, which sends it with a real HTTP client such as
RestClient. - It converts the response to the declared return type.
The interface does not send anything itself. It only describes. A later chapter shows how to build the proxy with HttpServiceProxyFactory and register it as a bean.
What you gain and what you give up
You gain less repetitive code, one place where the API is described, and a type that is easy to inject and to replace in tests. The annotations reuse Spring MVC vocabulary, so there is little new syntax to learn.
You give up some direct control. Fine-grained request handling, such as custom per-call logic, is less obvious in an interface than in a fluent RestClient chain. The chapters on error handling and defaults cover how to configure those concerns once, at the client level.
Exercise
In a Spring MVC controller, @PathVariable reads a value from the incoming request. What does it do on a parameter of an @HttpExchange interface method?
Show answer
It supplies a value to put into the outgoing request. The argument you pass replaces the matching {name} placeholder in the URI template, for example {id} in @GetExchange("/{id}").