Skip to Content
Course content

65: Building a Small Ktor Web Service

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 DELETE route 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 watchlist list if a movie with that ID exists.
  • Respond with a 200 OK status and a message confirming the deletion, or a 404 Not Found if the ID doesn't exist in the list.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.