Sub topic 8
Base URL, default headers, and authentication
This chapter assumes you can already build a TodoClient proxy with HttpServiceProxyFactory and expose it as a bean. Here you configure what every request from that client shares: the host, common headers, and credentials.
Where the configuration lives
An @HttpExchange interface describes paths, methods, and arguments. It does not know the host, and it should not know secrets. Those belong to the RestClient under the proxy. Every call the proxy makes goes through that client, so anything you set on it applies to all methods of the interface.
Base URL
Call baseUrl on the builder. The path in @HttpExchange("/todos") and in each method is appended to it.
RestClient restClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.build();With this setting, @GetExchange("/{id}") on a type annotated @HttpExchange("/todos") requests https://jsonplaceholder.typicode.com/todos/1. Keep the host out of the annotations so the same interface works against test, staging, and production.
Default headers
Use defaultHeader for values that never change per call, such as an API version or an Accept type. Use defaultHeaders when you need the HttpHeaders helper methods.
RestClient restClient = builder
.baseUrl("https://api.example.com")
.defaultHeader("X-Api-Version", "2")
.defaultHeaders(headers -> headers.setBasicAuth("svc-user", "svc-password"))
.build();For values that differ per call, declare a parameter on the interface instead:
@GetExchange("/{id}")
Todo getTodo(@PathVariable long id, @RequestHeader("X-Request-Id") String requestId);Authentication with a request interceptor
A static header is fine for a fixed API key or basic credentials. Tokens that expire need a value read at request time, so use a ClientHttpRequestInterceptor. It runs for every request the client sends.
import java.util.function.Supplier;
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 SecureTodoClientConfig {
@Bean
Supplier<String> todoTokenSupplier() {
// Replace with a real token source, such as a cached OAuth2 token.
return () -> System.getenv("TODO_API_TOKEN");
}
@Bean
TodoClient todoClient(RestClient.Builder builder, Supplier<String> todoTokenSupplier) {
RestClient restClient = builder
.baseUrl("https://api.example.com")
.defaultHeader("X-Api-Version", "2")
.requestInterceptor((request, body, execution) -> {
request.getHeaders().setBearerAuth(todoTokenSupplier.get());
return execution.execute(request, body);
})
.build();
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build()
.createClient(TodoClient.class);
}
}The interceptor sets Authorization: Bearer <token> on each request. Because the supplier is called every time, a refreshed token is picked up without rebuilding the client.
Setting the base URL from properties
On Spring Framework 7 and Spring Boot 4, clients registered with @ImportHttpServices take their base URL from configuration, so the builder code above is not needed for it:
spring.http.serviceclient.todos.base-url=https://jsonplaceholder.typicode.comOn earlier versions, inject the value yourself with @Value("${todos.base-url}") and pass it to baseUrl.
Common mistakes
- Putting the host in
@HttpExchange. The interface then cannot be pointed at another environment. - Hard-coding secrets in the configuration class. Read them from environment variables, a vault, or externalized properties.
- Setting a bearer token once in
defaultHeader. It keeps being sent after it expires. Use an interceptor. - Sharing one builder instance across clients. Boot's auto-configured
RestClient.Builderis prototype-scoped, so each injection gets a fresh one. Do not reuse a single builder for clients with different base URLs or credentials.
Exercise
A client calls an API whose access token expires every 15 minutes. Why is defaultHeader("Authorization", "Bearer " + token) the wrong choice, and what should you use?
Show answer
defaultHeader stores the value once, when the client is built, so the client keeps sending the expired token after 15 minutes. Register a ClientHttpRequestInterceptor that calls a token supplier on every request and sets the header with setBearerAuth.