Get Data from the Internet in Android with Retrofit
โ† BACK TO WRITING
October 17, 2026

By , Android developer & software engineer

Get Data from the Internet in Android with Retrofit

Use Retrofit to download real fruit data from a free API and show it in your Jetpack Compose list. Simple steps for total beginners.

Until now, our fruit list lived inside the app. We typed every fruit by hand. Real apps don't work like that. Facebook, Foodpanda and bKash all get their data from a server on the internet. In this part you will learn how to use Retrofit in Android to download real fruit data from the internet and show it in your list. In Part 12: Load Images from the Internet with Coil we loaded pictures from the internet. Today we load real data. Let's go!

What Is an API? (The Restaurant Waiter)

Imagine you are in a restaurant in Dhaka. You are hungry, but you can't walk into the kitchen and cook. So what do you do?

  1. You tell the waiter what you want: "One plate of biryani, please."
  2. The waiter goes to the kitchen.
  3. The waiter comes back with your food.

An API works the same way:

  • You = your Android app
  • The waiter = the API
  • The kitchen = the server (a computer somewhere on the internet)
  • The food = the data

Your app sends a request ("give me all fruits"). The server sends back a response (the list of fruits).

What Is JSON?

The server can't send you real fruits, of course. ๐Ÿ˜„ It sends text that describes them. This text is usually in a format called JSON. It looks like this:

[
  {
    "name": "Strawberry",
    "id": 3,
    "family": "Rosaceae",
    "order": "Rosales",
    "genus": "Fragaria",
    "nutritions": {
      "calories": 29,
      "fat": 0.4,
      "sugar": 5.4,
      "carbohydrates": 5.5,
      "protein": 0.8
    }
  }
]

Let's understand it:

  • [ ] square brackets mean a list.
  • { } curly brackets mean one object (one thing, like one fruit).
  • "name": "Strawberry" is a key and a value. Like a label on a box.
  • nutritions is an object inside another object.

We will use a free API called Fruityvice. It needs no key and no sign-up. Open this link in your browser and you will see real JSON:

https://www.fruityvice.com/api/fruit/all

What Is Retrofit?

Retrofit is a library made by a company called Square. It is our waiter. You tell Retrofit what you want, and it does all the hard work: it connects to the internet, sends the request and gets the answer.

Retrofit needs a helper called a converter. The converter turns the JSON text into Kotlin objects. We will use the Gson converter because it is the simplest to set up. No extra plugins needed.

Step 1: Check the INTERNET Permission

We added this in Part 12. Open app/src/main/AndroidManifest.xml and make sure this line is there, above the <application> tag:

<uses-permission android:name="android.permission.INTERNET" />

Without it, your app is not allowed to use the internet at all.

Step 2: Add Retrofit to Gradle

Open app/build.gradle.kts (the one inside the app folder). Find the dependencies { } block and add these two lines:

dependencies {
    // ... your other dependencies

    implementation("com.squareup.retrofit2:retrofit:3.0.0")
    implementation("com.squareup.retrofit2:converter-gson:3.0.0")
}

Now click Sync Now at the top of the editor.

Let's understand it:

  • retrofit is the main library (our waiter).
  • converter-gson turns JSON into Kotlin objects.
  • Both use the same version number. Always keep them the same.

Tip: Android Studio may show a yellow line and offer a newer version. That is fine. Just keep both Retrofit lines on the same version.

Step 3: Create Data Classes for the JSON

Now we tell Kotlin what one fruit looks like. Right-click your package folder โ†’ New โ†’ Kotlin Class/File โ†’ choose File and name it FruitDto.

package com.example.myfirstapp

data class FruitDto(
    val id: Int,
    val name: String,
    val family: String,
    val nutritions: NutritionsDto
)

data class NutritionsDto(
    val calories: Double,
    val sugar: Double,
    val carbohydrates: Double,
    val protein: Double,
    val fat: Double
)

