HTTP client
The HTTP client module describes outgoing HTTP calls: transport implementation, request mapping, response mapping,
telemetry, and interceptors. In Kora, clients can be described declaratively with @HttpClient and @HttpRoute,
or used imperatively through the common HttpClient interface when a request must be built in code.
The declarative approach is suitable for most integrations with external services: the method contract becomes the remote call contract,
and Kora creates the implementation at compile time without using Reflection at runtime. The imperative approach is useful for low-level
or dynamic scenarios where path, headers, query parameters, or body are easier to assemble manually.
Recommendation
We recommend using an approach where the OpenAPI file is the primary contract
and clients are created from it using the generator.
This approach allows you to achieve consistency between the consumer and owner of the contract
and update the API faster when the contract changes by replacing the contract file.
For more information about the generator, see the section on generating from OpenAPI.
For a step-by-step walkthrough before the reference details, see HTTP Client and Advanced HTTP Client.
OkHttp¶
HTTP client implementation based on OkHttp library. Please note that the implementation is written in Kotlin and uses appropriate dependencies.
Dependency¶
Dependency build.gradle:
Module:
Dependency build.gradle.kts:
Module:
Configuration¶
Basic OkHttp client configuration parameters:
- Maximum time to establish a connection (default:
5s) - Maximum time to read a response (default:
2m)
Full Configuration
Example of the complete configuration described in the OkHttpClientConfig
and HttpClientConfig classes (default or example values are specified):
httpClient {
ok {
followRedirects = true //(1)!
httpVersion = "HTTP_1_1" //(2)!
retryOnConnectionFailure = true //(3)!
}
connectTimeout = "5s" //(4)!
readTimeout = "2m" //(5)!
useEnvProxy = false //(6)!
proxy {
host = "localhost" //(7)!
port = 8090 //(8)!
user = "user" //(9)!
password = "password" //(10)!
nonProxyHosts = [ "host1", "host2" ] //(11)!
}
telemetry {
logging {
enabled = false //(12)!
mask = "***" //(13)!
maskQueries = [ ] //(14)!
maskHeaders = [ "authorization", "cookie", "set-cookie" ] //(15)!
pathTemplate = true //(16)!
}
metrics {
enabled = true //(17)!
slo = [ 1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000, 90000 ] //(18)!
tags = { // (19)!
"key1" = "value1"
"key2" = "value2"
}
}
tracing {
enabled = true //(20)!
attributes = { // (21)!
"key1" = "value1"
"key2" = "value2"
}
}
}
}
- Whether to follow HTTP redirects (default:
true) - Maximum
HTTPprotocol version to use, available values:HTTP_1_1/HTTP_2/HTTP_3(default:HTTP_1_1) - Whether to retry a request after a connection failure; this can affect the maximum connection establishment time (default:
true) - Maximum time to establish a connection (default:
5s) - Maximum time to read a response (default:
2m) - Whether to use
https_proxy/HTTPS_PROXY/http_proxy/HTTP_PROXYandno_proxy/NO_PROXYenvironment variables for proxy configuration (default:false) - Proxy host (
required, default not specified) - Proxy port (
required, default not specified) - Proxy user (default not specified, optional)
- Proxy password (default not specified, optional)
- Hosts to exclude from proxying (default not specified, optional)
- Enables module logging (default:
false) - Mask used to hide specified headers and request or response parameters (default:
***) - List of request parameters to hide (default:
[]) - List of request or response headers to hide (default:
[ "authorization", "cookie", "set-cookie" ]) - Whether to use the request path template in logging; when not specified, the template is used except at
TRACE, where the full path is used (default not specified, optional) - Enables module metrics (default:
true) - Configures SLO for metrics (default:
ru.tinkoff.kora.telemetry.common.TelemetryConfig.MetricsConfig#DEFAULT_SLO) - Configures metric tags (default:
{}) - Enables module tracing (default:
true) - Configures tracing attributes (default:
{})
httpClient:
ok:
followRedirects: true #(1)!
httpVersion: "HTTP_1_1" #(2)!
retryOnConnectionFailure: true #(3)!
connectTimeout: "5s" #(4)!
readTimeout: "2m" #(5)!
useEnvProxy: false #(6)!
proxy:
host: "localhost" #(7)!
port: 8090 #(8)!
user: "user" #(9)!
password: "password" #(10)!
nonProxyHosts: [ "host1", "host2" ] #(11)!
telemetry:
logging:
enabled: false #(12)!
mask: "***" #(13)!
maskQueries: [ ] #(14)!
maskHeaders: [ "authorization", "cookie", "set-cookie" ] #(15)!
pathTemplate: true #(16)!
metrics:
enabled: true #(17)!
slo: [ 1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000, 90000 ] #(18)!
tags: #(19)!
key1: value1
key2: value2
tracing:
enabled: true #(20)!
attributes: #(21)!
key1: value1
key2: value2
- Whether to follow HTTP redirects (default:
true) - Maximum
HTTPprotocol version to use, available values:HTTP_1_1/HTTP_2/HTTP_3(default:HTTP_1_1) - Whether to retry a request after a connection failure; this can affect the maximum connection establishment time (default:
true) - Maximum time to establish a connection (default:
5s) - Maximum time to read a response (default:
2m) - Whether to use
https_proxy/HTTPS_PROXY/http_proxy/HTTP_PROXYandno_proxy/NO_PROXYenvironment variables for proxy configuration (default:false) - Proxy host (
required, default not specified) - Proxy port (
required, default not specified) - Proxy user (default not specified, optional)
- Proxy password (default not specified, optional)
- Hosts to exclude from proxying (default not specified, optional)
- Enables module logging (default:
false) - Mask used to hide specified headers and request or response parameters (default:
***) - List of request parameters to hide (default:
[]) - List of request or response headers to hide (default:
[ "authorization", "cookie", "set-cookie" ]) - Whether to use the request path template in logging; when not specified, the template is used except at
TRACE, where the full path is used (default not specified, optional) - Enables module metrics (default:
true) - Configures SLO for metrics (default:
ru.tinkoff.kora.telemetry.common.TelemetryConfig.MetricsConfig#DEFAULT_SLO) - Configures metric tags (default:
{}) - Enables module tracing (default:
true) - Configures tracing attributes (default:
{})
Module metrics are described in the Metrics Reference section.
Configurer¶
Example of how to configure OkHttp client builder, OkHttpConfigurer must be available as component:
AsyncHttpClient¶
HTTP client implementation based on the Async HTTP Client library.
Dependency¶
Dependency build.gradle:
Module:
Dependency build.gradle.kts:
Module:
The HttpClient interface implementation is AsyncHttpClient and is available for manual implementation.
Configuration¶
Basic AsyncHttpClient configuration parameters:
- Maximum time to establish a connection (default:
5s) - Maximum time to read a response (default:
2m)
Full Configuration
Example of the complete configuration described in the AsyncHttpClientConfig
and HttpClientConfig classes (default or example values are specified):
httpClient {
async {
followRedirects = true //(1)!
}
connectTimeout = "5s" //(2)!
readTimeout = "2m" //(3)!
useEnvProxy = false //(4)!
proxy {
host = "localhost" //(5)!
port = 8090 //(6)!
user = "user" //(7)!
password = "password" //(8)!
nonProxyHosts = [ "host1", "host2" ] //(9)!
}
telemetry {
logging {
enabled = false //(10)!
mask = "***" //(11)!
maskQueries = [ ] //(12)!
maskHeaders = [ "authorization", "cookie", "set-cookie" ] //(13)!
pathTemplate = true //(14)!
}
metrics {
enabled = true //(15)!
slo = [ 1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000, 90000 ] //(16)!
tags = { // (17)!
"key1" = "value1"
"key2" = "value2"
}
}
tracing {
enabled = true //(18)!
attributes = { // (19)!
"key1" = "value1"
"key2" = "value2"
}
}
}
}
- Whether to follow HTTP redirects (default:
true) - Maximum time to establish a connection (default:
5s) - Maximum time to read a response (default:
2m) - Whether to use
https_proxy/HTTPS_PROXY/http_proxy/HTTP_PROXYandno_proxy/NO_PROXYenvironment variables for proxy configuration (default:false) - Proxy host (
required, default not specified) - Proxy port (
required, default not specified) - Proxy user (default not specified, optional)
- Proxy password (default not specified, optional)
- Hosts to exclude from proxying (default not specified, optional)
- Enables module logging (default:
false) - Mask used to hide specified headers and request or response parameters (default:
***) - List of request parameters to hide (default:
[]) - List of request or response headers to hide (default:
[ "authorization", "cookie", "set-cookie" ]) - Whether to use the request path template in logging; when not specified, the template is used except at
TRACE, where the full path is used (default not specified, optional) - Enables module metrics (default:
true) - Configures SLO for metrics (default:
ru.tinkoff.kora.telemetry.common.TelemetryConfig.MetricsConfig#DEFAULT_SLO) - Configures metric tags (default:
{}) - Enables module tracing (default:
true) - Configures tracing attributes (default:
{})
httpClient:
async:
followRedirects: true #(1)!
connectTimeout: "5s" #(2)!
readTimeout: "2m" #(3)!
useEnvProxy: false #(4)!
proxy:
host: "localhost" #(5)!
port: 8090 #(6)!
user: "user" #(7)!
password: "password" #(8)!
nonProxyHosts: [ "host1", "host2" ] #(9)!
telemetry:
logging:
enabled: false #(10)!
mask: "***" #(11)!
maskQueries: [ ] #(12)!
maskHeaders: [ "authorization", "cookie", "set-cookie" ] #(13)!
pathTemplate: true #(14)!
metrics:
enabled: true #(15)!
slo: [ 1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000, 90000 ] #(16)!
tags: #(17)!
key1: value1
key2: value2
tracing:
enabled: true #(18)!
attributes: #(19)!
key1: value1
key2: value2
- Whether to follow HTTP redirects (default:
true) - Maximum time to establish a connection (default:
5s) - Maximum time to read a response (default:
2m) - Whether to use
https_proxy/HTTPS_PROXY/http_proxy/HTTP_PROXYandno_proxy/NO_PROXYenvironment variables for proxy configuration (default:false) - Proxy host (
required, default not specified) - Proxy port (
required, default not specified) - Proxy user (default not specified, optional)
- Proxy password (default not specified, optional)
- Hosts to exclude from proxying (default not specified, optional)
- Enables module logging (default:
false) - Mask used to hide specified headers and request or response parameters (default:
***) - List of request parameters to hide (default:
[]) - List of request or response headers to hide (default:
[ "authorization", "cookie", "set-cookie" ]) - Whether to use the request path template in logging; when not specified, the template is used except at
TRACE, where the full path is used (default not specified, optional) - Enables module metrics (default:
true) - Configures SLO for metrics (default:
ru.tinkoff.kora.telemetry.common.TelemetryConfig.MetricsConfig#DEFAULT_SLO) - Configures metric tags (default:
{}) - Enables module tracing (default:
true) - Configures tracing attributes (default:
{})
You can also configure Netty transport.
Native client¶
Implementation of an HTTP client based on the native client provided in the JDK.
Dependency¶
Dependency build.gradle:
Module:
Dependency build.gradle.kts:
Module:
The HttpClient interface implementation is JdkHttpClient and is available for manual implementation.
Configuration¶
Basic JDK HttpClient configuration parameters:
- Maximum time to establish a connection (default:
5s) - Maximum time to read a response (default:
2m)
Full Configuration
Example of the complete configuration described in the JdkHttpClientConfig
and HttpClientConfig classes (default or example values are specified):
httpClient {
jdk {
threads = 2 //(1)!
httpVersion = "HTTP_1_1" //(2)!
}
connectTimeout = "5s" //(3)!
readTimeout = "2m" //(4)!
useEnvProxy = false //(5)!
proxy {
host = "localhost" //(6)!
port = 8090 //(7)!
user = "user" //(8)!
password = "password" //(9)!
nonProxyHosts = [ "host1", "host2" ] //(10)!
}
telemetry {
logging {
enabled = false //(11)!
mask = "***" //(12)!
maskQueries = [ ] //(13)!
maskHeaders = [ "authorization", "cookie", "set-cookie" ] //(14)!
pathTemplate = true //(15)!
}
metrics {
enabled = true //(16)!
slo = [ 1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000, 90000 ] //(17)!
tags = { // (18)!
"key1" = "value1"
"key2" = "value2"
}
}
tracing {
enabled = true //(19)!
attributes = { // (20)!
"key1" = "value1"
"key2" = "value2"
}
}
}
}
- Number of threads for the
HTTPclient (default: number of available processors multiplied by2) - Which
HTTPprotocol version to use, available values:HTTP_1_1/HTTP_2(default:HTTP_1_1) - Maximum time to establish a connection (default:
5s) - Maximum time to read a response (default:
2m) - Whether to use
https_proxy/HTTPS_PROXY/http_proxy/HTTP_PROXYandno_proxy/NO_PROXYenvironment variables for proxy configuration (default:false) - Proxy host (
required, default not specified) - Proxy port (
required, default not specified) - Proxy user (default not specified, optional)
- Proxy password (default not specified, optional)
- Hosts to exclude from proxying (default not specified, optional)
- Enables module logging (default:
false) - Mask used to hide specified headers and request or response parameters (default:
***) - List of request parameters to hide (default:
[]) - List of request or response headers to hide (default:
[ "authorization", "cookie", "set-cookie" ]) - Whether to use the request path template in logging; when not specified, the template is used except at
TRACE, where the full path is used (default not specified, optional) - Enables module metrics (default:
true) - Configures SLO for metrics (default:
ru.tinkoff.kora.telemetry.common.TelemetryConfig.MetricsConfig#DEFAULT_SLO) - Configures metric tags (default:
{}) - Enables module tracing (default:
true) - Configures tracing attributes (default:
{})
httpClient:
jdk:
threads: 2 #(1)!
httpVersion: "HTTP_1_1" #(2)!
connectTimeout: "5s" #(3)!
readTimeout: "2m" #(4)!
useEnvProxy: false #(5)!
proxy:
host: "localhost" #(6)!
port: 8090 #(7)!
user: "user" #(8)!
password: "password" #(9)!
nonProxyHosts: [ "host1", "host2" ] #(10)!
telemetry:
logging:
enabled: false #(11)!
mask: "***" #(12)!
maskQueries: [ ] #(13)!
maskHeaders: [ "authorization", "cookie", "set-cookie" ] #(14)!
pathTemplate: true #(15)!
metrics:
enabled: true #(16)!
slo: [ 1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000, 90000 ] #(17)!
tags: #(18)!
key1: value1
key2: value2
tracing:
enabled: true #(19)!
attributes: #(20)!
key1: value1
key2: value2
- Number of threads for the
HTTPclient (default: number of available processors multiplied by2) - Which
HTTPprotocol version to use, available values:HTTP_1_1/HTTP_2(default:HTTP_1_1) - Maximum time to establish a connection (default:
5s) - Maximum time to read a response (default:
2m) - Whether to use
https_proxy/HTTPS_PROXY/http_proxy/HTTP_PROXYandno_proxy/NO_PROXYenvironment variables for proxy configuration (default:false) - Proxy host (
required, default not specified) - Proxy port (
required, default not specified) - Proxy user (default not specified, optional)
- Proxy password (default not specified, optional)
- Hosts to exclude from proxying (default not specified, optional)
- Enables module logging (default:
false) - Mask used to hide specified headers and request or response parameters (default:
***) - List of request parameters to hide (default:
[]) - List of request or response headers to hide (default:
[ "authorization", "cookie", "set-cookie" ]) - Whether to use the request path template in logging; when not specified, the template is used except at
TRACE, where the full path is used (default not specified, optional) - Enables module metrics (default:
true) - Configures SLO for metrics (default:
ru.tinkoff.kora.telemetry.common.TelemetryConfig.MetricsConfig#DEFAULT_SLO) - Configures metric tags (default:
{}) - Enables module tracing (default:
true) - Configures tracing attributes (default:
{})
Declarative Client¶
It is suggested to use special annotations to create a declarative client:
@HttpClient- indicates that the interface is a declarative HTTP client@HttpRoute- specifies HTTP request type and request path
Client Configuration¶
By default, configuration for a particular @HttpClient implementation is looked up at httpClient.{lower case class name}.
If the path must be specified explicitly, use the configPath annotation parameter:
@HttpClient can also specify tags for injected components:
httpClientTag— tag used to select a particular transportHttpClientwhen the graph contains several implementations with different@TagvaluestelemetryTag— tag used to select a particular client telemetry factory
These tags select which component to inject when several are present in the graph. The other half is providing that component
under the same @Tag. For example, to give one client a dedicated transport (a separate connection pool, different timeouts,
a custom OkHttpConfigurer, etc.) provide a tagged HttpClient and reference the same tag class from httpClientTag:
public final class CustomTransport { } //(1)!
@Module
public interface TransportModule {
@Tag(CustomTransport.class) //(2)!
default HttpClient customHttpClient(okhttp3.OkHttpClient okHttp) {
return new OkHttpClient(okHttp); //(3)!
}
}
- A marker class used only as a tag
- Provided under the same tag referenced by
httpClientTag ru.tinkoff.kora.http.client.ok.OkHttpClient— the Kora transport wrapping anokhttp3.OkHttpClient
class CustomTransport //(1)!
@Module
interface TransportModule {
@Tag(CustomTransport::class) //(2)!
fun customHttpClient(okHttp: okhttp3.OkHttpClient): HttpClient {
return OkHttpClient(okHttp) //(3)!
}
}
- A marker class used only as a tag
- Provided under the same tag referenced by
httpClientTag -
ru.tinkoff.kora.http.client.ok.OkHttpClient— the Kora transport wrapping anokhttp3.OkHttpClient -
A marker class used only as a tag
- Provided under the same tag referenced by
httpClientTag
telemetryTag works the same way for a tagged HttpClientTelemetryFactory. When a tag is omitted, the default untagged transport
and telemetry are used.
Basic declarative client configuration parameters:
- Base service
URLwhere requests will be sent (required, no default) - Maximum request time (default: not specified, optional)
Full Configuration
Example configuration in the case of the httpClient.someClient path described in the DeclarativeHttpClientConfig class:
httpClient {
someClient {
url = "https://localhost:8090" //(1)!
requestTimeout = "10s" //(2)!
telemetry {
logging {
enabled = false //(3)!
mask = "***" //(4)!
maskQueries = [ ] //(5)!
maskHeaders = [ "authorization", "cookie", "set-cookie" ] //(6)!
pathTemplate = true //(7)!
}
metrics {
enabled = true //(8)!
slo = [ 1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000, 90000 ] //(9)!
tags = { // (10)!
"key1" = "value1"
"key2" = "value2"
}
}
tracing {
enabled = true //(11)!
attributes = { // (12)!
"key1" = "value1"
"key2" = "value2"
}
}
}
}
}
- Base service
URLwhere requests will be sent (required, default not specified) - Maximum request time: may include
DNSresolution, connection, request body write, server processing, and response body read. If the call requires redirects or retries, they must all finish within one period (default not specified, optional) - Enables module logging (default:
false) - Mask used to hide specified headers and request or response parameters (default:
***) - List of request parameters to hide (default:
[]) - List of request or response headers to hide (default:
[ "authorization", "cookie", "set-cookie" ]) - Whether to use the request path template in logging; when not specified, the template is used except at
TRACE, where the full path is used (default not specified, optional) - Enables module metrics (default:
true) - Configures SLO for metrics (default:
ru.tinkoff.kora.telemetry.common.TelemetryConfig.MetricsConfig#DEFAULT_SLO) - Configures metric tags (default:
{}) - Enables module tracing (default:
true) - Configures tracing attributes (default:
{})
httpClient:
someClient:
url: "https://localhost:8090" #(1)!
requestTimeout: "10s" #(2)!
telemetry:
logging:
enabled: false #(3)!
mask: "***" #(4)!
maskQueries: [ ] #(5)!
maskHeaders: [ "authorization", "cookie", "set-cookie" ] #(6)!
pathTemplate: true #(7)!
metrics:
enabled: true #(8)!
slo: [ 1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000, 90000 ] #(9)!
tags: #(10)!
key1: value1
key2: value2
tracing:
enabled: true #(11)!
attributes: #(12)!
key1: value1
key2: value2
- Base service
URLwhere requests will be sent (required, default not specified) - Maximum request time: may include
DNSresolution, connection, request body write, server processing, and response body read. If the call requires redirects or retries, they must all finish within one period (default not specified, optional) - Enables module logging (default:
false) - Mask used to hide specified headers and request or response parameters (default:
***) - List of request parameters to hide (default:
[]) - List of request or response headers to hide (default:
[ "authorization", "cookie", "set-cookie" ]) - Whether to use the request path template in logging; when not specified, the template is used except at
TRACE, where the full path is used (default not specified, optional) - Enables module metrics (default:
true) - Configures SLO for metrics (default:
ru.tinkoff.kora.telemetry.common.TelemetryConfig.MetricsConfig#DEFAULT_SLO) - Configures metric tags (default:
{}) - Enables module tracing (default:
true) - Configures tracing attributes (default:
{})
Method Configuration¶
For a particular method, some parameters can be configured separately. The method configuration path is determined by the client path and the method name:
if the client path is httpClient.someClient, the final path for the hello method is httpClient.someClient.hello.
Method configuration is applied over client configuration: method requestTimeout replaces the client value, and method telemetry settings override
only explicitly specified fields.
Basic method configuration parameters:
Full Configuration
Full method configuration example:
httpClient {
someClient {
hello {
requestTimeout = "10s" //(1)!
telemetry {
logging {
enabled = false //(2)!
mask = "***" //(3)!
maskQueries = [ ] //(4)!
maskHeaders = [ "authorization", "cookie", "set-cookie" ] //(5)!
pathTemplate = true //(6)!
}
metrics {
enabled = true //(7)!
slo = [ 1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000, 90000 ] //(8)!
tags = { // (9)!
"key1" = "value1"
"key2" = "value2"
}
}
tracing {
enabled = true //(10)!
attributes = { // (11)!
"key1" = "value1"
"key2" = "value2"
}
}
}
}
}
}
- Maximum request time: may include
DNSresolution, connection, request body write, server processing, and response body read. If the call requires redirects or retries, they must all finish within one period (default not specified, optional) - Enables module logging (default:
false) - Mask used to hide specified headers and request or response parameters (default:
***) - List of request parameters to hide (default:
[]) - List of request or response headers to hide (default:
[ "authorization", "cookie", "set-cookie" ]) - Whether to use the request path template in logging; when not specified, the client value is inherited (default not specified, optional)
- Enables module metrics (default:
true) - Configures SLO for metrics (default:
ru.tinkoff.kora.telemetry.common.TelemetryConfig.MetricsConfig#DEFAULT_SLO) - Configures metric tags (default:
{}) - Enables module tracing (default:
true) - Configures tracing attributes (default:
{})
httpClient:
someClient:
hello:
requestTimeout: "10s" #(1)!
telemetry:
logging:
enabled: false #(2)!
mask: "***" #(3)!
maskQueries: [ ] #(4)!
maskHeaders: [ "authorization", "cookie", "set-cookie" ] #(5)!
pathTemplate: true #(6)!
metrics:
enabled: true #(7)!
slo: [ 1, 10, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000, 90000 ] #(8)!
tags: #(9)!
key1: value1
key2: value2
tracing:
enabled: true #(10)!
attributes: #(11)!
key1: value1
key2: value2
- Maximum request time: may include
DNSresolution, connection, request body write, server processing, and response body read. If the call requires redirects or retries, they must all finish within one period (default not specified, optional) - Enables module logging (default:
false) - Mask used to hide specified headers and request or response parameters (default:
***) - List of request parameters to hide (default:
[]) - List of request or response headers to hide (default:
[ "authorization", "cookie", "set-cookie" ]) - Whether to use the request path template in logging; when not specified, the client value is inherited (default not specified, optional)
- Enables module metrics (default:
true) - Configures SLO for metrics (default:
ru.tinkoff.kora.telemetry.common.TelemetryConfig.MetricsConfig#DEFAULT_SLO) - Configures metric tags (default:
{}) - Enables module tracing (default:
true) - Configures tracing attributes (default:
{})
Request¶
This section describes HTTP request transformations for a declarative HTTP client.
Use special annotations to specify request parameters.
String Parameter Conversion¶
StringParameterConverter<T> converts a parameter value to a string before Kora puts it into a path, query parameter,
header, or cookie. The interface has one method:
The converter is looked up as a regular graph component by the exact parameter type. If the parameter has type Map<String, T>,
the converter is looked up for value type T; if Map<String, List<T>> is used, it is applied to every list item.
Built-in converters are available for Boolean, Short, Integer, Long, Double, Float, UUID, BigDecimal, BigInteger,
Duration, OffsetTime, OffsetDateTime, LocalTime, LocalDate, LocalDateTime, ZonedDateTime, and Instant.
Date and time types are written in ISO format. For custom types, provide a StringParameterConverter<T> component:
After that, the type can be used in client parameters:
Path parameter¶
@Path - denotes the value of the request path part, the parameter itself is specified in {quote} in the path
and the name of the parameter is specified in value or is equal to the name of the method argument by default.
Query parameter¶
@Query - query parameter value, the name is specified in value or defaults to the method argument name.
Single values, List<T>, Set<T>, Collection<T>, Map<String, T>, and Map<String, List<T>> are supported.
For non-string values, an available StringParameterConverter<T> is used.
Query parameters can also be sent in key-value format using Map, where the key is the parameter name and must be String.
If a Map value is a list, every item is sent as a separate value of the same parameter.
If a list item is null, the parameter is sent without a value.
Header¶
@Header - value of request header, parameter name is specified in value or defaults to the method argument name.
Single values, List<T>, Set<T>, Collection<T>, Map<String, T>, and a ready HttpHeaders object are supported.
Headers can be sent in key-value format using HttpHeaders or Map, where the key is the header name and must be String.
For non-string values, an available StringParameterConverter<T> is used:
Request body¶
Specifying the body of a request requires using a method argument without special annotations.
Kora provides built-in request mappers for the following types, each of which also sets the default Content-Type header:
| Body argument type | Default Content-Type |
|---|---|
String |
text/plain; charset=utf-8 |
byte[] / ByteBuffer |
application/octet-stream |
Flow.Publisher<ByteBuffer> |
application/octet-stream (streamed, not buffered in memory) |
@Json T (see Json) |
application/json |
FormUrlEncoded (see Text form) |
application/x-www-form-urlencoded |
FormMultipart (see Binary Form) |
multipart/form-data |
For any other type, or to set a different Content-Type, use a custom body mapper with HttpClientRequestMapper<T> and return the
appropriate HttpBody (for example HttpBody.of(bytes, "application/x-protobuf")). A Content-Type explicitly set via @Header takes precedence over the default.
Json¶
In order to indicate that the body is Json and needs to embed JsonWriter<T>, that is required to use the special @Json tag annotation:
Json module is required.
Text form¶
Use FormUrlEncoded (from ru.tinkoff.kora.http.common.form) as the body argument type to send a body with the
application/x-www-form-urlencoded content type (form data).
No @Json or @Mapping annotation is needed — Kora has a built-in writer for this type.
FormUrlEncoded is a collection of named parts, where every part can hold one or several values:
FormUrlEncoded.FormPart(String name, String value)— a part with a single valueFormUrlEncoded.FormPart(String name, List<String> values)— a part with several values (the field is repeated for each value)new FormUrlEncoded(FormPart...)/new FormUrlEncoded(List<FormPart>)/new FormUrlEncoded(Map<String, FormPart>)— construct the form; parts declared with the same name are merged into one
Declare the client method with a FormUrlEncoded parameter:
An example of a call with this form:
Binary Form¶
Use FormMultipart (from ru.tinkoff.kora.http.common.form) as the body argument type to send a multipart/form-data
body (binary form), typically used for file uploads mixed with text fields.
No @Json or @Mapping annotation is needed.
FormMultipart is a list of parts built through static factory methods:
FormMultipart.data(String name, String value)— a plain text fieldFormMultipart.file(String name, String fileName, String contentType, byte[] content)— a file part loaded into memory (fileNameandcontentTypemay benull)FormMultipart.file(String name, String fileName, String contentType, Flow.Publisher<ByteBuffer> content)— a streamed file part for large content that should not be buffered fully in memorynew FormMultipart(List<? extends FormPart>)— construct the form from the parts
Declare the client method with a FormMultipart parameter:
An example of a call with this form:
var response = someClient.formMultipart(new FormMultipart(List.of(
FormMultipart.data("field1", "some data content"), //(1)!
FormMultipart.file("field2", "example1.txt", "text/plain",
"some file content".getBytes(StandardCharsets.UTF_8)) //(2)!
)));
- A plain text field
- A file part with file name and content type
val response = someClient.formMultipart(
FormMultipart(
listOf<FormMultipart.FormPart>(
FormMultipart.data("field1", "some data content"), //(1)!
FormMultipart.file(
"field2",
"example1.txt",
"text/plain",
"some file content".toByteArray(StandardCharsets.UTF_8)
) //(2)!
)
)
)
- A plain text field
- A file part with file name and content type
Custom body¶
If the body needs to be written in a way different from the standard mechanisms,
it is possible to use a special HttpClientRequestMapper interface to implement your custom logic:
@HttpClient
public interface SomeClient {
record UserBody(String id) {}
final class UserRequestMapper implements HttpClientRequestMapper<UserBody> {
@Override
public HttpBodyOutput apply(Context ctx, UserBody value) {
return HttpBody.plaintext(value.id());
}
}
@HttpRoute(method = HttpMethod.POST, path = "/hello/world")
void hello(@Mapping(UserRequestMapper.class) UserBody body);
}
@HttpClient
interface SomeClient {
data class UserBody(val id: String)
class UserRequestMapper : HttpClientRequestMapper<UserBody> {
override fun apply(ctx: Context, value: UserBody): HttpBodyOutput {
return HttpBody.plaintext(value.id)
}
}
@HttpRoute(method = HttpMethod.POST, path = "/hello/world")
fun hello(@Mapping(UserRequestMapper::class) body: UserBody)
}
Example: Protobuf Serialization
@HttpClient
public interface ProtobufClient {
final class ProtobufRequestMapper implements HttpClientRequestMapper<MyMessage> {
@Override
public HttpBodyOutput apply(Context ctx, MyMessage value) {
byte[] protobufBytes = value.toByteArray();
return HttpBody.of(protobufBytes, "application/x-protobuf");
}
}
@HttpRoute(method = HttpMethod.POST, path = "/message")
void sendMessage(@Mapping(ProtobufRequestMapper.class) MyMessage message);
}
@HttpClient
interface ProtobufClient {
class ProtobufRequestMapper : HttpClientRequestMapper<MyMessage> {
override fun apply(ctx: Context, value: MyMessage): HttpBodyOutput {
val protobufBytes = value.toByteArray()
return HttpBody.of(protobufBytes, "application/x-protobuf")
}
}
@HttpRoute(method = HttpMethod.POST, path = "/message")
fun sendMessage(@Mapping(ProtobufRequestMapper::class) message: MyMessage)
}
Cookie¶
@Cookie - Cookie value, the parameter name is specified in value or defaults to the method argument name.
Single values, List<T>, Set<T>, Collection<T>, Map<String, T>, and a ready Cookie object are supported.
Cookies are added to the Cookie header; for collections, every value becomes a separate cookie value with the same name.
Required parameters¶
By default, all arguments declared in a method are required (NotNull).
By default, all arguments declared in a method that do not use the Kotlin Nullability syntax are considered required (NotNull).
Optional parameters¶
If a method argument is optional, that is, it may not exist then,
@Nullable annotation can be used:
@HttpClient
public interface SomeClient {
@HttpRoute(method = HttpMethod.GET, path = "/hello/world")
void hello(@Nullable @Query("queryValue") String queryValue); //(1)!
}
- Any
@Nullableannotation will do, such asjavax.annotation.Nullable/jakarta.annotation.Nullable/org.jetbrains.annotations.Nullable/ etc.
It is expected to use the Kotlin Nullability syntax and mark such a parameter as Nullable:
Response¶
The section describes the transformation of an HTTP response from a declarative HTTP client.
Response body¶
By default, you can use the standard response body return value types such as void, byte[], ByteBuffer or String.
Json¶
If the body is to be read as Json, the @Json annotation must be used over the method to specify handler with JsonReader<T>.
Json module is required.
Response Entity¶
If the intention is to read the body and also get the headers and status code of the response,
it is intended to use HttpResponseEntity, which is a wrapper over the response body.
Below is an example similar to the Json example along with the HttpResponseEntity wrapper:
Custom response¶
If you need to read the response in a different way, you can use the special HttpClientResponseMapper interface:
@HttpClient
public interface SomeClient {
record MyResponse(String name) { }
final class ResponseMapper implements HttpClientResponseMapper<MyResponse> {
@Override
public MyResponse apply(HttpClientResponse response) throws IOException, HttpClientDecoderException {
try (var is = response.body().asInputStream()) {
final byte[] bytes = is.readAllBytes();
var body = new String(bytes, StandardCharsets.UTF_8);
return new MyResponse(body);
}
}
}
@Mapping(ResponseMapper.class)
@HttpRoute(method = HttpMethod.GET, path = "/hello/world")
MyResponse hello();
}
@HttpClient
interface SomeClient {
data class MyResponse(val name: String)
class ResponseMapper : HttpClientResponseMapper<MyResponse> {
@Throws(IOException::class, HttpClientDecoderException::class)
override fun apply(response: HttpClientResponse): MyResponse {
response.body().asInputStream().use {
val bytes: ByteArray = it.readAllBytes()
val body = String(bytes, StandardCharsets.UTF_8)
return MyResponse(body)
}
}
}
@Mapping(ResponseMapper::class)
@HttpRoute(method = HttpMethod.GET, path = "/hello/world")
fun hello(): MyResponse
}
Example: Error Handling in Mapper
@HttpClient
public interface ApiClient {
record ApiResponse(String status, Object data) {}
final class SafeResponseMapper implements HttpClientResponseMapper<ApiResponse> {
private final JsonReader<ApiResponse> jsonReader;
public SafeResponseMapper(JsonReader<ApiResponse> jsonReader) {
this.jsonReader = jsonReader;
}
@Override
public ApiResponse apply(HttpClientResponse response) throws IOException {
int code = response.code();
final byte[] body;
try (var is = response.body().asInputStream()) {
body = is.readAllBytes();
}
if (code >= 400) {
// Handle error: log or throw exception
throw new HttpClientResponseException(code, response.headers(), body);
}
if (body.length == 0) {
return null;
}
return jsonReader.read(body);
}
}
@HttpRoute(method = HttpMethod.GET, path = "/api/data")
@Mapping(SafeResponseMapper.class)
ApiResponse getData();
}
@HttpClient
interface ApiClient {
data class ApiResponse(val status: String, val data: Any?)
class SafeResponseMapper(
private val jsonReader: JsonReader<ApiResponse>
) : HttpClientResponseMapper<ApiResponse> {
@Throws(IOException::class)
override fun apply(response: HttpClientResponse): ApiResponse {
val code = response.code()
val body = response.body().asInputStream().use { it.readAllBytes() }
if (code >= 400) {
// Handle error: log or throw exception
throw HttpClientResponseException(code, response.headers(), body)
}
if (body.isEmpty()) {
return null
}
return jsonReader.read(body)
}
}
@HttpRoute(method = HttpMethod.GET, path = "/api/data")
@Mapping(SafeResponseMapper::class)
fun getData(): ApiResponse
}
Response Error¶
By default, when neither converter tag nor converter is specified, conversion is applied only for 2xx HTTP response codes.
For all other codes, HttpClientResponseException is thrown. It contains the HTTP response code, response body, and response headers.
Client Exceptions¶
All standard HTTP client exceptions inherit from HttpClientException, which is a RuntimeException.
This lets you catch a specific error type or all client errors with one common type:
try {
client.getUser("123");
} catch (HttpClientResponseException e) {
var code = e.getCode();
var headers = e.getHeaders();
var body = e.getBytes();
} catch (HttpClientException e) {
throw e;
}
Main exception types:
HttpClientResponseException— response was received, but its code was not handled as successful. ContainsgetCode(),getHeaders(), andgetBytes().HttpClientTimeoutException— request, connection, or read timeout expired.HttpClientConnectionException— error while establishing or maintaining a connection to the remote host.HttpClientEncoderException— error while converting a user value into a request body.HttpClientDecoderException— error while converting a response body into a user type.HttpClientUnknownException— other transport client error that did not match a more specific category.
HttpClientResponseException is created after reading the response body into a byte array. If the body could not be read fully,
the read error is added as a suppressed exception, and getBytes() contains the body that could be collected.
Conversion by Code¶
If specific conversions are required depending on the HTTP status code of the response, you can use the @ResponseCodeMapper annotation to specify a
correspondence between the HTTP status code and the HttpClientResponseMapper resolver.
You can also use ResponseCodeMapper.DEFAULT to define default behavior for all unlisted HTTP codes.
If mapper is specified for a code, that particular HttpClientResponseMapper is used.
If type is specified, Kora selects a response mapper for that type and then casts the result to the method return type.
This is useful for closed response hierarchies where different HTTP statuses correspond to different result subtypes.
@HttpClient
public interface SomeClient {
record UserResponse(UserResponse.Payload payload, UserResponse.Error error) {
public record Error(int code, String message) {}
public record Payload(String message) {}
}
@ResponseCodeMapper(code = ResponseCodeMapper.DEFAULT, mapper = ResponseErrorMapper.class)
@ResponseCodeMapper(code = 200, mapper = ResponseSuccessMapper.class)
@HttpRoute(method = HttpMethod.GET, path = "/hello/world")
UserResponse hello();
}
@HttpClient
interface SomeClient {
data class UserResponse(val payload: Payload, val error: Error) {
data class Error(val code: Int, val message: String)
data class Payload(val message: String)
}
@ResponseCodeMapper(code = ResponseCodeMapper.DEFAULT, mapper = ResponseErrorMapper::class)
@ResponseCodeMapper(code = 200, mapper = ResponseSuccessMapper::class)
@HttpRoute(method = HttpMethod.GET, path = "/hello/world")
fun hello(): UserResponse
}
In the example above, ResponseSuccessMapper will be used for status code 200,
and for all other status codes the ResponseErrorMapper will be used.
Example with the type parameter:
@HttpClient
public interface SomeClient {
sealed interface UserResponse permits Success, Error {}
record Success(String id) implements UserResponse {}
record Error(String message) implements UserResponse {}
@Json
@ResponseCodeMapper(code = 200, type = Success.class)
@ResponseCodeMapper(code = 404, type = Error.class)
@HttpRoute(method = HttpMethod.GET, path = "/users/{id}")
UserResponse get(@Path String id);
}
@HttpClient
interface SomeClient {
sealed interface UserResponse
data class Success(val id: String) : UserResponse
data class Error(val message: String) : UserResponse
@Json
@ResponseCodeMapper(code = 200, type = Success::class)
@ResponseCodeMapper(code = 404, type = Error::class)
@HttpRoute(method = HttpMethod.GET, path = "/users/{id}")
fun get(@Path id: String): UserResponse
}
Signatures¶
Available signatures for declarative HTTP client methods out of the box:
The T refers to the type of the return value. It can be a body type (void, String, byte[], a @Json type, etc.), or
HttpResponseEntity<T> to also read the status code and headers. A @Nullable T return allows an empty successful body.
T myMethod()— synchronous (blocking): the calling thread waits for the responseCompletionStage<T> myMethod()— asynchronous: returns immediately, completes when the response arrives; see CompletionStageMono<T> myMethod()— asynchronous via Project Reactor (requires the reactor-core dependency)
By T we mean the type of the return value, which may be T, T? (nullable for an empty successful body), or Unit.
T can be a body type or HttpResponseEntity<T> to also read the status code and headers.
myMethod(): T— synchronous (blocking): the calling thread waits for the responsesuspend myMethod(): T— asynchronous Kotlin Coroutine (requires the kotlinx-coroutines-core dependency asimplementation)
By default a non-2xx response throws HttpClientResponseException regardless of signature; use @ResponseCodeMapper or HttpResponseEntity to handle other status codes without an exception.
Interceptors¶
You can create interceptors to change behavior or create additional behavior using the HttpClientInterceptor interface.
Interceptors can be attached to specific methods or the entire @HttpClient class using the @InterceptWith annotation.
Kora ships ready-made interceptors (such as Root URL and the authorization interceptors),
and you can implement your own — see method-level and class-level examples below.
The interface receives the current Context, the outgoing HttpClientRequest, and the InterceptChain that continues processing:
public interface HttpClientInterceptor {
CompletionStage<HttpClientResponse> processRequest(Context ctx, InterceptChain chain, HttpClientRequest request) throws Exception; //(1)!
interface InterceptChain {
CompletionStage<HttpClientResponse> process(Context ctx, HttpClientRequest request) throws Exception; //(2)!
}
}
- Called for every request the interceptor is attached to
- Continues the chain (the next interceptor, or the actual transport call)
An interceptor can:
- Modify the request before sending — rebuild it via
request.toBuilder()(add a header, change the URI, replace the body), then pass the new request tochain.process(ctx, newRequest) - Continue the chain — return
chain.process(ctx, request)unchanged - Short-circuit — return a response without calling
chain.process(...)(for example a cached response) - Inspect or transform the response — call
chain.process(...)and chain athenApply/thenCompose/exceptionallyon the returnedCompletionStage - Fail the call — throw an exception or return a failed
CompletionStageto break the chain
Example that adds a header to every request and inspects the response status:
@Component
public final class TracingInterceptor implements HttpClientInterceptor {
@Override
public CompletionStage<HttpClientResponse> processRequest(Context ctx, InterceptChain chain, HttpClientRequest request) throws Exception {
HttpClientRequest modified = request.toBuilder()
.header("x-request-id", UUID.randomUUID().toString()) //(1)!
.build();
return chain.process(ctx, modified).thenApply(response -> {
if (response.code() >= 500) {
// observe server errors
}
return response;
});
}
}
request.toBuilder()returns anHttpClientRequestBuilderinitialized from the current request
@Component
class TracingInterceptor : HttpClientInterceptor {
override fun processRequest(
ctx: Context,
chain: HttpClientInterceptor.InterceptChain,
request: HttpClientRequest
): CompletionStage<HttpClientResponse> {
val modified = request.toBuilder()
.header("x-request-id", UUID.randomUUID().toString()) //(1)!
.build()
return chain.process(ctx, modified).thenApply { response ->
if (response.code() >= 500) {
// observe server errors
}
response
}
}
}
request.toBuilder()returns anHttpClientRequestBuilderinitialized from the current request
For the imperative HttpClient, an interceptor is attached with httpClient.with(interceptor) instead of @InterceptWith.
Root URL¶
RootUriInterceptor is a ready-made interceptor that adds a base URL to relative requests.
If the request already contains a scheme (http:// or https://), the interceptor leaves it unchanged.
If the request is relative, RootUriInterceptor adds the root address and guarantees one / separator between the root and the path.
After registering the interceptor, connect it to the client:
For declarative clients, it is usually more convenient to set the base URL through DeclarativeHttpClientConfig.url.
RootUriInterceptor is useful for imperative HttpClient or when a shared root address should be added as separate cross-cutting behavior.
Custom interceptor¶
Method-level interceptor:
@HttpClient
public interface SomeClient {
final class MethodInterceptor implements HttpClientInterceptor {
private final Component1 component1;
private MethodInterceptor(Component1 component1) {
this.component1 = component1;
}
@Override
public CompletionStage<HttpClientResponse> processRequest(Context ctx, InterceptChain chain, HttpClientRequest request) throws Exception {
component1.doSomething();
return chain.process(ctx, request);
}
}
@InterceptWith(MethodInterceptor.class)
@HttpRoute(method = HttpMethod.GET, path = "/hello/world")
void hello();
}
@HttpClient
interface SomeClient {
class MethodInterceptor(val component1: Component1) : HttpClientInterceptor {
@Throws(Exception::class)
override fun processRequest(
ctx: Context,
chain: HttpClientInterceptor.InterceptChain,
request: HttpClientRequest
): CompletionStage<HttpClientResponse> {
component1.doSomething()
return chain.process(ctx, request)
}
}
@InterceptWith(MethodInterceptor::class)
@HttpRoute(method = HttpMethod.GET, path = "/hello/world")
fun hello()
}
Class-level interceptor:
Interceptor execution order:
Interceptors are executed in declaration order (left to right). Each interceptor can:
- Modify the request before sending
- Call the next interceptor in the chain (chain.process())
- Modify the response after receiving
- Throw an exception to break the chain
Request → Interceptor1 → Interceptor2 → Interceptor3 → HTTP Server
Response ← Interceptor1 ← Interceptor2 ← Interceptor3 ← HTTP Server
Global interceptor¶
To apply an interceptor to all clients, register it as a component without @InterceptWith:
@Component
class GlobalInterceptor : HttpClientInterceptor {
@Throws(Exception::class)
override fun processRequest(
ctx: Context,
chain: HttpClientInterceptor.InterceptChain,
request: HttpClientRequest
): CompletionStage<HttpClientResponse> {
// Applied to all HTTP clients
return chain.process(ctx, request)
}
}
If the interceptor must be applied to all client methods, @InterceptWith can be placed on the interface:
If interceptors are specified on both the client and the method, both interceptor sets are applied for that call.
Authorization¶
Kora provides out-of-the-box interceptors that can be used for Basic/ApiKey/Bearer/OAuth authorization.
Basic¶
You need to configure an interceptor and configuration for Basic authorization:
@Module
public interface BasicAuthModule {
@ConfigSource("openapiAuth.basicAuth")
public interface BasicAuthConfig {
String username();
String password();
}
default BasicAuthHttpClientInterceptor basicAuther(BasicAuthConfig config) {
return new BasicAuthHttpClientInterceptor(config.username(), config.password());
}
}
@Module
interface BasicAuthModule {
@ConfigSource("openapiAuth.basicAuth")
interface BasicAuthConfig {
fun username(): String
fun password(): String
}
fun basicAuther(config: BasicAuthConfig): BasicAuthHttpClientInterceptor {
return BasicAuthHttpClientInterceptor(config.username(), config.password())
}
}
You can also provide your own HttpClientTokenProvider implementation in the constructor if rules for getting secrets are different.
Then add interceptor for the entire HTTP client or specific methods.
ApiKey¶
You need to configure an interceptor and configuration for ApiKey authorization:
@Module
public interface ApiKeyAuthModule {
@ConfigSource("openapiAuth.apiKeyAuth")
interface ApiKeyAuthConfig {
String apiKey();
}
default ApiKeyHttpClientInterceptor apiKeyAuther(ApiKeyAuthConfig config) {
return new ApiKeyHttpClientInterceptor(ApiKeyLocation.HEADER, "X-API-KEY", config.apiKey());
}
}
Then add interceptor for the entire HTTP client or specific methods.
Bearer¶
You need to configure an interceptor for Bearer authorization:
You will need to implement the Bearer token provisioning yourself using your custom HttpClientTokenProvider implementation,
or use a constructor that accepts a static Bearer Token.
public interface HttpClientTokenProvider {
CompletionStage<String> getToken(HttpClientRequest request);
}
Then add interceptor for the entire HTTP client or specific methods.
OAuth¶
Authorization by OAuth is similar to Bearer,
you need to implement HttpClientTokenProvider yourself and put it in dependency container.
HttpClientTokenProvider¶
HttpClientTokenProvider — interface for providing authorization tokens dynamically.
Used when the token needs to be refreshed or obtained from an external source (e.g., OAuth2 token endpoint).
Implementation example:
@Component
public class MyTokenProvider implements HttpClientTokenProvider {
private final OAuthClient oauthClient;
private volatile String cachedToken;
private volatile long tokenExpiry;
public MyTokenProvider(OAuthClient oauthClient) {
this.oauthClient = oauthClient;
}
@Override
public CompletionStage<String> getToken(HttpClientRequest request) {
if (cachedToken != null && System.currentTimeMillis() < tokenExpiry) {
return CompletableFuture.completedFuture(cachedToken);
}
// Get new token
return oauthClient.refreshToken()
.thenApply(response -> {
this.cachedToken = response.accessToken();
this.tokenExpiry = System.currentTimeMillis() + response.expiresIn() * 1000;
return this.cachedToken;
});
}
}
@Component
class MyTokenProvider(
private val oauthClient: OAuthClient
) : HttpClientTokenProvider {
private var cachedToken: String? = null
private var tokenExpiry: Long = 0
override fun getToken(request: HttpClientRequest): CompletionStage<String> {
if (cachedToken != null && System.currentTimeMillis() < tokenExpiry) {
return CompletableFuture.completedFuture(cachedToken)
}
// Get new token
return oauthClient.refreshToken()
.thenApply { response ->
cachedToken = response.accessToken()
tokenExpiry = System.currentTimeMillis() + response.expiresIn() * 1000
cachedToken!!
}
}
}
Usage with BearerAuthHttpClientInterceptor:
Exception handling¶
Various exceptions may occur during HTTP requests. All exceptions inherit from the base HttpClientException.
Exception hierarchy:
HttpClientException
├── HttpClientTimeoutException
├── HttpClientConnectionException
├── HttpClientResponseException
├── HttpClientEncoderException
├── HttpClientDecoderException
└── HttpClientUnknownException
Handling example:
@Component
class SomeService {
private final SomeClient client;
public SomeService(SomeClient client) {
this.client = client;
}
public void call() {
try {
client.hello();
} catch (HttpClientTimeoutException e) {
// Timeout: log, retry
} catch (HttpClientConnectionException e) {
// Connection error: check service availability
} catch (HttpClientResponseException e) {
// Response error: code, body, headers
int code = e.getCode();
byte[] body = e.getBytes();
} catch (HttpClientEncoderException e) {
// Serialization error: validate data
} catch (HttpClientDecoderException e) {
// Deserialization error: log
} catch (HttpClientUnknownException e) {
// Unknown error: e.getCause()
}
}
}
@Component
class SomeService(
private val client: SomeClient
) {
fun call() {
try {
client.hello()
} catch (e: HttpClientTimeoutException) {
// Timeout: log, retry
} catch (e: HttpClientConnectionException) {
// Connection error: check service availability
} catch (e: HttpClientResponseException) {
// Response error: code, body, headers
val code = e.code
val body = e.bytes
} catch (e: HttpClientEncoderException) {
// Serialization error: validate data
} catch (e: HttpClientDecoderException) {
// Deserialization error: log
} catch (e: HttpClientUnknownException) {
// Unknown error: e.cause
}
}
}
Timeout Exception¶
Thrown when the request exceeds the configured timeout (requestTimeout or connectTimeout).
Causes:
- Server doesn't respond within requestTimeout
- Connection establishment timeout exceeded (connectTimeout)
- Network delays
Recommendations: - Configure appropriate timeouts in settings - Implement retry logic for temporary failures - Use circuit breaker to protect against cascading failures
Connection Exception¶
Thrown when connection to the server cannot be established.
Causes: - DNS resolution failure - Server unavailable (port closed, firewall) - Connection refused - SSL/TLS handshake failed
Recommendations: - Check service availability (health check) - Use fallback to backup service - Configure retry with exponential backoff
Response Exception¶
Thrown when the server returns an HTTP error status code (4xx or 5xx) and no custom mapper is specified via @ResponseCodeMapper.
Available data:
- getCode() — HTTP status code (400, 404, 500, etc.)
- getBytes() — response body as byte[] (may contain error details)
- getHeaders() — response headers
Recommendations:
- Use @ResponseCodeMapper for custom status handling
- Log statusCode and body for debugging
- Distinguish between client (4xx) and server (5xx) errors
Request Encoder Exception¶
Thrown when an error occurs during request body serialization.
Causes: - JSON/XML serialization error - Invalid data in request object - Missing serializer for type
Recommendations:
- Validate data before sending
- Check for Json annotations on classes
- Log original exception in cause
Response Decoder Exception¶
Thrown when an error occurs during response body deserialization.
Causes: - Invalid JSON/XML in server response - Schema mismatch (server returned unexpected fields) - Missing deserializer for type
Recommendations:
- Check API version compatibility
- Log response body for debugging
- Use @ResponseCodeMapper for format error handling
Unknown Exception¶
Thrown when an unknown error occurs that doesn't fit other categories.
Available data:
- cause — original exception
Recommendations:
- Always log cause for diagnostics
- Check HTTP client logs at DEBUG/TRACE level
- Report bug if exception is reproducible
Resilience¶
The recommendations above (retry, circuit breaker, timeout, fallback) are provided by the Resilient module rather than the HTTP client itself.
Its annotations apply directly to declarative @HttpClient methods, so you can add fault tolerance without changing the call sites:
@Retry— retry the call on failure@CircuitBreaker— stop calling a failing dependency and fail fast until it recovers@Timeout— bound the total call time@Fallback— return a fallback result when the call fails
Note the difference from the transport requestTimeout (Client Configuration): requestTimeout bounds a single HTTP attempt,
while @Timeout bounds the whole method call including retries. See the Resilient module for the configuration and semantics of each annotation.
Client imperative¶
The base client represents the HttpClient interface and is available for deployment:
public interface HttpClient {
CompletionStage<HttpClientResponse> execute(HttpClientRequest request); //(1)!
HttpClient with(HttpClientInterceptor interceptor); //(2)!
}
- Method of request execution
- A method that allows you to add various interceptors manually
Requests are built manually with HttpClientRequest.of(...) (see HttpClientRequestBuilder below)
and executed through execute, which returns a CompletionStage<HttpClientResponse>.
HttpClientRequestBuilder¶
HttpClientRequestBuilder allows building HTTP requests manually and is obtained via HttpClientRequest.of(method, uri).
UriQueryBuilder¶
UriQueryBuilder helps build URIs with query parameters.
HttpBodyInput¶
HttpBodyInput is an interface that describes an incoming HTTP body (the response body on the client, obtained via response.body())
as a data stream (Flow.Publisher<ByteBuffer>). Used for streaming large data without loading it fully into memory,
or read eagerly through the helper methods below.
Methods:
| Method | Returns | Description |
|---|---|---|
asInputStream() |
InputStream |
Represents body as InputStream for reading |
asBufferStage() |
CompletionStage<ByteBuffer> |
Asynchronously reads entire body to ByteBuffer |
asArrayStage() |
CompletionStage<byte[]> |
Asynchronously reads entire body to byte[] |
HttpClientResponse¶
HttpClientResponse is an interface that represents HTTP response from server. It extends Closeable, so it must be
closed once the body has been read (declarative clients and mappers do this automatically).
Methods:
| Method | Returns | Description |
|---|---|---|
code() |
int |
HTTP status code (200, 404, 500, etc.) |
body() |
HttpBodyInput |
Response body as a readable stream (see HttpBodyInput) |
headers() |
HttpHeaders |
Response headers |
close() |
void |
Releases the response and underlying connection |
There is no dedicated cookies accessor on the client response — read the Set-Cookie values from headers().
HttpHeaders¶
HttpHeaders provides access to request and response headers in the imperative client.
Reading headers:
HttpClientRequest request = HttpClientRequest.of("GET", "http://localhost:8090/api/data")
.build();
httpClient.execute(request).thenAccept(response -> {
HttpHeaders headers = response.headers();
String contentType = headers.getFirst("Content-Type");
List<String> allValues = headers.get("X-Custom-Header");
boolean hasHeader = headers.contains("Authorization");
});
val request = HttpClientRequest.of("GET", "http://localhost:8090/api/data").build()
httpClient.execute(request).thenAccept { response ->
val headers = response.headers()
val contentType = headers.getFirst("Content-Type")
val allValues = headers.get("X-Custom-Header")
val hasHeader = headers.contains("Authorization")
}
Adding headers:
MutableHttpHeaders headers = new MutableHttpHeaders();
headers.add("Authorization", "Bearer token123");
headers.add("X-Custom-Header", "value");
headers.set("Content-Type", "application/json");
HttpClientRequest request = HttpClientRequest.of("POST", "http://localhost:8090/api/data")
.headers(headers)
.body(HttpBody.plaintext("body"))
.build();
httpClient.execute(request);
val headers = MutableHttpHeaders()
headers.add("Authorization", "Bearer token123")
headers.add("X-Custom-Header", "value")
headers.set("Content-Type", "application/json")
val request = HttpClientRequest.of("POST", "http://localhost:8090/api/data")
.headers(headers)
.body(HttpBody.plaintext("body"))
.build()
httpClient.execute(request)
Cookies¶
The imperative HttpClientResponse does not expose a dedicated cookies accessor — response cookies are read from the
Set-Cookie response headers via headers(). On the request side, a cookie can be added as the Cookie header.
Reading response cookies:
HttpClientRequest request = HttpClientRequest.of("GET", "http://localhost:8090/api/profile")
.build();
httpClient.execute(request).thenAccept(response -> {
List<String> setCookies = response.headers().get("set-cookie"); //(1)!
if (setCookies != null) {
for (String setCookie : setCookies) {
// e.g. "SESSIONID=abc123; Path=/; HttpOnly"
}
}
});
- Header names are matched case-insensitively
val request = HttpClientRequest.of("GET", "http://localhost:8090/api/profile").build()
httpClient.execute(request).thenAccept { response ->
val setCookies = response.headers().get("set-cookie") //(1)!
setCookies?.forEach { setCookie ->
// e.g. "SESSIONID=abc123; Path=/; HttpOnly"
}
}
- Header names are matched case-insensitively
Sending a request cookie:
Telemetry¶
HTTP Client uses a telemetry contract for logging, metrics, and tracing of requests.
Telemetry configuration (section telemetry { logging / metrics / tracing }) is described in the Configuration section.
Extension points are located in ru.tinkoff.kora.http.client.common.telemetry.
For each HTTP request, an HttpClientTelemetry.HttpClientTelemetryContext is created, which is closed upon request completion.
The request is described through telemetry handler parameters, including method, URL, response status, and duration.
The default factory DefaultHttpClientTelemetryFactory combines three factories:
- HttpClientLoggerFactory builds HttpClientLogger for logging request start/end;
- HttpClientMetricsFactory builds HttpClientMetrics for writing request metrics;
- HttpClientTracerFactory builds HttpClientTracer for distributed tracing.
Metrics and tracing are described in the Metrics Reference section.
Logging¶
Client logging is written through SLF4J under two loggers named after the client: <clientName>.request and <clientName>.response
(where <clientName> is derived from the @HttpClient interface). Enabling logging in the configuration
(telemetry.logging.enabled = true) turns the telemetry on, but what is written is governed by the log level of those loggers,
so you tune verbosity from your logging framework (logback, etc.):
| Log level | What is logged |
|---|---|
INFO |
Request start and response end line: method, path template, response status, result code, and duration |
DEBUG |
Additionally request and response headers |
TRACE |
Additionally request and response bodies, and the full (non-templated) path |
The configuration fields shape the output (see Configuration for the full list):
pathTemplate— whentrue(default), the low-cardinality route template (/users/{id}) is logged and used as the metric/trace label instead of the resolved path (/users/42); atTRACEthe resolved path is loggedmaskHeaders— header names whose values are replaced withmask(default masksauthorization,cookie,set-cookie)maskQueries— query parameter names whose values are replaced withmaskmask— the replacement string (default***)
For a client whose interface produces the name someClient, enable full body logging with:
<logger name="someClient.request" level="TRACE"/>
<logger name="someClient.response" level="TRACE"/>
Custom logger¶
To fully control the log format or destination, provide your own HttpClientLoggerFactory (or HttpClientLogger) component — it replaces
the default Sl4fjHttpClientLoggerFactory. The same applies to metrics (HttpClientMetricsFactory) and tracing (HttpClientTracerFactory):
supplying any of these components overrides the corresponding default, while the others keep their default implementation.
@Component
public final class MyHttpClientLoggerFactory implements HttpClientLoggerFactory {
@Override
public HttpClientLogger get(TelemetryConfig.LogConfig logging, String clientName) {
return new MyHttpClientLogger(clientName); //(1)!
}
}
- Your
HttpClientLoggerimplementation controlling exactly what and how to log