Kotlin Ktor
Building web applications and APIs with Kotlin
🚀 What is Ktor?
Ktor is a modern, asynchronous web framework for Kotlin that makes building web applications and APIs simple and fun. Create powerful server-side applications with minimal boilerplate code.
// Simple Ktor server
fun main() {
embeddedServer(Netty, port = 8080) {
routing {
get("/") {
call.respondText("Hello, Ktor!")
}
}
}.start(wait = true)
}
Ktor Features
HTTP Server
Create REST APIs and web servers
get("/api/users") {
call.respond(users)
}
HTTP Client
Make HTTP requests easily
val client = HttpClient()
val response = client.get("https://api.example.com")
Plugins
Extend functionality with plugins
install(ContentNegotiation) {
json()
}
Coroutines
Asynchronous programming support
suspend fun fetchData() {
delay(1000)
return "Data"
}
🔹 Basic Ktor Server
Create a simple web server with routing:
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun main() {
embeddedServer(Netty, port = 8080) {
routing {
get("/") {
call.respondText("Welcome to Ktor!")
}
get("/hello/{name}") {
val name = call.parameters["name"]
call.respondText("Hello, $name!")
}
}
}.start(wait = true)
}
Server Response:
GET / → "Welcome to Ktor!"
GET /hello/John → "Hello, John!"
🔹 JSON API Example
Build a REST API that handles JSON:
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.Serializable
@Serializable
data class User(val id: Int, val name: String, val email: String)
fun Application.configureRouting() {
install(ContentNegotiation) {
json()
}
routing {
get("/api/users") {
val users = listOf(
User(1, "John Doe", "[email protected]"),
User(2, "Jane Smith", "[email protected]")
)
call.respond(users)
}
post("/api/users") {
val user = call.receive<User>()
call.respond(user)
}
}
}
API Response:
[
{"id": 1, "name": "John Doe", "email": "[email protected]"},
{"id": 2, "name": "Jane Smith", "email": "[email protected]"}
]
🔹 Ktor Client Usage
Make HTTP requests with Ktor client:
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.serialization.kotlinx.json.*
suspend fun main() {
val client = HttpClient {
install(ContentNegotiation) {
json()
}
}
// GET request
val response: String = client.get("https://api.example.com/data").body()
println(response)
// POST request
val user = User(3, "Bob Wilson", "[email protected]")
val createdUser: User = client.post("https://api.example.com/users") {
setBody(user)
}.body()
client.close()
}