CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor-client-core-iosx64

Ktor HTTP client core library - asynchronous framework for creating HTTP clients in Kotlin multiplatform

Pending
Overview
Eval results
Files

request-building.mddocs/

Request Building

Type-safe DSL for building and executing HTTP requests with all standard HTTP methods, URL configuration, headers, and body content.

Capabilities

Generic Request Functions

Core request building and execution functions supporting all HTTP methods.

/**
 * Executes an HttpClient's request with the parameters specified using builder.
 */
suspend fun HttpClient.request(
    builder: HttpRequestBuilder = HttpRequestBuilder()
): HttpResponse

/**
 * Executes an HttpClient's request with the parameters specified in block.
 */
suspend fun HttpClient.request(block: HttpRequestBuilder.() -> Unit): HttpResponse

/**
 * Executes an HttpClient's request with the urlString and the parameters configured in block.
 */
suspend fun HttpClient.request(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse

/**
 * Executes an HttpClient's request with the url and the parameters configured in block.
 */
suspend fun HttpClient.request(
    url: Url,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse

/**
 * Prepares an HttpClient's request with the parameters specified using builder.
 */
suspend fun HttpClient.prepareRequest(
    builder: HttpRequestBuilder = HttpRequestBuilder()
): HttpStatement

/**
 * Prepares an HttpClient's request with the parameters specified using block.
 */
suspend fun HttpClient.prepareRequest(block: HttpRequestBuilder.() -> Unit): HttpStatement

Usage Examples:

import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.http.*

val client = HttpClient()

// Using builder
val builder = HttpRequestBuilder().apply {
    method = HttpMethod.Get
    url("https://api.example.com/users")
    headers["Authorization"] = "Bearer token"
}
val response1 = client.request(builder)

// Using DSL block
val response2 = client.request {
    method = HttpMethod.Post
    url("https://api.example.com/users")
    contentType(ContentType.Application.Json)
    setBody("""{"name": "John"}""")
}

// Using URL string
val response3 = client.request("https://api.example.com/users") {
    method = HttpMethod.Get
    headers["Accept"] = "application/json"
}

// Prepared request (reusable)
val statement = client.prepareRequest {
    method = HttpMethod.Get
    url("https://api.example.com/users/{id}")
}

HTTP Method Convenience Functions

Convenience functions for all standard HTTP methods with multiple overloads.

// GET requests
suspend fun HttpClient.get(builder: HttpRequestBuilder): HttpResponse
suspend fun HttpClient.get(block: HttpRequestBuilder.() -> Unit): HttpResponse
suspend fun HttpClient.get(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse

// POST requests
suspend fun HttpClient.post(builder: HttpRequestBuilder): HttpResponse
suspend fun HttpClient.post(block: HttpRequestBuilder.() -> Unit): HttpResponse
suspend fun HttpClient.post(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse

// PUT requests
suspend fun HttpClient.put(builder: HttpRequestBuilder): HttpResponse
suspend fun HttpClient.put(block: HttpRequestBuilder.() -> Unit): HttpResponse
suspend fun HttpClient.put(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse

// DELETE requests
suspend fun HttpClient.delete(builder: HttpRequestBuilder): HttpResponse
suspend fun HttpClient.delete(block: HttpRequestBuilder.() -> Unit): HttpResponse
suspend fun HttpClient.delete(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse

// PATCH requests
suspend fun HttpClient.patch(builder: HttpRequestBuilder): HttpResponse
suspend fun HttpClient.patch(block: HttpRequestBuilder.() -> Unit): HttpResponse
suspend fun HttpClient.patch(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse

// HEAD requests
suspend fun HttpClient.head(builder: HttpRequestBuilder): HttpResponse
suspend fun HttpClient.head(block: HttpRequestBuilder.() -> Unit): HttpResponse
suspend fun HttpClient.head(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse

// OPTIONS requests
suspend fun HttpClient.options(builder: HttpRequestBuilder): HttpResponse
suspend fun HttpClient.options(block: HttpRequestBuilder.() -> Unit): HttpResponse
suspend fun HttpClient.options(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse

Usage Examples:

// Simple GET request
val response = client.get("https://api.example.com/users")

// POST with JSON body
val postResponse = client.post("https://api.example.com/users") {
    contentType(ContentType.Application.Json)
    setBody("""{"name": "Alice", "email": "alice@example.com"}""")
}

// PUT with custom headers
val putResponse = client.put("https://api.example.com/users/123") {
    headers {
        append(HttpHeaders.Authorization, "Bearer $token")
        append(HttpHeaders.Accept, "application/json")
    }
    contentType(ContentType.Application.Json)
    setBody(userData)
}

// DELETE request
val deleteResponse = client.delete("https://api.example.com/users/123") {
    headers["Authorization"] = "Bearer $token"
}

Prepared Request Functions

Functions for creating reusable prepared requests for all HTTP methods.

// Prepared requests for all HTTP methods
suspend fun HttpClient.prepareGet(builder: HttpRequestBuilder): HttpStatement
suspend fun HttpClient.prepareGet(block: HttpRequestBuilder.() -> Unit): HttpStatement
suspend fun HttpClient.prepareGet(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpStatement

suspend fun HttpClient.preparePost(builder: HttpRequestBuilder): HttpStatement
suspend fun HttpClient.preparePost(block: HttpRequestBuilder.() -> Unit): HttpStatement
suspend fun HttpClient.preparePost(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): HttpStatement

// Similar patterns for PUT, DELETE, PATCH, HEAD, OPTIONS
suspend fun HttpClient.preparePut(builder: HttpRequestBuilder): HttpStatement
suspend fun HttpClient.prepareDelete(builder: HttpRequestBuilder): HttpStatement
suspend fun HttpClient.preparePatch(builder: HttpRequestBuilder): HttpStatement
suspend fun HttpClient.prepareHead(builder: HttpRequestBuilder): HttpStatement
suspend fun HttpClient.prepareOptions(builder: HttpRequestBuilder): HttpStatement

Usage Examples:

// Prepare reusable requests
val getUserStatement = client.prepareGet("https://api.example.com/users/{id}")
val updateUserStatement = client.preparePut("https://api.example.com/users/{id}") {
    contentType(ContentType.Application.Json)
}

// Execute prepared requests multiple times
val user1 = getUserStatement.execute { response ->
    // Process response
    response.bodyAsText()
}

val user2 = getUserStatement.execute { response ->
    // Different processing
    response.body<User>()
}

HttpRequestBuilder Class

Mutable request configuration builder with DSL support for all request parameters.

/**
 * HttpRequestBuilder is used to build HttpRequest instances
 */
class HttpRequestBuilder {
    /** URL configuration */
    var url: URLBuilder
    
    /** HTTP method (GET by default) */
    var method: HttpMethod = HttpMethod.Get
    
    /** Headers configuration */
    var headers: HeadersBuilder
    
    /** Request body content */
    var body: Any = EmptyContent
    
    /** Body type information for serialization */
    var bodyType: TypeInfo?
    
    /** Execution context for cancellation */
    var executionContext: Job
    
    /** Request-specific attributes */
    var attributes: Attributes
    
    /**
     * Configure URL using URLBuilder DSL
     */
    fun url(block: URLBuilder.(URLBuilder) -> Unit)
    
    /**
     * Set URL from string
     */
    fun url(urlString: String)
    
    /**
     * Set URL from Url object
     */
    fun url(url: Url)
    
    /**
     * Build immutable HttpRequestData
     */
    fun build(): HttpRequestData
    
    /**
     * Configure attributes
     */
    fun setAttributes(block: Attributes.() -> Unit)
    
    /**
     * Copy configuration from another builder
     */
    fun takeFrom(builder: HttpRequestBuilder): HttpRequestBuilder
    
    /**
     * Set engine capability
     */
    fun <T> setCapability(key: HttpClientEngineCapability<T>, capability: T)
    
    /**
     * Get engine capability
     */
    fun <T> getCapabilityOrNull(key: HttpClientEngineCapability<T>): T?
}

Usage Examples:

import io.ktor.client.request.*
import io.ktor.http.*

// Build request step by step
val builder = HttpRequestBuilder().apply {
    method = HttpMethod.Post
    url("https://api.example.com/users")
    
    // Configure headers
    headers {
        append(HttpHeaders.ContentType, "application/json")
        append(HttpHeaders.Authorization, "Bearer $token")
    }
    
    // Set body
    setBody("""{"name": "John", "email": "john@example.com"}""")
    
    // Configure attributes
    attributes.put(AttributeKey("RequestId"), "req-123")
}

// URL configuration
builder.url {
    protocol = URLProtocol.HTTPS
    host = "api.example.com"
    port = 443
    path("users", "create")
    parameters.append("format", "json")
}

// Build immutable request data
val requestData = builder.build()

HttpRequestData Class

Immutable request data representing a fully configured HTTP request.

/**
 * Immutable HTTP request data
 */
data class HttpRequestData(
    val url: Url,
    val method: HttpMethod,
    val headers: Headers,
    val body: OutgoingContent,
    val executionContext: Job,
    val attributes: Attributes
)

Request Builder Utility Functions

Additional utility functions for creating and configuring request builders.

/**
 * Creates an HttpRequestBuilder and configures it using block.
 */
fun request(block: HttpRequestBuilder.() -> Unit): HttpRequestBuilder

Usage Examples:

// Create configured builder
val builder = request {
    method = HttpMethod.Get
    url("https://api.example.com/users")
    headers["Accept"] = "application/json"
}

// Use with client
val response = client.request(builder)

URL Configuration

Comprehensive URL building capabilities with type-safe DSL.

/**
 * Configure URL using URLBuilder DSL
 */
fun HttpRequestBuilder.url(block: URLBuilder.() -> Unit)

/**
 * Set URL from string
 */
fun HttpRequestBuilder.url(urlString: String)

/**
 * Set URL from Url object  
 */
fun HttpRequestBuilder.url(url: Url)

/**
 * Configure URL with individual components
 */
fun HttpRequestBuilder.url(
    scheme: String = "http",
    host: String = "localhost", 
    port: Int = DEFAULT_PORT,
    path: String = "/",
    block: URLBuilder.() -> Unit = {}
)

Usage Examples:

// URL from string
client.get("https://api.example.com/users/123")

// URL with DSL
client.get {
    url {
        protocol = URLProtocol.HTTPS
        host = "api.example.com"
        port = 443
        path("users", "123")
        parameters {
            append("include", "profile")
            append("format", "json")
        }
        fragment = "details"
    }
}

// URL with components
client.get {
    url(
        scheme = "https",
        host = "api.example.com",
        port = 443,
        path = "/users/123"
    ) {
        parameters.append("include", "profile")
    }
}

Headers Configuration

Type-safe header configuration with builder pattern.

/**
 * Configure headers using HeadersBuilder DSL
 */
fun HttpRequestBuilder.headers(block: HeadersBuilder.() -> Unit): HeadersBuilder

/**
 * Set content type header
 */
fun HttpRequestBuilder.contentType(contentType: ContentType)

/**
 * Set accept header
 */
fun HttpRequestBuilder.accept(contentType: ContentType)

/**
 * Set user agent header
 */
fun HttpRequestBuilder.userAgent(userAgent: String)

Usage Examples:

client.post("https://api.example.com/users") {
    // Content type shortcut
    contentType(ContentType.Application.Json)
    
    // Accept header
    accept(ContentType.Application.Json)
    
    // Custom headers
    headers {
        append(HttpHeaders.Authorization, "Bearer $token")
        append(HttpHeaders.UserAgent, "MyApp/1.0")
        append("X-Custom-Header", "value")
    }
    
    setBody(userData)
}

Request Body Configuration

Flexible request body configuration supporting various content types.

/**
 * Set request body content
 */
fun HttpRequestBuilder.setBody(body: Any)

/**
 * Set typed request body with type information
 */
fun HttpRequestBuilder.setBody(body: Any, bodyType: TypeInfo)

Usage Examples:

// String body
client.post("https://api.example.com/users") {
    contentType(ContentType.Application.Json)
    setBody("""{"name": "John"}""")
}

// Object body (requires serialization plugin)
client.post("https://api.example.com/users") {
    contentType(ContentType.Application.Json)
    setBody(User(name = "John", email = "john@example.com"))
}

// ByteArray body
client.post("https://api.example.com/upload") {
    contentType(ContentType.Image.PNG)
    setBody(imageBytes)
}

// Form data
client.post("https://api.example.com/form") {
    setBody(FormDataContent(Parameters.build {
        append("name", "John")
        append("email", "john@example.com")
    }))
}

Install with Tessl CLI

npx tessl i tessl/maven-io-ktor--ktor-client-core-iosx64

docs

client-configuration.md

cookie-management.md

engine-configuration.md

form-handling.md

http-caching.md

index.md

plugin-system.md

request-building.md

response-handling.md

websocket-support.md

tile.json