Network requests with Retrofit, Kotlinx Serialization, and OkHttp interceptors.
Retrofit Setup
# Dependencies
implementation("com.squareup.retrofit2:retrofit:2.11.0")
implementation("com.squareup.retrofit2:converter-kotlinx-serialization:1.0.0")
implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0")
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")API Service Definition
@Serializable
data class User(
@SerialName("id") val id: String,
@SerialName("name") val name: String,
@SerialName("email") val email: String,
@SerialName("avatar_url") val avatarUrl: String?,
@SerialName("created_at") val createdAt: String
)
@Serializable
data class UserResponse(
val users: List<User>,
val total: Int,
val page: Int
)
@Serializable
data class CreateUserRequest(
val name: String,
val email: String
)
@Serializable
data class ApiError(
val code: Int,
val message: String,
val details: Map<String, List<String>>?
)
interface ApiService {
@GET("users")
suspend fun getUsers(
@Query("page") page: Int = 1,
@Query("limit") limit: Int = 20
): Result<UserResponse>
@GET("users/{id}")
suspend fun getUser(@Path("id") id: String): Result<User>
@POST("users")
suspend fun createUser(@Body request: CreateUserRequest): Result<User>
@PUT("users/{id}")
suspend fun updateUser(
@Path("id") id: String,
@Body request: CreateUserRequest
): Result<User>
@DELETE("users/{id}")
suspend fun deleteUser(@Path("id") id: String): Result<Unit>
@Multipart
@POST("users/{id}/avatar")
suspend fun uploadAvatar(
@Path("id") id: String,
@Part file: MultipartBody.Part
): Result<User>
}
// Result wrapper for error handling
sealed interface Result<out T> {
@Serializable
data class Success<T>(val data: T) : Result<T>
@Serializable
data class Failure(val error: ApiError) : Result<Nothing>
}
// Extension for easier handling
suspend fun <T> Result<T>.onSuccess(action: (T) -> Unit): Result<T> {
if (this is Success) action(data)
return this
}
suspend fun <T> Result<T>.onFailure(action: (ApiError) -> Unit): Result<T> {
if (this is Failure) action(error)
return this
}
suspend fun <T> Result<T>.getOrNull(): T? = if (this is Success) data else nullRetrofit Configuration
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideOkHttpClient(
@ApplicationContext context: Context,
authInterceptor: AuthInterceptor
): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG)
HttpLoggingInterceptor.Level.BODY
else
HttpLoggingInterceptor.Level.NONE
})
.addInterceptor(authInterceptor)
.addNetworkInterceptor(ConnectivityInterceptor(context))
.cache(Cache(context.cacheDir, 10 * 1024 * 1024)) // 10MB
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build()
}
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl("https://api.example.com/v1/")
.client(okHttpClient)
.addConverterFactory(KotlinxSerializationConverterFactory.create(
Json {
ignoreUnknownKeys = true
isLenient = true
encodeDefaults = false
prettyPrint = BuildConfig.DEBUG
}
))
.build()
}
@Provides
@Singleton
fun provideApiService(retrofit: Retrofit): ApiService {
return retrofit.create(ApiService::class.java)
}
}Interceptors
// Auth Interceptor - adds Bearer token
class AuthInterceptor @Inject constructor(
private val tokenManager: TokenManager
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val token = tokenManager.getAccessToken()
val request = if (token != null) {
chain.request().newBuilder()
.addHeader("Authorization", "Bearer $token")
.build()
} else {
chain.request()
}
return chain.proceed(request)
}
}
// Connectivity Interceptor - handles offline
class ConnectivityInterceptor @Inject constructor(
private val context: Context
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val connectivity = context.getSystemService(ConnectivityManager::class.java)
val network = connectivity.activeNetwork
if (network == null) {
// Return cached response if available
val request = chain.request()
val cacheControl = request.cacheControl
if (cacheControl.maxAgeSeconds != -1 || cacheControl.maxStaleSeconds != -1) {
val cacheResponse = chain.connection?.cache?.get(request)
cacheResponse?.let { return it }
}
throw UnknownHostException("No network connection")
}
return chain.proceed(chain.request())
}
}
// Retry Interceptor with exponential backoff
class RetryInterceptor(
private val maxRetries: Int = 3,
private val baseDelay: Long = 1000
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
var retries = 0
while (true) {
try {
val response = chain.proceed(request)
// Retry on 5xx errors
if (response.code in 500..599 && retries < maxRetries) {
retries++
Thread.sleep(baseDelay * (2.0.pow(retries - 1)).toLong())
request = request.newBuilder().build()
continue
}
return response
} catch (e: IOException) {
if (retries >= maxRetries) throw e
retries++
Thread.sleep(baseDelay * (2.0.pow(retries - 1)).toLong())
}
}
}
}Token Manager
class TokenManager @Inject constructor(
private val dataStore: DataStore<Preferences>
) {
companion object {
val ACCESS_TOKEN = stringPreferencesKey("access_token")
val REFRESH_TOKEN = stringPreferencesKey("refresh_token")
val TOKEN_EXPIRY = longPreferencesKey("token_expiry")
}
suspend fun saveTokens(access: String, refresh: String, expiresIn: Long) {
dataStore.edit {
it[ACCESS_TOKEN] = access
it[REFRESH_TOKEN] = refresh
it[TOKEN_EXPIRY] = System.currentTimeMillis() + expiresIn * 1000
}
}
fun getAccessToken(): String? = runBlocking {
dataStore.data.first()[ACCESS_TOKEN]
}
suspend fun getValidAccessToken(): String? {
val expiry = dataStore.data.first()[TOKEN_EXPIRY] ?: 0
if (System.currentTimeMillis() < expiry - 60000) { // 1 min buffer
return getAccessToken()
}
return refreshAccessToken()
}
private suspend fun refreshAccessToken(): String? {
val refreshToken = dataStore.data.first()[REFRESH_TOKEN] ?: return null
// Call refresh endpoint
// val response = apiService.refreshToken(refreshToken)
// if (response is Result.Success) { saveTokens(...); return response.data.accessToken }
return null
}
suspend fun clearTokens() {
dataStore.edit {
it.remove(ACCESS_TOKEN)
it.remove(REFRESH_TOKEN)
it.remove(TOKEN_EXPIRY)
}
}
}Repository with Error Handling
class UserRepositoryImpl @Inject constructor(
private val apiService: ApiService,
private val userDao: UserDao
) : UserRepository {
override fun getUsers(): Flow<Result<List<User>>> {
return userDao.getAllUsers()
.map { Result.Success(it.map { it.toDomain() }) }
.catch { emit(Result.Failure(ApiError(-1, it.message!!, null))) }
}
override suspend fun refreshUsers(): Result<Unit> {
return try {
val response = apiService.getUsers()
response.onSuccess { userResponse ->
val entities = userResponse.users.map { it.toEntity() }
userDao.insertAll(entities)
}.onFailure { error ->
return Result.Failure(error)
}
Result.Success(Unit)
} catch (e: Exception) {
Result.Failure(ApiError(-1, e.message!!, null))
}
}
override suspend fun getUser(id: String): Result<User> {
// Try local first
val local = userDao.getUser(id)
if (local != null) return Result.Success(local.toDomain())
// Fetch from network
return apiService.getUser(id).onSuccess { user ->
userDao.insert(user.toEntity())
}
}
}Testing with MockWebServer
@RunWith(AndroidJUnit4::class)
class ApiServiceTest {
@get:Rule
val mockWebServer = MockWebServer()
private lateinit var apiService: ApiService
@Before
fun setup() {
val retrofit = Retrofit.Builder()
.baseUrl(mockWebServer.url("/"))
.addConverterFactory(KotlinxSerializationConverterFactory.create(Json { ignoreUnknownKeys = true }))
.build()
apiService = retrofit.create(ApiService::class.java)
}
@After
fun teardown() {
mockWebServer.shutdown()
}
@Test
fun getUsers_returnsSuccess() = runTest {
// Given
val json = """
{"users":[{"id":"1","name":"John","email":"john@test.com","avatar_url":null,"created_at":"2024-01-01"}],"total":1,"page":1}
""".trimIndent()
mockWebServer.enqueue(MockResponse()
.setResponseCode(200)
.setBody(json)
.addHeader("Content-Type", "application/json"))
// When
val result = apiService.getUsers()
// Then
assertTrue(result is Result.Success)
val users = (result as Result.Success).data.users
assertEquals(1, users.size)
assertEquals("John", users[0].name)
}
@Test
fun getUsers_returnsError() = runTest {
mockWebServer.enqueue(MockResponse().setResponseCode(500))
val result = apiService.getUsers()
assertTrue(result is Result.Failure)
}
}Try It
Add Retrofit and Serialization dependencies. Create API service with suspend functions. Add interceptors for auth and logging. Handle errors with sealed Result class.
# Add to build.gradle.kts:
# implementation("com.squareup.retrofit2:retrofit:2.11.0")
# implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0")Retrofit mastery
- Create API service with GET, POST, PUT, DELETE
- Implement Kotlinx Serialization converter
- Add auth interceptor with token refresh
- Create connectivity interceptor for offline support
- Implement retry logic with exponential backoff
- Build Repository with local-first strategy
- Write tests with MockWebServer
- Handle multipart file uploads
Retrofit with Kotlinx Serialization provides type-safe networking. Use suspend functions for async calls. Interceptors for cross-cutting concerns (auth, logging, retry). Sealed Result class for error handling. MockWebServer for testing.
Resources
- Retrofit: https://square.github.io/retrofit/
- Kotlinx Serialization: https://github.com/Kotlin/kotlinx.serialization
- OkHttp Interceptors: https://square.github.io/okhttp/interceptors/
- MockWebServer: https://github.com/square/okhttp/tree/master/mockwebserver