Sub topic 10
Declarative clients with HTTP interfaces
This chapter assumes you can build a RestClient with a base URL, send GET and POST requests, and map JSON to records. It also assumes you know what @Configuration and @Bean do in Spring Boot. If any of that is unfamiliar, review the chapters on creating a client and reading responses first.
The problem HTTP interfaces solve
A service class that wraps RestClient tends to repeat the same shape. Each method picks a verb, fills in a URI template, calls retrieve(), and asks for a body type. The details differ, but the structure is the same for every endpoint.
An HTTP interface moves that description into an annotated Java interface. You declare what the remote API looks like. Spring generates the implementation at runtime as a proxy. The proxy turns each method call into a request and sends it through a RestClient that you supply.
If you have used Spring Data repositories or Feign, the idea is familiar. You write the contract, and the framework writes the plumbing.
Declaring the interface
The interface below describes one endpoint of the todo API used throughout this tutorial.
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.service.annotation.GetExchange;
interface TodoApi {
@GetExchange("/todos/{id}")
Todo findById(@PathVariable long id);
}@GetExchange marks the method as an HTTP GET. The path is a URI template, and {id} is filled from the argument annotated with @PathVariable. The return type, Todo, is the type the response body is converted to. This is the same conversion that retrieve().body(Todo.class) performs.
The annotations come from the org.springframework.web.service.annotation package. The parameter annotations, such as @PathVariable, are the same ones you use in Spring MVC controllers.
Creating the proxy
The interface is only a description. To get a working object, you pass a RestClient to a factory.
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
TodoApi todoApi(RestClient restClient) {
RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
return factory.createClient(TodoApi.class);
}Three objects take part:
RestClientAdapterwraps yourRestClientso the proxy machinery can use it. The factory does not depend onRestClientdirectly. It depends on an adapter abstraction, which is why the same interfaces can also be backed byWebClient.HttpServiceProxyFactoryreads the annotations on the interface and builds the proxy.createClient(TodoApi.class)returns an object that implementsTodoApi.
Everything you configured on the RestClient still applies to the proxy. That includes the base URL, default headers, request factory, timeouts, and interceptors. The proxy adds no transport settings of its own.
To use it in a Spring Boot application, expose the proxy as a bean:
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 todoRestClient) {
RestClientAdapter adapter = RestClientAdapter.create(todoRestClient);
return HttpServiceProxyFactory.builderFor(adapter)
.build()
.createClient(TodoApi.class);
}
}Other components can now inject TodoApi like any other bean. The todoRestClient parameter is the bean defined in the chapter on creating a client.
How a call flows
Because the proxy delegates to RestClient, errors behave as they do for any RestClient call. A 4xx or 5xx response throws a RestClientResponseException subclass out of the interface method, unless you have registered a default status handler on the client.
More exchange methods
Each HTTP method has a matching annotation: @GetExchange, @PostExchange, @PutExchange, @PatchExchange, @DeleteExchange. A general @HttpExchange annotation also exists, which takes the method as an attribute. You can place @HttpExchange on the interface itself to share a path prefix.
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.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
import org.springframework.web.service.annotation.PutExchange;
record Todo(long id, String title, boolean completed) {}
record NewTodo(String title) {}
@HttpExchange("/todos")
interface FullTodoApi {
@GetExchange
List<Todo> findAll();
@GetExchange
List<Todo> findByCompleted(@RequestParam boolean completed);
@GetExchange("/{id}")
Todo findById(@PathVariable long id);
@GetExchange("/{id}")
ResponseEntity<Todo> findEntityById(@PathVariable long id);
@PostExchange(contentType = "application/json")
ResponseEntity<Void> create(@RequestBody NewTodo newTodo);
@PutExchange("/{id}")
void update(@PathVariable long id, @RequestBody Todo todo);
@DeleteExchange("/{id}")
void delete(@PathVariable long id);
}The type-level @HttpExchange("/todos") is a prefix. A method-level path such as "/{id}" is appended to it. A method annotation with no path, such as the bare @GetExchange on findAll, uses the prefix alone.
Return types
The return type tells the proxy how much of the response you want.
| Return type | What you get |
|---|---|
| `void` | Nothing. The response body is discarded. |
| A class or record, such as `Todo` | The body converted to that type. |
| `List<Todo>` | The body converted to a generic collection. The proxy keeps the generic type information, so you do not need `ParameterizedTypeReference`. |
| `ResponseEntity<Todo>` | Status, headers, and the converted body. |
| `ResponseEntity<Void>` | Status and headers only. |
| `HttpHeaders` | The response headers only. |
Declaring List<Todo> as a method return type works without extra code because the proxy reads the generic signature from the method.
Parameters
The proxy supports these parameter annotations, among others:
@PathVariablefills a{name}placeholder in the path. If the parameter name differs from the placeholder, give the name explicitly:@PathVariable("id") long todoId.@RequestParamadds a query parameter. AMapor multi-value map adds several at once.@RequestBodyserializes the argument as the request body.@RequestHeaderadds a request header.
Without a name, @PathVariable and @RequestParam rely on the parameter name being available at runtime. Spring Boot's Maven and Gradle plugins compile with the -parameters flag by default, so this usually works. If you compile without it, you see errors about missing names. Fix that by enabling -parameters or by writing the name in each annotation.
Common errors
The failures in this area come from a small set of causes.
- The interface method is not annotated. A method without an exchange annotation cannot be turned into a request. The factory rejects it when you call
createClient, so the failure appears at startup instead of on the first call. - A placeholder has no matching argument. If the path contains
{id}and no parameter suppliesid, the call fails when the URI is expanded. - No base URL on the client. The annotation paths are relative. If the
RestClienthas nobaseUrl, a path like/todos/1is not a valid absolute URI. Set the base URL on the client, not in each annotation. - Expecting a 404 to return null. A missing resource throws an exception, as it does with
RestClient. ReturnResponseEntity<Todo>only if you also configure the client to stop throwing on 4xx. A plainResponseEntityreturn type does not change the default error behavior. - Putting transport settings on the interface. Timeouts, interceptors, and authentication belong on the
RestClient. The interface cannot express them.
Choosing between an interface and direct calls
An HTTP interface is a good fit when the remote API has many similar endpoints and the calls are plain: a path, a few parameters, a body, a typed result. The contract is short and readable, and the interface is easy to fake in unit tests because it is an ordinary Java interface. A test double only has to implement it.
Direct RestClient calls remain the better choice in other cases:
- You need per-call error handling that differs between endpoints.
- You need
exchange()to read the response in a custom way. - You build the URI dynamically in ways that templates do not describe.
- The remote API has only one or two endpoints, and an interface adds more ceremony than it saves.
The two styles mix well. A single RestClient can back an HTTP interface for the routine calls, and you can still inject the same RestClient into a class that needs low-level control.
Testing an interface-backed client
Since the proxy sits on top of a RestClient, the technique from the testing chapter applies unchanged. Bind MockRestServiceServer to the builder, build the client, and then create the proxy from it.
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
void proxyReturnsTodo() {
RestClient.Builder builder = RestClient.builder().baseUrl("https://api.example.com");
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
RestClient client = builder.build();
TodoApi api = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(client))
.build()
.createClient(TodoApi.class);
server.expect(requestTo("https://api.example.com/todos/1"))
.andRespond(withSuccess(
"{\"id\":1,\"title\":\"Write docs\",\"completed\":false}",
MediaType.APPLICATION_JSON));
Todo todo = api.findById(1);
server.verify();
}The test checks that the annotations produce the URL you expect and that the JSON maps to the record. No network is involved.
Exercise
A teammate defines interface OrderApi with @GetExchange("/orders/{id}") Order find(@PathVariable long id). The proxy is built from a RestClient that has no base URL. The remote server returns 404 for an unknown order. What goes wrong in each case, and where should you fix it?
Show answer
Without a base URL, the relative path /orders/{id} does not form an absolute URI, so the call fails before any request is sent. Fix this by calling baseUrl(...) on the RestClient builder, not by changing the annotation. For the 404, the proxy delegates to RestClient, so by default it throws a RestClientResponseException subclass (a not-found exception) instead of returning null. If you want a domain exception or a normal "absent" result, register an onStatus handler (or a default status handler) on the RestClient, so the policy applies to every method on the interface.
Exercise
Write an @HttpExchange interface method that lists todos filtered by a completed query parameter and returns them as a List<Todo>, with the interface prefix /todos. Why is no ParameterizedTypeReference needed?
Show answer
Declare @HttpExchange("/todos") on the interface and add @GetExchange List<Todo> findByCompleted(@RequestParam boolean completed);. The proxy reads the generic return type from the method signature, so it already knows the element type is Todo. ParameterizedTypeReference is only needed when you call body(...) directly on RestClient, where the generic type is otherwise erased.