Kotlin Multiplatform HTTP — Complete Guide
In this tutorial, you'll learn about Kotlin Multiplatform HTTP. We cover key concepts, practical examples, and best practices.
The Problem
Your KMP app can't make HTTP requests because the Ktor engine isn't configured for the target platform, or SSL handshake fails on iOS.
Wrong Approach ❌
// Using JVM-specific HTTP library in commonMain
// commonMain
val url = URL("https://api.example.com") // JVM-only!
Output: Compilation error on iOS.
Right Approach ✅
// build.gradle.kts
commonMain.dependencies {
implementation("io.ktor:ktor-client-core:2.3.12")
implementation("io.ktor:ktor-client-content-negotiation:2.3.12")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.12")
implementation("io.ktor:ktor-client-logging:2.3.12")
}
androidMain.dependencies {
implementation("io.ktor:ktor-client-okhttp:2.3.12")
}
iosMain.dependencies {
implementation("io.ktor:ktor-client-darwin:2.3.12")
}
// commonMain
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.serialization.kotlinx.json.*
// Create platform-specific engine via expect
expect fun createHttpEngine(): HttpClientEngine
// Or use HttpClient() which auto-selects engine per platform
val httpClient = HttpClient {
install(ContentNegotiation) {
json(Json { ignoreUnknownKeys = true })
}
install(HttpTimeout) {
requestTimeoutMillis = 15000
connectTimeoutMillis = 10000
}
install(Logging) {
level = LogLevel.HEADERS
}
defaultRequest {
url("https://api.example.com")
contentType(ContentType.Application.Json)
}
}
suspend fun getUsers(): List<User> {
return httpClient.get("/users").body()
}
suspend fun createUser(user: User): User {
return httpClient.post("/users") {
setBody(user)
}.body()
}
// androidMain
actual fun createHttpEngine(): HttpClientEngine = OkHttpEngine()
// iosMain
actual fun createHttpEngine(): HttpClientEngine = DarwinEngine()
Output: Cross-platform HTTP requests work on both Android and iOS.
Prevention
- Use Ktor Client with platform-specific engines.
- Install
ContentNegotiationwithkotlinx-serializationfor JSON. - Configure timeouts per platform.
- Use
defaultRequestfor base URL and common headers. - Handle platform-specific SSL configurations.
Common Mistakes with multiplatform http
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world KOTLIN code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro