TL;DR
- Retrofit is JVM-only. It's built on OkHttp and Java reflection, so it can't run in
commonMainor on iOS. - Ktor Client is multiplatform. You write requests once, and each platform plugs in its own engine: OkHttp on Android, Darwin on iOS.
- Almost every Retrofit concept has a direct Ktor equivalent. It's a translation, not a rewrite of how you think.
- You can migrate gradually behind an interface, and you don't have to switch at all if your app is Android-only.
Retrofit has been the default on Android for a decade, and for good reason. But the moment you move your networking into a Kotlin Multiplatform module, it stops compiling. Here's why, and what changes when you switch to Ktor Client.
Prefer video?Ktor Client in a real multi-module KMP app: Gamopedia
01 Why Retrofit can't follow you to iOS
Retrofit works by reading your annotated interface at runtime and generating an implementation using Java's dynamic proxies. Underneath, requests go through OkHttp. Both of those live on the JVM.
Your shared KMP code, though, also compiles to native iOS binaries, where there is no JVM, no Java reflection and no OkHttp.
So anything in commonMain can only depend on libraries that are themselves multiplatform.
02 The same API, side by side
Here's a typical games API in both libraries. Switch tabs to compare.
interface GameApi {
@GET("games")
suspend fun games(@Query("page") page: Int): GamesResponse
@GET("games/{id}")
suspend fun game(@Path("id") id: Int): GameDto
}
val api: GameApi = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(okHttpClient)
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
.create(GameApi::class.java)
class GameApi(private val client: HttpClient) {
suspend fun games(page: Int): GamesResponse =
client.get("games") { parameter("page", page) }.body()
suspend fun game(id: Int): GameDto =
client.get("games/$id").body()
}
val client = HttpClient {
install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }
defaultRequest { url("https://api.example.com/") }
expectSuccess = true // throw on 4xx / 5xx, like Retrofit's HttpException
}
The biggest mindset shift: Retrofit is declarative (annotations describe a request), while Ktor is imperative (you build the request in code). It's slightly more typing, but there's no magic, and everything is plain Kotlin you can step through in a debugger.
03 The translation cheat sheet
| Retrofit / OkHttp | Ktor Client |
|---|---|
@GET("path") | client.get("path") |
@Query("page") | parameter("page", page) |
@Path("id") | String template: "games/$id" |
@Body | setBody(dto) + contentType(ContentType.Application.Json) |
@Header | header("X-Key", value), or defaultRequest for every call |
| Converter factory | ContentNegotiation plugin |
| OkHttp interceptor | A plugin: Logging, DefaultRequest, or your own with createClientPlugin |
OkHttp Authenticator | Auth plugin with bearer { refreshTokens { } } |
| Timeouts | HttpTimeout plugin |
Response<T> | HttpResponse (status, headers, then .body<T>()) |
HttpException | ClientRequestException (4xx) / ServerResponseException (5xx) when expectSuccess = true |
04 Engines and dependencies
Put the core and plugins in commonMain, and one engine per platform in its own source set.
When there's exactly one engine on the classpath, HttpClient { } picks it up automatically.
kotlin {
sourceSets {
commonMain.dependencies {
implementation("io.ktor:ktor-client-core:$ktor")
implementation("io.ktor:ktor-client-content-negotiation:$ktor")
implementation("io.ktor:ktor-client-logging:$ktor")
implementation("io.ktor:ktor-client-auth:$ktor")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor")
}
androidMain.dependencies {
implementation("io.ktor:ktor-client-okhttp:$ktor") // keep using OkHttp on Android
}
iosMain.dependencies {
implementation("io.ktor:ktor-client-darwin:$ktor") // NSURLSession under the hood
}
commonTest.dependencies {
implementation("io.ktor:ktor-client-mock:$ktor")
}
}
}
On Android, Ktor can run on OkHttp, so you keep its connection pooling and HTTP/2 support. You're changing the API you write, not the HTTP stack underneath.
05 Interceptors and token refresh
In Retrofit land, you'd write an OkHttp interceptor to add the token and an Authenticator to refresh it.
Ktor's Auth plugin handles both, and it works on every platform.
fun createHttpClient(tokens: TokenStore) = HttpClient {
install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }
install(Logging) { level = LogLevel.INFO }
install(HttpTimeout) { requestTimeoutMillis = 15_000 }
defaultRequest { url("https://api.example.com/") }
expectSuccess = true
install(Auth) {
bearer {
loadTokens {
tokens.load()?.let { BearerTokens(it.access, it.refresh) }
}
refreshTokens {
val fresh: TokenResponse = client.post("auth/refresh") {
markAsRefreshTokenRequest()
contentType(ContentType.Application.Json)
setBody(RefreshRequest(oldTokens?.refreshToken.orEmpty()))
}.body()
tokens.save(fresh)
BearerTokens(fresh.access, fresh.refresh)
}
}
}
}
When a request comes back 401, Ktor calls refreshTokens once and retries the original request with the new token.
06 Migrate without a big-bang rewrite
You don't need to switch everything in one PR. Put an interface in front of your networking and swap the implementation behind it.
- Move your DTOs to
commonMainand make them@Serializable. Retrofit can keep using them through its kotlinx.serialization converter. - Define a data-source interface that the rest of your app depends on, instead of the Retrofit interface itself.
- Add a Ktor implementation next to the Retrofit one, and switch them in your DI module, one endpoint group at a time.
- Delete Retrofit once nothing uses it.
interface GameRemoteDataSource {
suspend fun games(page: Int): GamesResponse
suspend fun game(id: Int): GameDto
}
// androidMain: the old one, kept during the migration
class RetrofitGameDataSource(private val api: RetrofitGameApi) : GameRemoteDataSource {
override suspend fun games(page: Int) = api.games(page)
override suspend fun game(id: Int) = api.game(id)
}
// commonMain: the new one, shared with iOS
class KtorGameDataSource(private val client: HttpClient) : GameRemoteDataSource {
override suspend fun games(page: Int): GamesResponse =
client.get("games") { parameter("page", page) }.body()
override suspend fun game(id: Int): GameDto =
client.get("games/$id").body()
}
07 Bonus: testing gets easier
With Retrofit you'd usually spin up a MockWebServer. Ktor ships a MockEngine: you hand it a lambda
that returns fake responses, and your tests run in commonTest on every platform.
class KtorGameDataSourceTest {
@Test
fun parsesGame() = runTest {
val engine = MockEngine { request ->
assertEquals("/games/42", request.url.encodedPath)
respond(
content = """{"id":42,"name":"Hollow Knight"}""",
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
val client = HttpClient(engine) {
install(ContentNegotiation) { json() }
defaultRequest { url("https://api.example.com/") }
}
val game = KtorGameDataSource(client).game(42)
assertEquals("Hollow Knight", game.name)
}
}
08 So, should you switch?
Keep Retrofit
Your app is Android-only with no plans for iOS or Desktop. Retrofit is mature and great. Don't switch just to switch.
Migrate gradually
You're starting to share code with iOS. Put an interface in front, then move endpoints over one group at a time.
Start with Ktor
You're building a new multiplatform app. Use Ktor Client from day one, and share networking everywhere.
See it in a real project
Compose Multiplatform: Build Gamopedia
Use Ktor Client, Koin and SQLDelight in a real multi-module KMP app that runs on Android, iOS and Desktop.
