Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
65: Building a Small Ktor Web Service
By now, you've got a handle on the Kotlin language, but the real magic happens when you put it to work in a production environment. Today, we're going to build a lightweight web service using Ktor. I prefer Ktor over Spring Boot for small-to-medium services because it's asynchronous by nature and doesn't feel like it's hiding half the logic behind magic annotations.
We're going to build a "Movie Watchlist" API. It's a simple service where you can list movies you want to see and add new ones to the list. No database for today—we'll keep it in memory to focus on the Ktor plumbing.
Setting up the Netty engine
First, we need a server to actually listen for requests. Ktor allows you to swap engines, but Netty is the industry standard for a reason—it's fast and reliable. I'm going to use embeddedServer here because it's the quickest way to get a standalone service running without needing a complex configuration file.
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun main() {
embeddedServer(Netty, port = 8080) {
routing {
get("/") {
call.respondText("Welcome to the Movie Watchlist API!")
}
}
}.start(wait = true)
}
At this point, if you run this, you've got a working web server. But a "Welcome" message isn't a service; it's a landing page. Let's add some actual data.
Defining the Watchlist logic
I'll start by defining a simple Movie data class. Since we aren't using a database, I'll just throw these into a MutableList. In a real app, this would be a repository class, but let's keep the noise down for now.
import kotlinx.serialization.Serializable
@Serializable
data class Movie(val id: Int, val title: String, val director: String)
val watchlist = mutableListOf(
Movie(1, "Inception", "Christopher Nolan"),
Movie(2, "Everything Everywhere All At Once", "Daniel Kwan")
)
Now, I'll add a route to fetch the whole list. I want the client to receive a JSON array, not just a string.
routing {
get("/movies") {
call.respond(watchlist)
}
}
Hitting the "JSON Wall"
Here is where I usually trip up when I'm starting a new Ktor project. I just ran the code above, and it crashed immediately with a TransformationException. Ktor told me it didn't know how to transform the List<Movie> into a response.
The problem? I forgot the plumbing. Ktor is modular—it doesn't include JSON serialization by default because not everyone wants it. I need to install the ContentNegotiation plugin and tell it to use kotlinx.serialization.
Here is the corrected setup. Notice how I'm adding the install block inside the server configuration:
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.json.Json
fun main() {
embeddedServer(Netty, port = 8080) {
// This is the part I missed!
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
})
}
routing {
get("/movies") {
call.respond(watchlist)
}
}
}.start(wait = true)
}
Now, when you hit localhost:8080/movies, you'll actually get a clean JSON array back. Much better.
Accepting data via POST
A watchlist isn't useful if you can't add to it. To handle incoming data, we use call.receive<T>(). This is a suspending function, which is why Ktor is so efficient—it doesn't block the thread while waiting for the request body to be read from the network.
routing {
get("/movies") {
call.respond(watchlist)
}
post("/movies") {
val movie = call.receive<Movie>()
watchlist.add(movie)
call.respondText("Added ${movie.title} to the list!", status = io.ktor.http.HttpStatusCode.Created)
}
}
I've kept the Movie id manual here for simplicity. In a production scenario, you'd probably use a UUID or a database-generated sequence. But for a small service, this proves the concept: we're receiving a JSON object, mapping it to a Kotlin data class, and updating our state.
📋 Practical Task
Implement a Movie Removal Route
Our Movie Watchlist API can list and add movies, but it can't remove them. Your task is to extend the existing service by adding a new route.
Requirements:
- Create a
DELETEroute at/movies/{id}. - Use
call.parameters["id"]to retrieve the ID of the movie to be deleted. - Convert the ID from a String to an Int.
- Remove the movie from the
watchlistlist if a movie with that ID exists. - Respond with a
200 OKstatus and a message confirming the deletion, or a404 Not Foundif the ID doesn't exist in the list.
There are no comments for now.