Ecosystem

Migrate from Axios to Ktor Client in Kotlin Multiplatform

Move an Axios request to Ktor Client in Kotlin Multiplatform and check JSON, authentication, and error handling before switching.

On this page

Ktor Client can run shared HTTP requests in a Kotlin Multiplatform module. A small first step is to move one read request and preserve what its caller sees. Keep the existing React Native implementation available while you compare both paths.

The same JSON request#

In an Axios app, a configured client might fetch a record and return its response body:

ts
type Item = { id: string; title: string };

export async function fetchItem(id: string): Promise<Item> {
  const { data } = await api.get<Item>("/items/" + encodeURIComponent(id));
  return data;
}

With a configured Ktor client, a suspending function can perform the same request:

kotlin
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.http.encodeURLPathPart
import kotlinx.serialization.Serializable

@Serializable
data class Item(val id: String, val title: String)

class ItemsApi(private val client: HttpClient) {
    suspend fun fetchItem(id: String): Item =
        client.get("items/${id.encodeURLPathPart()}").body()
}

Configure the client's base URL, install JSON content negotiation with a serializer, and select an engine for each target. The Kotlin snippet assumes the base URL is the same API scope as in Axios and that its path ends in a slash. See Ktor Client setup, default requests and JSON serialization.

Preserve the behaviour your app depends on#

  • Authentication. Carry over the token and refresh behaviour your app needs. Decide which side owns the session while both clients are in use. See Ktor bearer authentication.
  • Errors. Axios and Ktor have different defaults. With Ktor, configure expectSuccess or check the response status explicitly. Map a missing item, a failed refresh and an unreadable response to the same outcomes the screen already handles. See Ktor response validation.
  • Timeouts and cancellation. Check the offline and slow-network cases, and verify what happens when a user leaves the screen during a request.
  • Tests. Compare both clients with the same successful response, an expired token, a missing item and a server error. Include an ID with reserved characters if your API accepts them.

Once the shared request behaves as expected, call it from the Kotlin screen or expose an eligible Kotlin function to the existing React Native screen. See the RN2KMP annotations and types for what can cross the bridge.

See all library alternatives