Setting up Retrofit for Network Requests in Android Application
Retrofit is de-facto standard for working with REST API in Android. The library turns HTTP calls into Kotlin suspend functions or RxJava Observable, handles serialization/deserialization, and with proper configuration requires zero boilerplate for standard CRUD operations.
What Setup Includes
Standard stack: Retrofit 2 + OkHttp as HTTP client + kotlinx.serialization or Gson as converter. KotlinX Serialization preferred for Kotlin projects: null-safety at JSON-parsing level, sealed classes support, no reflection (important for R8 obfuscation).
Retrofit configuration:
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.API_BASE_URL)
.client(okHttpClient)
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.build()
API_BASE_URL from BuildConfig, not hardcoded. Different environments (dev/staging/prod) managed via productFlavors in Gradle.
API interface with suspend functions:
interface UserApi {
@GET("users/{id}")
suspend fun getUser(@Path("id") id: Long): UserResponse
@POST("users")
suspend fun createUser(@Body request: CreateUserRequest): UserResponse
@PUT("users/{id}")
@Headers("Content-Type: application/json")
suspend fun updateUser(@Path("id") id: Long, @Body request: UpdateUserRequest): UserResponse
}
OkHttp Interceptors
This is where most network layer logic concentrates.
Authorization: Interceptor that adds Authorization: Bearer {token} to every request. Token read from encrypted EncryptedSharedPreferences or DataStore. If token expired — 401 from server, interceptor via Authenticator (separate OkHttp interface) refreshes and retries request. Without Authenticator you'll handle 401 in every UseCase manually.
Logging: HttpLoggingInterceptor with BODY level — debug builds only (if (BuildConfig.DEBUG)). In release — NONE. Logging tokens in production is vulnerability.
Retry: custom Interceptor with exponential backoff for network errors (IOException). Server errors (4xx, 5xx) — don't auto-retry, only network errors.
Timeout: connectTimeout(30, TimeUnit.SECONDS), readTimeout(30, TimeUnit.SECONDS), writeTimeout(30, TimeUnit.SECONDS) on OkHttpClient.Builder. For file uploads — separate client with increased writeTimeout.
Error Handling
Retrofit suspend functions throw HttpException on non-2xx status and IOException on network error. Wrap in sealed result class:
sealed class ApiResult<out T> {
data class Success<T>(val data: T) : ApiResult<T>()
data class Error(val code: Int, val message: String) : ApiResult<Nothing>()
data object NetworkError : ApiResult<Nothing>()
}
This lets ViewModel work with typed errors without try/catch on every call — wrapper logic in one place in NetworkDataSource.
Certificate pinning via CertificatePinner in OkHttpClient — for apps with enhanced security requirements (fintech, healthcare). Requires update on certificate rotation — plan this process.
Retrofit setup with full network layer (authorization, retry, error handling, logging, unit-tests with MockWebServer) — 1–3 days. Cost calculated individually.







