Content Index
- Adding Retrofit and its dependencies to the project
- Initial project configuration
- 1. Data Classes and Data Modeling
- 2. Sealed Classes: enums with superpowers
- Advantages of Sealed Classes over Enums
- 3. Retrofit Client as a Singleton
- Service Interface: defining endpoints
- Implementation and Main Screen
- API Call and State Management
- Displaying Results and Loading Images with Coil
- Complete Code
- Conclusion
Retrofit is a type-safe HTTP client for Android and Java, developed by Square. It is relatively simple to integrate and one of the most popular libraries in the Android ecosystem for consuming REST APIs. Its greatest advantage lies in its converters: they allow you to automatically map JSON or XML responses from an API into objects of your own Kotlin classes, eliminating all manual deserialization boilerplate code.
Previously we looked at how to create a custom notification in Android Studio.
To work with Retrofit in Android Studio we need to be clear about several concepts involved in the process:
- An external REST API to which we can make HTTP requests. We have previously seen how to create one with CodeIgniter, although in this example we will use a free public API.
- A data class that models the JSON response returned by the API. This is known as the data model or deserializer.
- A Retrofit client (ideally as a Singleton) that configures the connection, the
baseUrl, and the JSON converter. - A service interface that centralizes and defines the available endpoints along with their HTTP annotations (
@GET,@POST, etc.). - The consumption logic in the UI, using coroutines to avoid blocking the main thread.
With these five elements, we have everything necessary to make Internet connections in Android in a clean and maintainable way.
Adding Retrofit and its dependencies to the project
To consume data from a REST API and convert it into Kotlin objects within our app, we need to add some dependencies to the build.gradle file (at the app module level).
Dependency management in modern Android is done with implementation instead of the old compile, which is already considered legacy and was removed in recent versions of Gradle. Below are the updated dependencies for Retrofit and the Gson converter:
implementation 'com.squareup.retrofit2:retrofit:3.0.0'
implementation 'com.google.code.gson:gson:2.13.2'
implementation 'com.squareup.retrofit2:converter-gson:3.0.0'You can check the latest available version and all official documentation from the official Retrofit website.
Other libraries for processing JSON
Retrofit is flexible and supports various converters to parse JSON. Depending on your needs or preferences, you can choose any of the following options:
- Gson:
implementation 'com.squareup.retrofit2:converter-gson:3.0.0' - Moshi:
implementation 'com.squareup.retrofit2:converter-moshi:3.0.0' - Jackson:
implementation 'com.squareup.retrofit2:converter-jackson:3.0.0'
In this tutorial we will use Gson for its popularity, simplicity, and the abundant documentation available. That said, you are free to use the library that best fits your project.
Initial project configuration
In addition to the Retrofit and Gson dependencies, in this example we also need Coil, a library for loading images from the Internet asynchronously, perfectly integrated with Jetpack Compose. The three key dependencies are:
- Retrofit (
com.squareup.retrofit2:retrofit): The main library for HTTP requests. - Gson Converter (
com.squareup.retrofit2:converter-gson): To automatically convert JSON responses into Kotlin objects. - Coil (
io.coil-kt.coil3:coil-compose): To load images from a URL directly into composables, such as Pokémon sprites.
A critical step you must not forget is to enable the Internet access permission in your AndroidManifest.xml file. Without this declared permission, Android will block any network connection and the app will fail silently or throw an exception:
<uses-permission android:name="android.permission.INTERNET" />What about the Backend?
In a real-world client application, you will typically need to implement or consume a backend layer. Whether using technologies like Laravel (PHP), Django, FastAPI, or Flask (Python), the goal is the same: expose a REST API that your Android app can query via Retrofit.For this example we will use the PokeAPI, a very popular free public API in the community. By sending it a Pokémon's name, it returns a JSON with its characteristics, which we will map to data models in Kotlin.
1. Data Classes and Data Modeling
Our goal is to create a model that represents the API response and display some data on screen. This is a minimal, functional example; in a real application there would be more layers and files involved (repositories, ViewModels, use cases, etc.).
The first thing we need is a data class. Data classes in Kotlin are designed specifically to model data structures, automatically generating methods like equals(), hashCode(), toString(), and copy(). They are perfect when working with API responses: they only contain data, without business logic or complex inheritance.
In this case we define a Pokémon with three properties: its ID, its name, and its sprites (the image). The sprites field is declared as nullable using the ? operator, since it is not always guaranteed that the API will return that field. For the sprites, we create a separate class where we only care about the front image (front_default) to keep the example simple:
data class PokemonResponse(
val id: Int,
val name: String,
val sprites: PokemonSprites?
)
data class PokemonSprites(
val front_default: String?
)2. Sealed Classes: enums with superpowers
To manage the different states that the interface can have during a network request, we use a sealed class named PokemonUiState. Unlike traditional enums, sealed classes allow each state to carry its own associated data, making them much more expressive and safe. For this case we define four possible states:
- Idle: Initial state. The app is waiting for the user to do something.
- Loading: The request is in progress. A loading indicator is displayed.
- Success: The API responded successfully. It carries the
PokemonResponseobject with the data. - Error: Something failed. It carries a
Stringwith the error message to display.
Advantages of Sealed Classes over Enums
The key lies in how Kotlin handles the when expression with sealed classes: if you do not cover all defined states, the compiler will flag an error at compile time, not at runtime. This makes it impossible to forget to handle a state—a protection that simple enums do not offer when you need to transport data in each branch.
// --- UI STATES (SEALED CLASS) ---
sealed class PokemonUiState {
object Idle : PokemonUiState()
object Loading : PokemonUiState()
data class Success(val pokemon: PokemonResponse) : PokemonUiState()
data class Error(val message: String) : PokemonUiState()
}3. Retrofit Client as a Singleton
The Retrofit client is implemented as a Kotlin object, which acts as a Singleton by nature. This makes complete sense: we only need a single connection instance throughout the entire application lifecycle; creating multiple instances would be a waste of memory and resources.
In this object we configure three essential things:
- The
BASE_URL: the root URL of the Pokémon API, which Retrofit will automatically concatenate with each route defined in the service. - The
GsonConverterFactory: the converter that transforms the response JSON into our Kotlin objects. - The
PokeApiServiceinstance: created lazily (by lazy), meaning only when accessed for the first time, optimizing startup.
object RetrofitClient {
private const val BASE_URL = "https://pokeapi.co/api/v2/"
val instance: PokeApiService by lazy {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofit.create(PokeApiService::class.java)
}
}Service Interface: defining endpoints
The service interface contains no direct implementation; it simply declares the available endpoints and their HTTP methods using annotations. Retrofit handles generating the implementation at runtime based on these annotations.
The function is marked with suspend so it can be called from a coroutine without blocking the main thread. The @GET annotation defines the HTTP method and the relative route to the BASE_URL, while @Path allows injecting dynamic parameters into that route:
interface PokeApiService {
@GET("pokemon/{name}")
suspend fun getPokemonInfo(@Path("name") name: String): PokemonResponse
}Implementation and Main Screen
In MainActivity, we create the PokemonScreen composable, which acts as the main screen. This is where all the previous concepts come together and two key tools of Jetpack Compose come into play:
- Coroutines: Network connections are asynchronous operations and should not be executed on the main UI thread. We use
rememberCoroutineScope()to launch the search asynchronously without freezing the interface. - Reactive State: We use
mutableStateOfso that Compose observes state changes and automatically reloads the screen when the API response arrives or when an error occurs.
API Call and State Management
When the user presses the search button, the logic is as follows: first we change the state to Loading, then we make the call via RetrofitClient inside a try/catch block, and finally we update the state to the result:
- We transition to
PokemonUiState.Loadingbefore making the call, to display the progress indicator. - If the response is successful, we transition to
PokemonUiState.Successwith the Pokémon data. - If any exception occurs (dropped network, Pokémon not found, timeout, etc.), we transition to
PokemonUiState.Error.
These three states are reflected directly in the interface, displaying the CircularProgressIndicator, a red error message, or the card with the Pokémon information, as appropriate.
@Composable
fun PokemonScreen() {
val scope = rememberCoroutineScope()
var pokemonName by remember { mutableStateOf("") }
var uiState by remember { mutableStateOf<PokemonUiState>(PokemonUiState.Idle) }
Column(
modifier = Modifier.fillMaxSize().padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
OutlinedTextField(
value = pokemonName,
onValueChange = { pokemonName = it },
label = { Text("Pokémon Name") },
modifier = Modifier.fillMaxWidth()
)
Button(
onClick = {
uiState = PokemonUiState.Loading
scope.launch {
try {
val response = RetrofitClient.instance.getPokemonInfo(pokemonName.lowercase().trim())
uiState = PokemonUiState.Success(response)
} catch (e: Exception) {
Log.e("POKEMON_APP", e.toString())
uiState = PokemonUiState.Error("Pokémon not found")
}
}
},
modifier = Modifier.padding(top = 8.dp)
) {
Text("Search")
}
Spacer(modifier = Modifier.height(20.dp))
when (val state = uiState) {
is PokemonUiState.Loading -> CircularProgressIndicator()
is PokemonUiState.Success -> PokemonDetailCard(state.pokemon)
is PokemonUiState.Error -> Text(state.message, color = Color.Red)
is PokemonUiState.Idle -> Text("Type a name to begin")
}
}
}The when block acts as a state router: it evaluates the current value of uiState and renders the corresponding composable. Thanks to sealed classes, Kotlin guarantees at compile time that all states are covered.
Displaying Results and Loading Images with Coil
When the state is Success, we display the PokemonDetailCard composable, which presents the data inside a Material3 Card. For the image we use AsyncImage from the Coil library, which handles downloading and displaying the sprite directly from the URL returned by the API, all asynchronously and without extra code:
@Composable
fun PokemonDetailCard(pokemon: PokemonResponse) {
Card(
modifier = Modifier.fillMaxWidth(),
elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
) {
Column(
modifier = Modifier.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
AsyncImage(
model = pokemon.sprites?.front_default,
contentDescription = "Image of ${pokemon.name}",
modifier = Modifier.size(150.dp)
)
Text(text = "ID: #${pokemon.id}", style = MaterialTheme.typography.labelMedium)
Text(text = pokemon.name.uppercase(), style = MaterialTheme.typography.headlineMedium)
}
}
}Complete Code
package com.example.myproyectandroid
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.example.myproyectandroid.ui.theme.MyProyectAndroidTheme
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
// --- DATA MODELS ---
data class PokemonResponse(
val id: Int,
val name: String,
val sprites: PokemonSprites?
)
data class PokemonSprites(
val front_default: String?
)
// --- UI STATES (SEALED CLASS) ---
sealed class PokemonUiState {
object Idle : PokemonUiState()
object Loading : PokemonUiState()
data class Success(val pokemon: PokemonResponse) : PokemonUiState()
data class Error(val message: String) : PokemonUiState()
}
// --- RETROFIT CLIENT (SINGLETON) ---
object RetrofitClient {
private const val BASE_URL = "https://pokeapi.co/api/v2/"
val instance: PokeApiService by lazy {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofit.create(PokeApiService::class.java)
}
}
interface PokeApiService {
@GET("pokemon/{name}")
suspend fun getPokemonInfo(@Path("name") name: String): PokemonResponse
}
// --- MAIN ACTIVITY ---
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
MyProyectAndroidTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
PokemonScreen()
}
}
}
}
}
@Composable
fun PokemonScreen() {
val scope = rememberCoroutineScope()
var pokemonName by remember { mutableStateOf("") }
var uiState by remember { mutableStateOf<PokemonUiState>(PokemonUiState.Idle) }
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
OutlinedTextField(
value = pokemonName,
onValueChange = { pokemonName = it },
label = { Text("Pokémon Name") },
modifier = Modifier.fillMaxWidth()
)
Button(
onClick = {
uiState = PokemonUiState.Loading
scope.launch {
try {
val response = RetrofitClient.instance.getPokemonInfo(pokemonName.lowercase().trim())
uiState = PokemonUiState.Success(response)
} catch (e: Exception) {
Log.e("POKEMON_APP", e.toString())
uiState = PokemonUiState.Error("Pokémon not found")
}
}
},
modifier = Modifier.padding(top = 8.dp)
) {
Text("Search")
}
Spacer(modifier = Modifier.height(20.dp))
when (val state = uiState) {
is PokemonUiState.Loading -> CircularProgressIndicator()
is PokemonUiState.Success -> PokemonDetailCard(state.pokemon)
is PokemonUiState.Error -> Text(state.message, color = Color.Red)
is PokemonUiState.Idle -> Text("Type a name to begin")
}
}
}
@Composable
fun PokemonDetailCard(pokemon: PokemonResponse) {
Card(
modifier = Modifier.fillMaxWidth(),
elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
) {
Column(
modifier = Modifier.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
AsyncImage(
model = pokemon.sprites?.front_default,
contentDescription = "Image of ${pokemon.name}",
modifier = Modifier.size(150.dp)
)
Text(text = "ID: #${pokemon.id}", style = MaterialTheme.typography.labelMedium)
Text(text = pokemon.name.uppercase(), style = MaterialTheme.typography.headlineMedium)
}
}
}You can check the official documentation and more examples at the following link: Retrofit — Official Documentation.
Conclusion
With this you now have a functional foundation to make your first Internet connection in Android using Retrofit. Throughout the tutorial you applied important concepts of modern Android development: data class, sealed class, coroutines with rememberCoroutineScope, reactive state with mutableStateOf, and declarative rendering with Jetpack Compose. All of this forms a solid base upon which you can build more complex and scalable applications.
The next step is learning how to use the Canvas API in Android Studio to draw custom shapes and graphics.