Ktor Client: Set up ktor client and get data from typicode
Video: Ktor Client: Set up ktor client and get data from typicode by Taught by Celeste AI - AI Coding Coach
Watch full page →Ktor Client: Set Up Ktor Client and Get Data from Typicode
In this tutorial, you'll learn how to set up a Ktor HTTP client in Kotlin and fetch JSON data from the Typicode API, a popular free REST API for testing. This example demonstrates making a GET request and parsing the response to work with remote data efficiently.
Code
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.client.call.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
// Define a data class matching the JSON structure from Typicode
@Serializable
data class Post(
val userId: Int,
val id: Int,
val title: String,
val body: String
)
fun main() = runBlocking {
// Create Ktor client with CIO engine and JSON serialization support
val client = HttpClient(CIO) {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true // Ignore extra fields in JSON
})
}
}
try {
// Make a GET request to fetch a post from Typicode API
val post: Post = client.get("https://jsonplaceholder.typicode.com/posts/1").body()
println("Post title: ${post.title}")
println("Post body: ${post.body}")
} catch (e: Exception) {
println("Error fetching data: ${e.message}")
} finally {
client.close()
}
}
Key Points
- Ktor Client can be configured with different engines; CIO is a lightweight asynchronous engine.
- ContentNegotiation plugin with Kotlinx Serialization enables automatic JSON parsing into Kotlin data classes.
- Use suspend functions and runBlocking to perform asynchronous network calls in a simple main function.
- Always close the client after use to free resources and avoid leaks.
- Typicode provides a simple REST API ideal for testing HTTP clients and JSON parsing.