Setting up Retrofit for network requests in an Android application

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.
Development and support of all types of mobile applications:
Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1 servicesAll 1735 services
Setting up Retrofit for network requests in an Android application
Medium
from 1 business day to 3 business days
FAQ
Our competencies:
Development stages
Latest works
  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    756
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    624
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1052
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    947
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    862
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    445

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.