Kotlin

Ktor Client — POST JSON with Serialization

admin by @admin ADMIN
1h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Combine Ktor + kotlinx.serialization: register the JSON plugin, declare `@Serializable` data classes, the client (de)serializes automatically.
Kotlin
Raw
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.client.call.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.Serializable

@Serializable data class NewUser(val name: String, val email: String)
@Serializable data class CreatedUser(val id: Int, val name: String, val email: String)

val client = HttpClient(CIO) {
    install(ContentNegotiation) { json() }      // auto JSON (de)serialization
    expectSuccess = true
}

suspend fun createUser(req: NewUser): CreatedUser =
    client.post("https://api.example.com/users") {
        contentType(ContentType.Application.Json)
        setBody(req)
    }.body()                                    // <-- typed deserialize via body<T>()

fun main() = runBlocking {
    val user = createUser(NewUser("Alice", "a@x.com"))
    println(user)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.