Retrofit vs. Ktor: Choosing the Right Network Client

Kostadin Georgiev
3 min readFeb 29, 2024

--

Modern Android development often centers around interaction with remote APIs. Network libraries are essential tools for handling HTTP requests, parsing responses, and managing API communication efficiently. In the realm of Kotlin-based Android development, Retrofit and Ktor have emerged as two powerful and popular network client options. This article will delve into the strengths, weaknesses, and ideal use cases for both Retrofit and Ktor to help you make an informed decision.

Note: The real professionals are using HttpUrlConnection class 😀

Retrofit: The Seasoned Veteran

Retrofit, backed by Square, is a type-safe HTTP client for Android and Java. It relies on annotations to streamline the process of defining API endpoints and their corresponding HTTP methods. Retrofit’s core advantages include:

  • Maturity and Reliability: Retrofit boasts a large community and extensive documentation, offering robust support and proven reliability.
  • Annotation-driven Approach: Easy definition of API endpoints and request methods.
  • Strong Type Safety: Minimizes the risk of runtime errors through type-safety.

Code Sample (Retrofit):

Kotlin

interface ApiService {
@GET("users")
suspend fun getUsers(): List<User>
}
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(ApiService::class.java

Attaching Auth Header to All Requests

  1. Create an Interceptor: Implement the Interceptor interface to modify requests before they are sent.
  2. Add Authorization Header: Within the intercept method, retrieve the auth token (stored securely) and add it as an "Authorization" header to the request.

Kotlin

val authInterceptor = Interceptor { chain ->
val request = chain.request()
val token = // retrieve auth token from secure storage
    if (token != null) {
val newRequest = request.newBuilder()
.addHeader("Authorization", "Bearer $token")
.build()
chain.proceed(newRequest)
} else {
chain.proceed(request)
}
}
val retrofit = Retrofit.Builder()
// ... other configurations
.client(OkHttpClient.Builder().addInterceptor(authInterceptor).build()).build()

Ktor: The Modern, Coroutine-Based Champion

Ktor, created by JetBrains, is a multiplatform asynchronous framework for building connected applications. It leverages Kotlin coroutines for exceptional concurrency management, making it a great fit within Kotlin’s ecosystem. Key advantages of Ktor include:

  • Coroutines-First: Smooth integration with coroutines for efficient asynchronous operations.
  • Multiplatform Capabilities: Create networking code usable across Android, iOS, backend applications, and more.
  • Flexibility: Ktor offers granular control and modular design through various plugins and features.

Code Sample (Ktor):

Kotlin

val httpClient = HttpClient(CIO) {
install(JsonFeature) {
serializer = GsonSerializer()
}
}
suspend fun getUsers(): List<User> {
return httpClient.get("https://api.example.com/users")
}

Attaching Auth Header to All Requests

Install Feature and Configure Interceptor: Install the Auth feature and configure an interceptor within your Ktor client:

Kotlin

val httpClient = HttpClient(CIO) {
install(Auth) {
bearer {
credentials {
// Store and retrieve credentials securely
bearerAuth {
load { // Load token from secure storage }
}
}
}
}
}

Customize (Optional): You can further customize the interceptor behavior (e.g., adding the header only for specific routes) by implementing a custom HttpAuthHeader and attaching it to the client.

Comparison table

Conclusion

Both Retrofit and Ktor offer effective ways to handle network communication in your Android projects. Retrofit excels with its maturity, type safety, and established ecosystem, while Ktor shines with its coroutine-based approach, multiplatform capabilities, and flexibility. Ultimately, the choice depends on your project’s specific requirements, team preferences, and desired level of control over network requests. By understanding the strengths and weaknesses of each library, you can make an informed decision and leverage the power of either Retrofit or Ktor to build robust and efficient network interactions within your Android application.

--

--