Sub topic 10
Declarative clients with HTTP interfaces
This chapter assumes you can build a RestClient with a base URL (see the earlier chapter on creating clients), map JSON to records, and register Spring beans. You also need Java 17 or later and Spring Boot 3.2 or later.
What an HTTP interface is
An HTTP interface is a Java interface whose methods describe calls to a remote API. You annotate the methods, and Spring generates a proxy class that implements them. The proxy builds the request, sends it through a RestClient, and converts the response, so you write no request code.
The idea is the same as a Spring Data repository. You declare what you need, and the framework supplies the implementation.
Declaring the interface
Each method carries an exchange annotation that sets the HTTP method and path. Method parameters supply path variables, query parameters, headers, and the request body.
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.service.annotation.DeleteExchange;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.PostExchange;
record Todo(long id, String title, boolean completed) {}
record NewTodo(String title) {}
interface TodoApi {
@GetExchange("/todos/{id}")
Todo findById(@PathVariable long id);
@GetExchange("/todos")
List<Todo> findAll(@RequestParam(required = false) Boolean completed);
@PostExchange("/todos")
ResponseEntity<Void> create(@RequestBody NewTodo newTodo);
@DeleteExchange("/todos/{id}")
void delete(@PathVariable long id);
}The annotations used above:
| Annotation | HTTP method |
|---|---|
| `@GetExchange` | GET |
| `@PostExchange` | POST |
| `@PutExchange` | PUT |
| `@DeleteExchange` | DELETE |
| `@HttpExchange` | Any method, set with its `method` attribute |
The parameter annotations (@PathVariable, @RequestParam, @RequestBody, @RequestHeader) come from Spring MVC, but here they describe an outgoing request. The return type controls how the response is read. A plain type such as Todo maps the body. ResponseEntity<T> also gives you status and headers. void discards the body.
Creating the proxy
HttpServiceProxyFactory builds the proxy. It talks to the RestClient through a RestClientAdapter. Register the result as a bean so other classes can inject TodoApi.
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 TodoApiConfig {
@Bean
TodoApi todoApi(RestClient.Builder builder) {
RestClient restClient = builder
.baseUrl("https://api.example.com")
.build();
RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
return factory.createClient(TodoApi.class);
}
}The RestClient carries all the configuration you already know: base URL, default headers, timeouts, and interceptors. The interface only declares paths relative to that base URL.
Using the client
Inject the interface like any other bean.
import org.springframework.stereotype.Service;
@Service
class TodoReport {
private final TodoApi todoApi;
TodoReport(TodoApi todoApi) {
this.todoApi = todoApi;
}
String firstTitle() {
return todoApi.findById(1).title();
}
}Errors and behavior you inherit
The proxy delegates to RestClient, so error handling is the same. A 4xx or 5xx response throws a RestClientResponseException unless you registered a status handler on the underlying client. If you want a domain exception, add defaultStatusHandler to the RestClient.Builder before building it, because the interface has no place to attach onStatus per call.
When to choose this style
Use an HTTP interface when you call many endpoints on one API and want the contract in one readable place. It also makes tests simple, because you can mock the interface itself. Use RestClient directly when one call needs custom status handling or access to the raw response.
Exercise
You declared @GetExchange("/todos/{id}") Todo findById(@PathVariable long id); and built the proxy from a RestClient whose base URL is https://api.example.com. Which URL does findById(7) request, and where would you set a read timeout for this call?
Show answer
It requests https://api.example.com/todos/7. The read timeout belongs on the RestClient that the adapter wraps, through its request factory, because the interface only describes paths and parameters.
Exercise
A method returns ResponseEntity<Void>, and the server answers with status 404. What happens, and how can you change it?
Show answer
The proxy throws a RestClientResponseException because RestClient treats 4xx as an error by default. To change it, register a defaultStatusHandler on the RestClient.Builder before creating the adapter.