DEV Community

Tapp.AI for Tapp.AI

Posted on

Integrate APIs in Android: Compose, MVVM, Retrofit

In this guide, we will explore how to integrate an API within a Jetpack Compose Android app using the MVVM pattern. Retrofit will handle network calls, LiveData will manage data updates, and Compose will construct the UI. We'll use an API supplying credit card detail.

Prerequisites:

Familiarity with Jetpack Compose, MVVM principles, and Retrofit basics.

Step 1: Configure the Project

Begin by configuring your Android project. Add these dependencies to your app-level build.gradle file:

// Jetpack Compose 
implementation 'androidx.activity:activity-compose:1.4.0' 
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07' 
implementation 'androidx.compose.runtime:runtime-livedata:1.0.4' 
// Retrofit for network requests 
implementation 'com.squareup.retrofit2:retrofit:2.9.0' 
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
// Coroutines for asynchronous programming 
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.1' 
Enter fullscreen mode Exit fullscreen mode

Repository: https://gist.github.com/dheeraj-bhadoria/d97b0af1592cc24cd0b912dcbae38eaf#file-build-gradle

Step 2: Build the Data Model

Create a CreditCard data class to model your credit card object. Inside a new CreditCard.kt file, add this code:

data class CreditCard( 
    val id: String, 
    val bank: String, 
    val number: String, 
    val cvv: String, 
    val type: String 
) 
Enter fullscreen mode Exit fullscreen mode

https://gist.github.com/dheeraj-bhadoria/42cc69848f821ddd1f2b5b11b3e03e60#file-creditcard-kt

Step 3: Set up Retrofit

Build a Retrofit service interface to specify API endpoints. Make a new Kotlin file named CreditCardService.kt and add the code.

interface CreditCardService { 
    @GET("credit_cards") 
    suspend fun getCreditCards(): List<CreditCard> 
Enter fullscreen mode Exit fullscreen mode

https://gist.github.com/dheeraj-bhadoria/bc1be647d040bc5fc1eeae825ddbc273#file-creditcardservice-kt

Now, build a Retrofit instance for network requests. Make a new Kotlin file named RetrofitInstance.kt and add this code:

object RetrofitInstance { 
    private const val BASE_URL = "https://random-data-api.com/api/v2/" 
    private val retrofit: Retrofit by lazy { 
        Retrofit.Builder() 
            .baseUrl(BASE_URL) 
            .addConverterFactory(GsonConverterFactory.create()) 
            .build() 
    } 
    val creditCardService: CreditCardService by lazy { 
        retrofit.create(CreditCardService::class.java)
    } 
} 
Enter fullscreen mode Exit fullscreen mode

https://gist.github.com/dheeraj-bhadoria/e32ef92cda80d120ccb4690517b99cd9#file-retrofitinstance-kt

Step 4: Build Data Repository

Generate a repository class to manage data actions. Form a new Kotlin file titled CreditCardRepository.kt. Include the following code:

class CreditCardRepository {
    private val creditCardService = RetrofitInstance.creditCardService 
    suspend fun getCreditCards(): List<CreditCard> { 
        return creditCardService.getCreditCards() 
    } 
} 
Enter fullscreen mode Exit fullscreen mode

https://gist.github.com/dheeraj-bhadoria/a5e97a94f18eb43ea66e5508f2bec82e#file-creditcardrepository-kt

Step 5: Build the ViewModel

Create a ViewModel class to handle data within your Composable UI. Make a new Kotlin file named CreditCardViewModel.kt and insert this code:

class CreditCardViewModel : ViewModel() { 
    private val repository = CreditCardRepository() 
    private val _creditCards = MutableLiveData<List<CreditCard>>() 
    val creditCards: LiveData<List<CreditCard>> = _creditCards 
     fun fetchCreditCards() { 
        viewModelScope.launch { 
            try { 
                val cards = repository.getCreditCards() 
                _creditCards.value = cards 
            } catch (e: Exception) { 
                // Handle error 
            } 
        } 
    } 
} 
Enter fullscreen mode Exit fullscreen mode

https://gist.github.com/dheeraj-bhadoria/4edcc141ed8c63a82951a16e49414daa#file-creditcardviewmodel-kt

Step 6: Build the Composable UI

Construct your Composable UI. Generate a fresh Kotlin file (e.g., CreditCardScreen.kt) and insert the following code:

@Composable 
fun CreditCardScreen(viewModel: CreditCardViewModel) { 
    val creditCards by viewModel.creditCards.observeAsState(emptyList()) 
    LaunchedEffect(Unit) { 
        viewModel.fetchCreditCards() 
    } 
    Column { 
        if (creditCards.isEmpty()) { 
            // Show loading indicator or placeholder 
            Text(text = "Loading...") 
        } else { 
            // Display the list of credit cards 
            LazyColumn { 
                items(creditCards) { creditCard -> 
                    Text(text = creditCard.bank) 
                    Text(text = creditCard.number) 
                    Text(text = creditCard.type) 
                    Divider() // Add a divider between items 
                } 
            } 
        } 
    } 
} 
Enter fullscreen mode Exit fullscreen mode

https://gist.github.com/dheeraj-bhadoria/5585712c22e9f8cf6ced92a83b775d82#file-creditcardscreen-kt

Step 7: Configure Entry Point 

In your app's activity or entry point, use the setContent function to initialize the Composable UI. Example (MainActivity.kt):

class MainActivity : AppCompatActivity() { 
    private val viewModel: CreditCardViewModel by viewModels() 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        setContent { 
            CreditCardScreen(viewModel) 
        } 
    } 
} 
Enter fullscreen mode Exit fullscreen mode

https://gist.github.com/dheeraj-bhadoria/154eea7dd32528f2376e7405eb7a6ba5#file-mainactivity-kt

Step 8: Grant Internet Permission

In your AndroidManifest.xml file, add the internet permission to enable network access:

<uses-permission android:name="android.permission.INTERNET" />
Enter fullscreen mode Exit fullscreen mode

Output

In this tutorial, we have successfully integrated the given API into a Jetpack Compose-based Android app using the MVVM architecture. We set up Retrofit for network requests, LiveData for data observation, and Compose for building the UI. The ViewModel handles data retrieval and state management, and the Composable UI displays the list of credit cards fetched from the API. This architecture provides a structured and efficient way to handle network requests and update the UI in a reactive manner.

Sample Repository:
https://github.com/dheeraj-bhadoria/Compose-MVVM-Retrofit-ViewMode-LiveData-Complete-Example-Android-App.git

Top comments (0)