How to Use Retrofit With Coroutines for API Calls
Modern Android applications depend on reliable network communication, whether they retrieve weather data for Perth, display transport updates in Sydney, or process online orders in Melbourne. Retrofit provides a clean interface for HTTP requests, while Kotlin coroutines make asynchronous work easier to read, test and maintain.
Using these tools together involves more than adding a dependency and declaring an endpoint. A dependable implementation needs clear data models, sensible error handling, lifecycle-aware scopes and a network configuration suited to Australian users, including people working with slower regional connections or moving between Wi-Fi and mobile data.
This guide explains a practical Retrofit and Kotlin coroutines setup for Android. The examples use a typical REST API, but the same approach applies to JSON services, authentication endpoints, product catalogues and location-based applications.
Why Retrofit And Coroutines Fit
Retrofit converts an HTTP API into a Kotlin interface. Instead of manually opening connections, constructing URLs and parsing JSON responses, you describe the service methods and let Retrofit handle the request machinery. Its converter support can transform JSON into Kotlin data classes, commonly through Kotlin serialization or Gson.
Coroutines provide structured concurrency for these network calls. A function marked with suspend can pause while waiting for a response without blocking Android’s main thread. This keeps the user interface responsive when a request takes longer because of congestion, limited coverage or a user travelling between suburbs.
A typical call runs inside a ViewModel scope, so it can survive configuration changes such as screen rotation. For applications used across Australia, this also helps preserve state when a user switches networks or briefly loses connectivity on a train, in a shopping centre or in a regional town.
Set Up Dependencies And The HTTP Client
Add Retrofit, a JSON converter and an OkHttp logging dependency to the application module. Kotlin’s coroutine libraries are also required. Versions change regularly, so use the current compatible releases from official documentation rather than copying an outdated version without checking your project’s Kotlin and Android Gradle Plugin versions.
dependencies {
implementation("com.squareup.retrofit2:retrofit:<version>")
implementation("com.squareup.retrofit2:converter-kotlinx-serialization:<version>")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:<version>")
implementation("com.squareup.okhttp3:logging-interceptor:<version>")
}
Declare internet access in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Create a single Retrofit instance instead of constructing a new client for every request. OkHttp can manage connection pooling, timeouts and interceptors. Logging should be enabled only in development because request logs may expose tokens, addresses or other personal information.
private val logging = HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) {
HttpLoggingInterceptor.Level.BODY
} else {
HttpLoggingInterceptor.Level.NONE
}
}
private val httpClient = OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(httpClient)
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.build()
Define Endpoints And Data Models
Keep API models close to the format returned by the server. With Kotlin serialization, annotate names that differ between JSON and Kotlin. A suspend service method is usually the simplest option for a request that returns one response.
@Serializable
data class WeatherDto(
val city: String,
val temperature: Double,
@SerialName("condition_text")
val condition: String
)
interface WeatherApi {
@GET("weather")
suspend fun getWeather(
@Query("location") location: String
): WeatherDto
}
Create the service once:
val weatherApi: WeatherApi = retrofit.create(WeatherApi::class.java)
For production applications, separate transport models such as WeatherDto from screen models such as WeatherUiModel. This prevents changes in an external API from spreading through the interface. It also makes it easier to convert Celsius values, format dates in Australian conventions and display appropriate states for locations such as Brisbane, Adelaide or Darwin.
When an API uses bearer authentication, add the access token through an OkHttp interceptor rather than placing it directly in every service method. Store credentials securely and avoid writing them to logs. Apps handling personal information should also consider the Privacy Act 1988 and the Australian Privacy Principles, especially when collecting names, addresses, location history or health-related data.
Handle Results And Failures
A repository can translate Retrofit responses into a result type that the ViewModel understands. The network layer should distinguish HTTP failures, connection problems, malformed responses and unexpected exceptions. A 404 is different from a timeout, and each may need a different message or recovery action.
class WeatherRepository(
private val api: WeatherApi
) {
suspend fun loadWeather(location: String): Result<WeatherDto> {
return try {
Result.success(api.getWeather(location))
} catch (error: HttpException) {
Result.failure(Exception("Server returned ${error.code()}"))
} catch (error: IOException) {
Result.failure(Exception("Network connection unavailable"))
}
}
}
Use viewModelScope to call the repository and expose state through StateFlow. The UI can then render loading, success and failure states without directly knowing how Retrofit works.
class WeatherViewModel(
private val repository: WeatherRepository
) : ViewModel() {
private val _state = MutableStateFlow<UiState>(UiState.Idle)
val state: StateFlow<UiState> = _state.asStateFlow()
fun refresh(location: String) {
viewModelScope.launch {
_state.value = UiState.Loading
repository.loadWeather(location)
.onSuccess { _state.value = UiState.Success(it) }
.onFailure { _state.value = UiState.Error(it.message.orEmpty()) }
}
}
}
Avoid catching every exception and silently ignoring it. A useful app can offer retry behaviour, cached data or an offline message. This matters when customers use an app in rural New South Wales, travel through areas with patchy coverage or exceed a mobile data allowance.
Build A Reliable Retrofit Layer
A clean implementation benefits from a few consistent rules. Keep network calls out of activities and composables, validate user input before sending it, and use realistic timeout values. Automatic retries should be limited to safe operations because repeating a payment or booking request could create duplicate transactions.
Use the following practices when moving from a proof of concept to a production Android application:
- Keep one configured Retrofit and OkHttp instance for the application.
- Expose loading, success, empty and error states through
StateFlow. - Use DTO-to-domain mapping so API changes remain isolated.
- Remove body-level logging from release builds and protect authentication data.
- Add tests for successful responses, HTTP errors, timeouts and malformed JSON.
- Provide retry or cached-content behaviour for intermittent connectivity.
- Review privacy, consent and data retention against Australian requirements.
For Australian users, server location and latency can influence perceived performance. A service hosted in Sydney may respond differently for users in Perth or remote Queensland, so measure real request times rather than relying only on an office Wi-Fi connection. If the app processes payments or customer records, use TLS, minimise stored data and document how personal information is handled under applicable Australian privacy obligations.
Compare Common API Call Approaches
Retrofit with coroutines is a strong default, but it is not the only option. The right choice depends on project size, existing libraries and how much control the application needs over HTTP traffic.
A small app may use Retrofit directly from a repository. A larger codebase can add a dedicated domain layer, a result wrapper and a local cache. For very specialised protocols or streaming requirements, a lower-level client may be more suitable.
| Approach | Strengths | Trade-offs | Suitable Use |
|---|---|---|---|
| Retrofit with coroutines | Clear service interfaces, easy JSON conversion, readable asynchronous code | Requires initial project setup | Most REST-based Android apps |
| OkHttp directly | Detailed control over requests, caching and interceptors | More manual parsing and response handling | Custom HTTP workflows |
| Ktor Client | Kotlin-first design and multiplatform support | Retrofit examples and integrations may be less familiar | Shared Android and iOS networking |
| Callback-based Retrofit | Works with older codebases | More nesting and lifecycle management | Maintaining legacy applications |
| Flow-based repository layer | Supports updates, caching and reactive UI state | Adds architectural complexity | Larger apps with ongoing data streams |
A sensible migration path is to begin with a suspend Retrofit service, place it behind a repository, and introduce Flow, caching or dependency injection when the application genuinely needs those features. This keeps the first implementation understandable while leaving room for growth.
Select the right endpoints, model the responses carefully and test failure states before releasing the app. With Retrofit, coroutines and a privacy-conscious network layer, Android applications can deliver dependable API calls for users from Sydney to regional Western Australia.