Skip to Content
Course content

64: Building a Simple REST Client with Coroutines

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I remember a developer on my team a few years back who was building a small dashboard to track cryptocurrency prices. He used a standard blocking HTTP library and, for a while, everything seemed fine on his high-end workstation. But the moment he deployed it to a low-end Android device, the app just... stopped. The dreaded "Application Not Responding" (ANR) dialog popped up immediately. He was baffled because the API call only took 200ms. The problem was that 200ms of total thread blockage on the UI thread feels like an eternity to the OS. He was trying to handle the "waiting" part by threading manually, which led to a nightmare of nested callbacks that we spent an entire weekend untangling.

This is exactly where Kotlin Coroutines shine. Instead of blocking a thread while we wait for a server in another timezone to respond, we "suspend" the execution. The thread is released to do other work, and when the bytes finally arrive over the wire, the coroutine resumes exactly where it left off. It looks like synchronous, sequential code, but it performs like a highly efficient asynchronous machine.

Wiring up the Ktor Client and Serialization

To build a modern REST client, you'll want to use Ktor. It's the industry standard for Kotlin because it's built from the ground up using coroutines. I generally recommend the CIO (Coroutine-based I/O) engine because it's lightweight and doesn't require a heavy external dependency like Apache or Jetty.

One thing that usually trips people up is the serialization. You can't just throw a JSON string at a Kotlin object; you need a bridge. We use kotlinx.serialization for this. By installing the ContentNegotiation plugin into the Ktor client, we tell the client: "Whenever you see a response with application/json, use this specific library to map it to my data class."

import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json

val client = HttpClient(CIO) {
    install(ContentNegotiation) {
        json(Json {
            ignoreUnknownKeys = true // Crucial: prevents crashes if the API adds new fields
            prettyPrint = true
        })
    }
}

Fetching and Parsing the JSON Response

Now let's actually hit an endpoint. For this example, we'll use the PokéAPI—it's public, free, and predictable. Notice that the function we use to fetch the data is marked as suspend. This is the magic word. It tells the compiler that this function can pause its execution without blocking the thread it's running on.

I always suggest creating a dedicated data class for your response. Don't try to parse the whole JSON blob into a Map; it's brittle and a pain to maintain. Define exactly what you need, mark it as @Serializable, and let Ktor handle the rest.

import io.ktor.client.call.*
import io.ktor.client.request.*
import kotlinx.serialization.Serializable

@Serializable
data class Pokemon(
    val name: String,
    val weight: Int,
    val base_experience: Int
)

suspend fun fetchPokemonData(pokemonName: String): Pokemon {
    // This call suspends. The thread is free until the response returns.
    val response: Pokemon = client.get("https://pokeapi.co/api/v2/pokemon/$pokemonName").body()
    return response
}

// Usage inside a coroutine scope
suspend fun main() {
    try {
        val pikachu = fetchPokemonData("pikachu")
        println("Found ${pikachu.name}! Weight: ${pikachu.weight}")
    } catch (e: Exception) {
        println("Error fetching data: ${e.message}")
    } finally {
        client.close() // Always close your client to free up resources
    }
}

You'll notice I wrapped the call in a try-catch block. In the real world, networks are flaky. DNS fails, servers timeout, and APIs return 404s. If you don't handle these exceptions, your coroutine will fail silently or crash your application. It's a habit you should build early.




📋 Practical Task

GitHub User Profile Fetcher

Your task is to build a small REST client that retrieves public information about a GitHub user. You will need to use the Ktor CIO engine and kotlinx.serialization.

Requirements:

  • Create a @Serializable data class called GitHubUser that captures at least the login, id, and public_repos fields from the GitHub API.
  • Implement a suspend function called fetchGitHubUser(username: String) that makes a GET request to https://api.github.com/users/{username}.
  • In your main function, launch a coroutine to fetch the profile of a real GitHub user (e.g., "kotlin") and print their public repository count to the console.
  • Ensure the HttpClient is configured to ignore unknown keys in the JSON response, as the GitHub API returns a massive amount of data we don't need.
  • Implement basic error handling to catch and print a message if the user is not found or the network is down.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.