Let's think about it this way for a second
Retrofit is the most widely used library for making REST API calls on Android — just declare the API endpoint (URL, HTTP method) as a Kotlin interface (using annotations), and Retrofit handles the HTTP request/response for you, auto-converting the JSON response into a Kotlin data class (via a Gson/Moshi converter). Since API calls depend on the network, they need to be asynchronous — that's where Kotlin Coroutines (next lesson) come in.
Let's connect this to a real scenario
Define `interface WeatherApi { @GET("weather") suspend fun getWeather(@Query("city") city: String): WeatherResponse }`, then `retrofit.create(WeatherApi::class.java)` auto-generates the implementation for you — calling `viewModelScope.launch { val weather = api.getWeather("Yangon") }` fetches the weather data from the API and lets you show it in the UI.
Let's walk through it together
data class WeatherResponse(val city: String, val tempCelsius: Double)
interface WeatherApi {
@GET("weather")
suspend fun getWeather(@Query("city") city: String): WeatherResponse
}
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val weatherApi = retrofit.create(WeatherApi::class.java)$ val weather = weatherApi.getWeather("Yangon")
// weather: WeatherResponse(city="Yangon", tempCelsius=32.0)5-minute try-it
Define a `WeatherApi` interface yourself (pick any free public weather API) — build a Retrofit instance and sketch out an API call (review the docs, do a dry run).
A quick word of caution
If you hardcode an API key (secret) into your app code and it ends up in the APK, it can be extracted by decompiling — sensitive keys should be used through a backend proxy server instead.