Skip to main content
Kotlin Basics
CHAPTER 26 Beginner

REST APIs and JSON Handling

Updated: May 18, 2026
5 min read

# CHAPTER 26

REST APIs and JSON Handling

1. Chapter Introduction

Almost every modern application requires internet access. A weather app fetches forecasts; a social media app fetches posts. Apps communicate with servers using REST APIs (Application Programming Interfaces). The server typically responds with data formatted as JSON (JavaScript Object Notation). In this chapter, we will learn how to use the industry-standard library, Retrofit, alongside Coroutines to fetch data from the internet and convert it directly into Kotlin Data Classes.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand what a REST API and JSON are.
  • Understand the role of the Retrofit library.
  • Create Data Classes to match JSON structure.
  • Define an API Interface using @GET.
  • Make an asynchronous network request.

3. Understanding JSON

JSON is a text format used to transmit data over the web. It uses Key-Value pairs. Example of a JSON response from a server:
json
123456
{
  "userId": 1,
  "id": 101,
  "title": "Learn Kotlin",
  "completed": false
}

4. Creating the Kotlin Data Class

To use this data in Kotlin, we create a Data Class that exactly matches the JSON keys! A library like Gson or Moshi (used alongside Retrofit) will automatically parse the JSON text into this object.
kotlin
1234567
// The property names must match the JSON keys exactly!
data class Todo(
    val userId: Int,
    val id: Int,
    val title: String,
    val completed: Boolean
)

5. Defining the API Interface (Retrofit)

Similar to Room DAOs, Retrofit uses an Interface to define the API endpoints. We use annotations like @GET or @POST.

*Crucial: Network requests are slow. We MUST mark them as suspend functions so they run in Coroutines!*

kotlin
123456789
import retrofit2.http.GET

interface ApiService {
    
    // If the base URL is https://jsonplaceholder.typicode.com/
    // This calls https://jsonplaceholder.typicode.com/todos
    @GET("todos")
    suspend fun getTodos(): List<Todo> // Automatically returns a List of our Kotlin objects!
}

6. Setting Up Retrofit

To actually make the request, we must build the Retrofit instance, assign the Base URL, and add a Converter Factory (which translates the JSON text into our Data Class).
kotlin
1234567891011121314
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

// Usually configured as a Singleton object
object RetrofitInstance {
    
    val api: ApiService by lazy {
        Retrofit.Builder()
            .baseUrl("https://jsonplaceholder.typicode.com/")
            .addConverterFactory(GsonConverterFactory.create()) // Use Gson to parse JSON
            .build()
            .create(ApiService::class.java)
    }
}

7. Making the Request

Because the API call is a suspend function, we must launch a Coroutine to execute it. We should also wrap it in a try-catch block, because networks are unreliable (no wifi, airplane mode, server down).
kotlin
12345678910111213141516
import kotlinx.coroutines.*

fun main() = runBlocking {
    println("Fetching Todos from the Internet...")
    
    try {
        // This pauses the coroutine until the network request finishes
        val todos: List<Todo> = RetrofitInstance.api.getTodos()
        
        println("Successfully downloaded ${todos.size} items.")
        println("First Item: ${todos[0].title}")
        
    } catch (e: Exception) {
        println("Network Error: ${e.message}")
    }
}

8. Common Mistakes

  • Missing Internet Permission: In Android, if you do not add <uses-permission android:name="android.permission.INTERNET"/> to your AndroidManifest.xml, your app is strictly blocked from making network requests and will crash.
  • Mismatched Variable Names: If the JSON key is firstname but your data class has val firstName, the parser will fail and return null. You must either match it exactly, or use annotations like @SerializedName("firstname") to bridge the gap.

9. Best Practices

  • Never hardcode API Keys: If you use a paid API, do not hardcode the key in your Kotlin file. Keep it in a secure local.properties file or inject it via build configurations.

10. Exercises

*(Theoretical)*
  1. 1. A server returns {"username": "dev123", "score": 95}. Write the Kotlin data class to hold this.
  1. 2. Write a Retrofit Interface with a @GET("profile") method that returns this object.

11. MCQs with Answers

Question 1

What is JSON?

Question 2

What is the industry-standard library for making network requests in Kotlin/Android?

Question 3

How do you map JSON data to a Kotlin object?

Question 4

What Retrofit annotation is used to fetch data from a server?

Question 5

Why must Retrofit API methods be marked with the suspend keyword?

Question 6

What does a Converter Factory (like GsonConverterFactory) do in Retrofit?

Question 7

What happens if the internet goes down during a Retrofit request?

Question 8

What permission is mandatory in the Android Manifest to use Retrofit?

Question 9

If a JSON key is "userage", but you want your Kotlin variable to be "userAge", what annotation do you use?

Question 10

How is Retrofit usually instantiated in an application?

12. Interview Questions

  • Q: Describe the architecture of a Retrofit setup. How do Data Classes, the API Interface, and Coroutines work together?
  • Q: Why do we use try-catch blocks around network requests? Give two examples of exceptions that might occur. (Answer: No internet connection UnknownHostException, or Server Timeout SocketTimeoutException).

13. Summary

Connecting to the internet is a fundamental requirement for modern applications. By utilizing Retrofit and Gson, Kotlin developers can avoid manual, error-prone JSON parsing. Furthermore, by executing Retrofit requests as suspend functions inside Coroutines, we ensure that our applications remain buttery-smooth and responsive, regardless of how slow the network connection is.

14. Next Chapter Recommendation

If your app handles money, you cannot afford bugs. Manual testing is not enough. In Chapter 27: Testing in Kotlin, we will learn how to write automated scripts to test our code mathematically.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·