Change com.example.myfirstapp to your own package name. Keep the one Android Studio wrote at the top of the file.

Let's understand it:

  • DTO means "Data Transfer Object". It's just a fancy name for "data that came from the internet".
  • The property names (name, family, nutritions) must match the JSON keys exactly. Yes, even the strange spelling nutritions!
  • nutritions is an object inside the fruit, so we make a second data class for it.
  • We don't need every key. The JSON also has order and genus, but we skip them. Gson simply ignores them.
  • We use Double for numbers because some values have decimals, like 0.4.

Step 4: Create the API Interface

Now we write the "menu" for our waiter. Create a new Kotlin file called FruitApi:

package com.example.myfirstapp

import retrofit2.http.GET

interface FruitApi {

    @GET("api/fruit/all")
    suspend fun getFruits(): List<FruitDto>
}

Let's understand it:

  • An interface is a list of things we can ask for. We don't write the code inside. Retrofit writes it for us!
  • @GET("api/fruit/all") means "go and get data from this address".
  • List<FruitDto> is what we expect back: a list of fruits.
  • suspend is a special word. Read the next section.

What Does suspend Mean?

Getting data from the internet takes time. Maybe one second, maybe five. If the app just waits, the screen freezes and the user thinks the app is broken.

A suspend function can pause and wait without freezing the app. Think of ordering tea at a tea stall. You don't stand frozen. You chat with friends, and when the tea is ready, you pick it up.

A suspend function can only be called from a coroutine (a light background job). We will use one in the ViewModel. If you want to learn more, read Kotlin Coroutines Guide later.

Step 5: Create the Retrofit Instance

Now we build the waiter himself. Create a new Kotlin file called RetrofitInstance:

package com.example.myfirstapp

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitInstance {

    private const val BASE_URL = "https://www.fruityvice.com/"

    val api: FruitApi by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(FruitApi::class.java)
    }
}

Let's understand it:

  • object means there is only one Retrofit in the whole app. We don't need many waiters.
  • BASE_URL is the main address of the server. It must end with /.
  • Retrofit joins the base URL and api/fruit/all together. The result is https://www.fruityvice.com/api/fruit/all.
  • addConverterFactory(GsonConverterFactory.create()) tells Retrofit to use Gson for JSON.
  • create(FruitApi::class.java) makes a real working object from our interface.
  • by lazy means "build it only the first time someone uses it".

Step 6: Call the API from the ViewModel

In Part 9 we made FruitViewModel. Now we change it to load fruits from the internet. Replace the whole file with this:

package com.example.myfirstapp

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class FruitViewModel : ViewModel() {

    private val _fruits = MutableStateFlow<List<FruitDto>>(emptyList())
    val fruits: StateFlow<List<FruitDto>> = _fruits.asStateFlow()

    init {
        loadFruits()
    }

    fun loadFruits() {
        viewModelScope.launch {
            try {
                _fruits.value = RetrofitInstance.api.getFruits()
            } catch (e: Exception) {
                Log.e("FruitViewModel", "Could not load fruits", e)
            }
        }
    }
}

Let's understand it:

  • init { } runs once when the ViewModel is created. So fruits start loading right away.
  • viewModelScope.launch { } starts a coroutine. This is where we are allowed to call a suspend function.
  • viewModelScope is smart. If the user leaves the screen, the work stops by itself.
  • RetrofitInstance.api.getFruits() asks the waiter for fruits. When they arrive, we put them in _fruits.
  • try { } catch { } catches problems, like "no internet". Without it, the app would crash. For now we just write the error in Logcat. In the next part we will show a nice error screen.

Step 7: Show the Fruits on the Screen

Now let's show the real data. We make a new row called FruitApiRow that shows the name, family and calories. Create a new file FruitListScreen (or replace your old list screen):

package com.example.myfirstapp

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel

