Skip to Content
Course content

60: Building APIs with Ktor

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

Think of building a Ktor API like starting a specialized food truck. You don't buy a fully stocked industrial kitchen if you're only selling gourmet grilled cheese. Instead, you start with a basic chassis—the engine and the wheels—and then you "install" only the specific equipment you need. Need a grill? Install it. Need a POS system for payments? Add that. If you aren't selling ice cream, you don't waste space or money on a freezer. This modularity is exactly how Ktor works; it doesn't force a massive set of features on you. You start with a bare-bones server and plug in the functionality you actually want.

Let's map that food truck logic to the code we're about to write:

  • The Chassis is your embeddedServer. It's the core that handles the network connections.
  • The Equipment are the Ktor Plugins. Want to handle JSON? You install the ContentNegotiation plugin.
  • The Menu is your routing. It defines exactly what happens when a customer (the client) asks for a specific item (an endpoint).

Setting Up Your Server Chassis

In Ktor, you don't need a complex XML configuration or a massive framework bootstrapper. You just tell Ktor which engine to use (like Netty or Jetty) and which port to listen on. I usually stick with Netty for most projects because it's rock-solid and asynchronous by nature.

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("The server is humming along nicely!")
            }
        }
    }.start(wait = true)
}

Notice how the routing block is essentially our menu. When a GET request hits the root path, we respond. Simple. But in the real world, we aren't just sending strings; we're sending data.

Installing the Gear You Actually Need

If we want our API to speak JSON, we can't just assume the server knows how to turn a Kotlin object into a JSON string. We have to install the "JSON equipment." This is where ContentNegotiation comes in. I highly recommend using kotlinx.serialization because it's the official Kotlin way and keeps everything type-safe.

import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.Serializable

@Serializable
data class Book(val id: Int, val title: String, val author: String)

fun Application.module() {
    install(ContentNegotiation) {
        json() // This "installs" the JSON serializer
    }
    
    // Now we can return Book objects directly!
}

By installing this plugin, Ktor automatically looks at the Accept header of the incoming request. If the client says "I want JSON," Ktor uses that plugin to serialize your data objects automatically. It's a huge time-saver.

Defining Your Menu with Routes

Let's build a real scenario: a Book Inventory API. We need a way to get all books and a way to add a new one. I like to keep my routing organized by grouping related endpoints together. Since we've already handled the JSON installation, we can just pass our Book data classes straight into the respond method.

import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.routing.*
import io.ktor.server.response.*

val bookInventory = mutableListOf(
    Book(1, "Atomic Kotlin", "Bruce Eckel"),
    Book(2, "Kotlin in Action", "Dmitry Jemerov")
)

fun Application.configureRouting() {
    routing {
        route("/books") {
            get {
                // Return the whole list as JSON
                call.respond(bookInventory)
            }
            post {
                // Receive the book object from the request body
                val newBook = call.receive<Book>()
                bookInventory.add(newBook)
                call.respond(io.ktor.http.HttpStatusCode.Created, newBook)
            }
        }
    }
}

One thing I've learned the hard way: always be explicit with your HTTP status codes. When you create a resource via a POST request, don't just return 200 OK. Return 201 Created. It makes your API feel professional and predictable for whoever is consuming it.




📋 Practical Task

Build a Personal Task-Tracker API

It's time to put this into practice. You are going to build a small API to manage a to-do list. Your API needs to handle Task objects, which should have an id (Int), a description (String), and an isCompleted (Boolean) field.

Requirements:

  • Set up an embeddedServer using Netty on port 8080.
  • Install the ContentNegotiation plugin with json() support.
  • Create a mutableListOf to act as your in-memory database for tasks.
  • Implement a GET /tasks endpoint that returns the full list of tasks.
  • Implement a POST /tasks endpoint that accepts a Task object and adds it to the list.
  • Implement a PATCH /tasks/{id} endpoint that finds a task by its ID and toggles its isCompleted status.

Testing Tip: Use a tool like Postman, Insomnia, or even curl to send your POST and PATCH requests. Make sure your Task class is marked with @Serializable!

Rating
0 0

There are no comments for now.

to be the first to leave a comment.