A Kotlin Minimal REST client
I had 3 goals in mind when starting this work.
- Fully async code no blocking threads.
- Easy to compose both sequentially and concurrently
- Minimum dependencies.
- Small
- Choosing the underlining http client to be Apache HttpAsyncClient satisfy the first and third requirements.
- Extending
CloseableHttpAsyncClient.executeas a suspend function (in the fileCloseableHttpAsyncClientExt.kt) enable easy composition of the result client sequentially and concurrently, hence satisfy the second requirement.
To consume this project using maven add the following to your pom.xml
<dependency>
<groupId>com.github.barakb</groupId>
<artifactId>mini-rest-client</artifactId>
<version>1.0.5</version>
</dependency>
Or gradle
implementation("com.github.barakb:mini-rest-client:1.0.5")
Usage:
To create a Nomad client Kotlin DSL can be used.
fun main(): Unit = runBlocking {
HttpClient {
defaultRequest {
url = "http://httpbin.org/"
header("name", "value")
param("v", "f")
}
}.use { client ->
val headers = client.get<JsonObject> {
path = "headers"
}
println("headers: $headers")
}
}
Inside the client DLS you have full access to the underline HttpAsyncClientBuilder, so it is easy to configure
client {
}
The client uses the return type to extract the result form the http response.
News:
With version 1.0.5 it is possible to set the connectTimeout and the responseTimeout per request
@ExperimentalTime
fun main(): Unit = runBlocking {
HttpClient {
gson { setPrettyPrinting() }
defaultRequest {
contentType = ContentType.APPLICATION_JSON
url = "http://httpbin.org/"
header("name", "value")
param("v", "f")
}
}.use { client ->
val headers = client.get<Headers> {
path = "headers"
connectTimeout = 15.seconds
responseTimeout = 30.seconds
}
println("headers: $headers")
}
}
data class Headers(@HttpHeader("host") var host: String?, val headers: JsonObject)