@Composable
fun FruitListScreen(
    modifier: Modifier = Modifier,
    viewModel: FruitViewModel = viewModel()
) {
    val fruits by viewModel.fruits.collectAsStateWithLifecycle()

    LazyColumn(modifier = modifier) {
        items(fruits) { fruit ->
            FruitApiRow(fruit = fruit)
        }
    }
}

@Composable
fun FruitApiRow(fruit: FruitDto) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 6.dp)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text(
                text = fruit.name,
                style = MaterialTheme.typography.titleMedium
            )
            Text(
                text = "Family: ${fruit.family}",
                style = MaterialTheme.typography.bodyMedium
            )
            Text(
                text = "${fruit.nutritions.calories.toInt()} calories per 100 g",
                style = MaterialTheme.typography.bodySmall
            )
        }
    }
}

Now use it inside your Scaffold from Part 10, where your old list was:

Scaffold(
    topBar = { /* your TopAppBar */ },
    bottomBar = { /* your NavigationBar */ }
) { innerPadding ->
    FruitListScreen(modifier = Modifier.padding(innerPadding))
}

Let's understand it:

  • collectAsStateWithLifecycle() watches the list. When new fruits arrive, the screen updates by itself.
  • At first the list is empty, so the screen is blank for a moment. Then the fruits appear.
  • items(fruits) makes one FruitApiRow for each fruit.
  • calories.toInt() turns 29.0 into 29, which looks nicer.

Tip: Press Alt+Enter on any red word to add the import. Watch out for these tricky ones: androidx.compose.foundation.lazy.items, androidx.compose.runtime.getValue, retrofit2.converter.gson.GsonConverterFactory and retrofit2.http.GET.

Now run the app. Wait one or two seconds... and you will see around 50 real fruits from the internet! ๐ŸŽ‰

Common Errors

1. The list is empty and Logcat says UnknownHostException Your emulator has no internet. Check the Wi-Fi icon in the emulator. Also check the INTERNET permission in the Manifest.

2. SecurityException: Permission denied (missing INTERNET permission?) You forgot the <uses-permission> line. Add it and run the app again.

3. IllegalArgumentException: baseUrl must end in / Your BASE_URL needs a / at the end: "https://www.fruityvice.com/".

4. Values show as null or 0 A property name doesn't match the JSON key. Check the spelling. It's nutritions, not nutrition.

5. Suspend function 'getFruits' should be called only from a coroutine You called getFruits() outside viewModelScope.launch { }. Move it inside.

Try It Yourself

  1. Show the sugar amount in FruitApiRow too.
  2. Sort the list by name before saving it. Hint: RetrofitInstance.api.getFruits().sortedBy { it.name }.
  3. Add val genus: String to FruitDto and show it in the row.

Frequently Asked Questions

Do I need to pay for the Fruityvice API? No. It's free and needs no API key. Many real APIs need a key, but this one is perfect for learning.

Why Gson and not another converter? Gson is the easiest to set up. You just add one line in Gradle. Other converters, like kotlinx.serialization or Moshi, are also great. You can try them when you feel more confident.

Why does my app not crash when the internet is off? Because of try { } catch { }. It catches the error and writes it in Logcat. Your app keeps running, but the user sees a blank screen. We fix that in the next part.

Quick Recap

  • An API is like a waiter. Your app asks, the server answers.
  • JSON is the text format the server uses to send data.
  • Retrofit is the library that talks to the API for us.
  • Data classes describe the shape of the JSON.
  • A suspend function waits without freezing the app. Call it inside viewModelScope.launch { }.
  • try / catch stops the app from crashing when something goes wrong.

Right now, the user sees a blank screen while waiting, and a blank screen when there's no internet. That's not friendly. Next, we will add a loading spinner, an error message and a "Try again" button.

Part 14: Loading, Error and Retry Screens in Jetpack Compose

Next in Android for Beginners โ†’
Loading, Error and Retry Screens in Jetpack Compose
ยฉ 2026 SHAKIL AHMED. SYSTEM: ANTIGRAVITY OS v1.0