Sub topic 8
Base URL, default headers, and authentication
This chapter assumes you have already built a client interface with @HttpExchange and created its proxy with HttpServiceProxyFactory and a RestClient, as covered earlier in the tutorial. You should also be comfortable with @Configuration classes and @Value property injection.
An @HttpExchange interface describes what a call looks like: the HTTP method, the path, and the arguments. It says nothing about which server to call or who you are. That information belongs to the RestClient underneath the proxy. This chapter covers the three things you will configure on it in almost every real project: the base URL, headers sent on every request, and credentials.
Where each setting lives
The interface and the RestClient have separate jobs. If you put a setting in the wrong place, you either hard-code environment details into an interface or repeat yourself on every method.
| Setting | Belongs on | Mechanism |
|---|---|---|
| Path prefix such as `/todos` | The interface | `@HttpExchange("/todos")` |
| Scheme, host, port, API version prefix | The `RestClient` | `builder.baseUrl(...)` |
| Header sent on every call (API key, `Accept`) | The `RestClient` | `defaultHeader(...)`, `defaultHeaders(...)` |
| Header that changes per call (trace id, `If-Match`) | The method | `@RequestHeader` argument |
| Credential that changes over time (OAuth token) | The `RestClient` | A request interceptor |
Base URL
Call baseUrl on the builder. Every relative path from the interface is resolved against it.
RestClient restClient = builder
.baseUrl("https://api.example.com/v2")
.build();With this base URL and @HttpExchange("/invoices") on the interface plus @GetExchange("/{id}") on a method, the request goes to https://api.example.com/v2/invoices/42. The base URL's own path (/v2) is kept, and the interface paths are appended to it.
Some points to keep in mind:
- Do not put the host in the annotation.
@HttpExchange("https://api.example.com/invoices")works, but it fixes the environment into the code and makes testing and staging setups harder. - Read the base URL from configuration. A property such as
billing.base-urllets you point the same code at a sandbox, a staging server, or a mock server. - A method can declare a
java.net.URIargument. When you pass one, it replaces the whole URL, including the base URL. This is useful for following pagination links returned by an API, but it also means that argument bypasses your base-URL configuration. - Keep the slash convention consistent. Start every annotation path with
/and leave the trailing slash off the base URL. This avoids doubled or missing slashes.
Default headers
Headers that apply to every call go on the builder:
RestClient restClient = builder
.baseUrl(baseUrl)
.defaultHeader("X-Api-Key", apiKey)
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.build();defaultHeader(name, values...) sets one header. defaultHeaders(Consumer<HttpHeaders>) gives you the HttpHeaders object, which is convenient when you want helpers such as setBasicAuth or several headers at once. defaultRequest(...) is the most general option: it receives each request spec and can change anything on it, not just headers.
For content negotiation you often do not need a default header at all. @HttpExchange has accept and contentType attributes, so you can declare them on the interface and keep the RestClient generic:
@HttpExchange(url = "/invoices", accept = "application/json")
interface InvoiceApi {
// ...
}Per-call headers
When a value changes from call to call, make it an argument:
@GetExchange("/{id}")
Invoice get(@PathVariable long id,
@RequestHeader("X-Request-Id") String requestId);If an argument is annotated @RequestHeader and its value is null, whether the call fails depends on the required attribute. Mark optional headers with @RequestHeader(name = "...", required = false).
Avoid declaring the same header twice
In current Spring versions, per-call headers are added to the request after the defaults, and adding a header does not replace an existing value of the same name. If you set Accept as a default and also pass it with @RequestHeader, the request may carry both values. Choose one place for each header name. Interceptors are different: they work directly on the outgoing HttpHeaders, so set replaces any earlier value. That is why interceptors suit Authorization.
Authentication
How you attach credentials depends on how often they change.
Static credentials: API keys and Basic auth
A key or a fixed username and password never changes while the application runs, so a default header is enough. HttpHeaders has helpers that format the value correctly:
RestClient restClient = builder
.baseUrl(baseUrl)
.defaultHeaders(h -> h.setBasicAuth(username, password))
.build();For a fixed bearer token, use h.setBearerAuth(token) the same way.
Rotating credentials: a request interceptor
OAuth access tokens expire. If you copy the token into a default header when the bean is created, the client keeps sending the old value after it expires. Instead, register a ClientHttpRequestInterceptor that asks a supplier for the current token on every request.
The configuration below shows an API key and a rotating token together. The interface is a small invoice client.
import java.util.function.Supplier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
@HttpExchange("/invoices")
interface BillingClient {
@GetExchange("/{id}")
Invoice getInvoice(@PathVariable long id);
}
record Invoice(Long id, String customer, long amountCents) {}
interface TokenSource extends Supplier<String> {}
@Configuration
class BillingClientConfig {
@Bean
BillingClient billingClient(RestClient.Builder builder,
TokenSource tokens,
@Value("${billing.base-url}") String baseUrl,
@Value("${billing.api-key}") String apiKey) {
ClientHttpRequestInterceptor bearer = (request, body, execution) -> {
request.getHeaders().setBearerAuth(tokens.get());
return execution.execute(request, body);
};
RestClient restClient = builder
.baseUrl(baseUrl)
.defaultHeader("X-Api-Key", apiKey)
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.requestInterceptor(bearer)
.build();
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build()
.createClient(BillingClient.class);
}
}The application must also provide a TokenSource bean that returns a valid token, for example one that caches the token and refreshes it shortly before it expires. The interceptor does no caching itself, so tokens.get() runs on every request and should be cheap.
If you use Spring Security's OAuth2 client support, it ships interceptors that do this token management for you. The principle is the same: credentials are attached by the RestClient, never by the interface.
Keep secrets out of code and logs
- Inject keys and passwords from environment variables or a secrets manager through properties. Never write them as string literals.
- Do not log full request headers.
Authorizationand API-key headers would end up in your log files. - Treat a base URL that comes from user input as untrusted. A user-controlled
URIargument can send your credentials to a host you did not intend, because the interceptor adds them to whatever URL the request has. Validate the host before you pass aURIto a client that carries credentials.
One builder per client
Spring Boot's auto-configured RestClient.Builder is prototype-scoped. Each injection point gets its own fresh copy that already carries Boot's defaults, such as message converters and any RestClientCustomizer beans. This matters when an application talks to several services:
- Each client bean should inject
RestClient.Builderand callbaseUrl,defaultHeader, and the rest on its own copy. - Changes on one builder never leak into another client.
- Do not share one
RestClientbetween services that need different base URLs or credentials. Build oneRestClientper remote service.
The same applies on Spring Framework 7 and Boot 4 when you register clients by group (a later chapter covers this). Each group is configured separately. The spring.http.serviceclient.<group>.base-url property sets the group's base URL, and the Boot reference documents the other per-group properties available in your version. Authentication that needs logic, such as the interceptor above, is still written in Java.
Common mistakes
- Stale token. Passing a token string to
defaultHeaderfreezes it at startup. Use an interceptor for anything that expires. - Wrong base URL path. A base URL with a path and a method path that also starts with that prefix produces
/v2/v2/invoices. Put each prefix in exactly one place. - Duplicate header values. Setting the same header as both a default and a
@RequestHeaderargument can send two values. - Shared builder state. Building a
RestClientfrom aRestClient.Builderyou created yourself and reused across clients carries settings from one to the other. Inject the Boot builder, or callclone()on one you share. - Credentials sent to the wrong host. A
URIargument overrides the base URL, but the interceptor still adds the token.
Exercise
A client sets defaultHeader("Authorization", "Bearer " + token) when the bean is created. The service works for an hour and then returns 401 on every call, until the application restarts. What is the cause, and how do you fix it?
Show answer
The token string was read once, when the bean was built, so the client keeps sending the expired token. Replace the default header with a ClientHttpRequestInterceptor registered through requestInterceptor(...). The interceptor asks a token supplier for the current token on every request and calls request.getHeaders().setBearerAuth(...) before running execution.execute(request, body). The supplier is responsible for caching the token and refreshing it before it expires.
Exercise
An interface is annotated @HttpExchange("/v2/orders"), and the RestClient base URL is https://shop.example.com/v2. What URL does @GetExchange("/{id}") call for id 7, and how do you correct the configuration?
Show answer
It calls https://shop.example.com/v2/v2/orders/7, because the base URL path and the annotation both contain /v2. Keep /v2 in only one place: either set the base URL to https://shop.example.com and keep /v2/orders in the annotation, or keep the base URL as is and change the annotation to @HttpExchange("/orders").