Application
Multiple HTTP clients
Register several named HTTP clients in one application, one for each remote API, and pick the one you need by name.
An application often calls more than one remote API: Google for sign-in, Twitter for posts, a payment provider and so on. Each has its own base URL, credentials, timeouts and retry rules. HttpClientsModule registers any number of them, each with its own settings, and you choose the one you want by name.
Register the clients
@Module(imports = [HttpClientsModule.forRoot {
defaults {
timeout = Duration.ofSeconds(10) // every client starts from these settings
header("accept", "application/json")
}
client("google") {
baseUrl = "https://www.googleapis.com"
header("authorization", "Bearer ${System.getenv("GOOGLE_TOKEN")}")
}
client("twitter") {
baseUrl = "https://api.x.com/2"
header("authorization", "Bearer ${System.getenv("TWITTER_TOKEN")}")
retries = 2 // a client's own setting wins over the default
}
}])
class ExternalApisModuleEach client takes the same settings as the single HttpClientModule: baseUrl, timeout, connectTimeout, header(...), retries, retryDelay and interceptor(...).
The clients can also come from configuration, which keeps secrets out of the code:
HttpClientsModule.forRootAsync<ConfigService> { config ->
client("google") {
baseUrl = config.getOrThrow("google.base-url")
header("authorization", "Bearer ${config.getOrThrow<String>("google.token")}")
}
client("twitter") {
baseUrl = config.getOrThrow("twitter.base-url")
header("authorization", "Bearer ${config.getOrThrow<String>("twitter.token")}")
}
}Use them
Inject the registry, and ask for the client by name:
@Injectable
class SocialService {
private val clients by inject<HttpClients>()
fun profile(token: String): Profile =
clients["google"].get("/oauth2/v3/userinfo").ensureOk().json<Profile>()
fun post(text: String): ClientResponse =
clients["twitter"].post("/tweets", mapOf("text" to text)).ensureOk()
}clients["google"]returns the client registered under that name. It is the same object for the whole application, so its connections are reused.- An unknown name fails at the call, and the error lists the names that exist. A typo cannot quietly call the wrong API.
clients.names()lists the registered names, and"google" in clientschecks one.
Each call returns a response. Use ensureOk() to turn a 4xx or 5xx into an exception, or read status and text yourself.
Settings each client keeps to itself
| Setting | Per client | Notes |
|---|---|---|
baseUrl | yes | Relative paths are joined to it. An absolute URL in the path is used as it is. |
headers | yes | A client's headers are added to every request. Per-call headers override them. |
timeout, connectTimeout | yes | The whole call, and the connection alone. |
retries, retryDelay | yes | Retries network failures and 5xx responses, with exponential waits. |
interceptor(...) | yes | Runs around every call, for signing requests or logging. |
Testing
Point a client at a local stub server in the test, and check the calls. The framework's own tests do this: they start a small HTTP server for each "remote API", register a client for each, and assert that each name reaches only its own server.
The single client
If the application calls only one API, HttpClientModule.forRoot { ... } registers one HttpClientService, and you inject it directly. Use HttpClientsModule as soon as there is a second one.