Kotlin

Ktor Server — JSON API with kotlinx.serialization

admin by @admin ADMIN
10m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Install `ContentNegotiation` + `Json` plugin and you get typed (de)serialization for every route. Decode request bodies into data classes; respond with data classes.
Kotlin
Raw
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.Serializable

@Serializable data class CreateUserRequest(val name: String, val email: String)
@Serializable data class User(val id: Int, val name: String, val email: String)

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(ContentNegotiation) { json() }

        routing {
            post("/users") {
                val req = call.receive<CreateUserRequest>()        // typed!
                val newUser = User(id = 42, name = req.name, email = req.email)
                call.respond(HttpStatusCode.Created, newUser)      // serialized to JSON
            }

            get("/users/{id}") {
                val id = call.parameters["id"]?.toIntOrNull()
                    ?: return@get call.respond(HttpStatusCode.BadRequest, "bad id")
                call.respond(User(id, "Alice", "a@x.com"))
            }
        }
    }.start(wait = true)
}
Tags

Save your own code snippets

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