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
60: Building APIs with Ktor
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
ContentNegotiationplugin. - 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
embeddedServerusing Netty on port 8080. - Install the
ContentNegotiationplugin withjson()support. - Create a
mutableListOfto act as your in-memory database for tasks. - Implement a
GET /tasksendpoint that returns the full list of tasks. - Implement a
POST /tasksendpoint that accepts aTaskobject and adds it to the list. - Implement a
PATCH /tasks/{id}endpoint that finds a task by its ID and toggles itsisCompletedstatus.
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!
There are no comments for now.