Kest

Search

Search the documentation

Application

HTTP client

Call other services over HTTP, with timeouts, retries and interceptors.

Your application often needs to call another HTTP service: a payment API, a partner, another microservice. http-client gives you an injectable HttpClientService (the counterpart of HttpModule from @nestjs/axios), built on the JDK's java.net.http. Calls block, which is cheap because handlers run on virtual threads.

Set it up

Kest.run<AppModule> {
    import(HttpClientModule.register {
        baseUrl = "https://api.payments.example"        // paths are added to this
        timeout = Duration.ofSeconds(5)                  // per request (default 10 s)
        connectTimeout = Duration.ofSeconds(2)           // default 5 s
        retries = 2                                      // extra attempts after a failure (see below)
        header("x-source", "billing")                    // sent with every request
        interceptor(myInterceptor)                       // see below
    })
}

Make calls

@Injectable
class Payments(private val http: HttpClientService) {
 
    fun charge(order: Order): Receipt =
        http.post("/charges", mapOf("orderId" to order.id, "cents" to order.total))      // an object body is sent as JSON
            .ensureOk()                                                                    // throws HttpStatusException unless 2xx
            .json<Receipt>()                                                               // decode the JSON answer
 
    fun find(id: String): Charge? {
        val r = http.get("/charges/$id", query = mapOf("expand" to "customer"))
        return if (r.status == 404) null else r.ensureOk().json()
    }
}
Method
get(path, query, headers), delete(path, headers)no body
post, put, patch(path, body, headers)a String or ByteArray is sent as is; any other object is encoded as JSON with the application's codec
request(method, path, body, headers, query)any method

A ClientResponse has status, ok (2xx), text, bytes, headers, header(name), json<T>() and ensureOk(). A path starting with http:// or https:// is used as is, ignoring baseUrl.

Failures and retries

  • Network errors (cannot connect, connection dropped) throw IOException after the retries.
  • A non-2xx answer is not an exception unless you call ensureOk(), which throws HttpStatusException(status, body). Check status yourself when some codes are normal (404).
  • retries = n repeats a call up to n extra times when it fails with a network error or a 5xx, waiting retryDelay (200 ms) then doubling. Retries apply to every method, including POST. A retried POST may be executed twice by the other side: only enable retries when the API is idempotent or you send an idempotency key header.
  • Redirects are followed.

For a dependency that may go down, add resilience around the calling method: a time limit, a circuit breaker and a fallback.

Interceptors

An interceptor wraps every call: add a header, log, sign, measure.

val signer = ClientInterceptor { request, next ->
    val signature = hmac(secret, request.url + String(request.body ?: ByteArray(0)))
    next(ClientRequest(request.method, request.url, request.headers + ("x-signature" to signature), request.body))
}
HttpClientModule.register { baseUrl = "https://partner.example"; interceptor(signer) }

The tracing interceptor (TracingClientInterceptor) adds client spans and the traceparent header (Distributed tracing).

Several clients

register provides one HttpClientService. For several services with different settings, create instances yourself with their own options and provide them under tokens.

Testing

Point baseUrl at a small local server (the JDK's HttpServer, or a TestServer of another module) and assert what it received, or override HttpClientService with a fake.

Read more