HTTP interceptors - AWS SDK for Kotlin

HTTP interceptors

You can use interceptors to hook into the execution of API requests and responses. Interceptors are open-ended mechanisms in which the SDK calls code that you write to inject behavior into the request/response lifecycle. This way, you can modify an in-flight request, debug request processing, view exceptions, and more.

The following example shows a simple interceptor that adds an additional header to all outgoing requests before the retry loop is entered.

class AddHeader( private val key: String, private val value: String ) : HttpInterceptor { override suspend fun modifyBeforeRetryLoop(context: ProtocolRequestInterceptorContext<Any, HttpRequest>): HttpRequest { val httpReqBuilder = context.protocolRequest.toBuilder() httpReqBuilder.headers[key] = value return } }

For more information and the available interception hooks, see the Interceptor interface.

Interceptor registration

You register interceptors when you construct a service client or when you override configuration for a specific set of operations.

Interceptor for all service client operations

The following code adds an AddHeader instance to the interceptors property of the builder. This addition adds the x-foo-version header to all operations before the retry loop is entered.

val s3 = S3Client.fromEnvironment { interceptors += AddHeader("x-foo-version", "1.0") } // All service operations invoked using 's3' will have the header appended. s3.listBuckets { ... } s3.listObjectsV2 { ... }

Interceptor for only specific operations

By using the withConfig extension, you can override service client configuration for one or more operations for any service client. With this capability, you can register additional interceptors for a subset of operations.

The following example overrides the configuration of the s3 instance for operations within the use extension. Operations called on s3Scoped contain both the x-foo-version and the x-bar-version headers.

// 's3' instance created in the previous code snippet. s3.withConfig { interceptors += AddHeader("x-bar-version", "3.7") }.use { s3Scoped -> // All service operations invoked using 's3Scoped' trigger interceptors // that were registered when the client was created and any added in the // withConfig { ... } extension. }