TL;DR
- Ktor is JetBrains' Kotlin framework for building servers. If you can write a ViewModel, you can write a Ktor API.
- You'll build a small Tasks REST API: list, read, create and delete, with JSON in and out.
- Then you'll test it, handle errors properly, and package it in Docker so it can run anywhere.
- Same language, same coroutines, same
kotlinx.serializationyou already use on Android.
As a mobile developer, you've probably waited on a backend team, or built an app on top of an API you didn't control. The good news: you don't need to learn Node or Python to build your own. Your Kotlin skills already cover most of it.
Prefer video?A full Ktor backend with JWT auth and MongoDB, from my full-stack KMP course
01 Create the project
The quickest start is the project generator at start.ktor.io (also built into IntelliJ IDEA). Pick these plugins:
- Routing: map URLs to code
- Content Negotiation + kotlinx.serialization: JSON in and out
- Status Pages: clean error responses
Your build.gradle.kts will look roughly like this:
plugins {
kotlin("jvm") version "2.2.0"
kotlin("plugin.serialization") version "2.2.0"
id("io.ktor.plugin") version "3.2.0"
}
application {
mainClass.set("com.example.ApplicationKt")
}
val ktor = "3.2.0"
dependencies {
implementation("io.ktor:ktor-server-core:$ktor")
implementation("io.ktor:ktor-server-netty:$ktor")
implementation("io.ktor:ktor-server-content-negotiation:$ktor")
implementation("io.ktor:ktor-server-status-pages:$ktor")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor")
implementation("ch.qos.logback:logback-classic:1.5.18")
testImplementation("io.ktor:ktor-server-test-host:$ktor")
testImplementation("io.ktor:ktor-client-content-negotiation:$ktor")
testImplementation(kotlin("test"))
}
Version numbers move fast. Use whatever the generator gives you; the code in this article works the same way across Ktor 3.x.
02 Start the server
A Ktor app is just a main function that starts an engine (Netty here) and installs a module: an extension function on Application where you configure everything.
fun main() {
// Cloud platforms tell you which port to use through the PORT variable
val port = System.getenv("PORT")?.toInt() ?: 8080
embeddedServer(Netty, port = port, module = Application::module)
.start(wait = true)
}
fun Application.module() {
install(ContentNegotiation) { json() }
configureErrors()
configureRouting(TaskRepository())
}
Run it, open http://localhost:8080, and⦠nothing yet. Let's add routes.
03 Models and a simple store
Models are plain @Serializable data classes, exactly like on Android. For now we'll keep tasks in memory.
Swapping in a real database later only changes this one class.
@Serializable
data class Task(val id: String, val title: String, val done: Boolean = false)
@Serializable
data class NewTask(val title: String)
class TaskRepository {
private val tasks = ConcurrentHashMap<String, Task>()
private val nextId = AtomicInteger(1)
fun all(): List<Task> = tasks.values.sortedBy { it.id.toInt() }
fun find(id: String): Task? = tasks[id]
fun add(title: String): Task {
val task = Task(id = nextId.getAndIncrement().toString(), title = title)
tasks[task.id] = task
return task
}
fun delete(id: String): Boolean = tasks.remove(id) != null
}
Why ConcurrentHashMap? A server handles many requests at the same time, on different threads.
A plain mutableMapOf() isn't safe for that.
04 Add the routes
Routing reads almost like a description of your API. Each handler is a suspend lambda with access to the call: the request coming in and the response going out.
fun Application.configureRouting(repo: TaskRepository) {
routing {
get("/") {
call.respondText("Hello from Ktor π")
}
route("/tasks") {
get {
call.respond(repo.all())
}
get("/{id}") {
val task = repo.find(call.parameters["id"]!!)
?: return@get call.respond(HttpStatusCode.NotFound)
call.respond(task)
}
post {
val body = call.receive<NewTask>()
if (body.title.isBlank()) {
return@post call.respond(HttpStatusCode.BadRequest, mapOf("error" to "title is required"))
}
call.respond(HttpStatusCode.Created, repo.add(body.title.trim()))
}
delete("/{id}") {
val removed = repo.delete(call.parameters["id"]!!)
call.respond(if (removed) HttpStatusCode.NoContent else HttpStatusCode.NotFound)
}
}
}
}
call.receive<NewTask>() turns the JSON body into a Kotlin object, and call.respond(task) turns it back into JSON.
That's Content Negotiation doing its job. Notice the status codes too: 201 for created,
204 for a successful delete, 404 when something doesn't exist. Good APIs say what happened.
05 Try the API
Here's exactly how your API will behave. Send some requests. The responses below are simulated in your browser, but they match the code above.
Tip: try a POST with an empty title, or GET a task you just deleted.
When your real server is running, the same requests work from a terminal:
# create a task
curl -X POST http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"title":"Write my first API"}'
# list all tasks
curl http://localhost:8080/tasks
06 Handle errors like a pro
What happens if someone sends broken JSON? By default, the client gets a vague error. The Status Pages plugin lets you turn exceptions into clear, consistent responses in one place.
fun Application.configureErrors() {
install(StatusPages) {
exception<BadRequestException> { call, cause ->
call.respond(HttpStatusCode.BadRequest, mapOf("error" to "Invalid request body"))
}
exception<Throwable> { call, cause ->
call.application.log.error("Unhandled error", cause)
call.respond(HttpStatusCode.InternalServerError, mapOf("error" to "Something went wrong"))
}
}
}
Never send stack traces to clients. Log the details on the server, and return a short, safe message.
07 Test it without starting a server
testApplication runs your whole module in memory, so tests are fast and need no network.
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation as ClientContentNegotiation
class TasksTest {
@Test
fun `creating a task returns 201`() = testApplication {
application { module() }
val client = createClient {
install(ClientContentNegotiation) { json() }
}
val response = client.post("/tasks") {
contentType(ContentType.Application.Json)
setBody(NewTask("Write tests"))
}
assertEquals(HttpStatusCode.Created, response.status)
assertEquals("Write tests", response.body<Task>().title)
}
@Test
fun `blank title returns 400`() = testApplication {
application { module() }
val response = client.post("/tasks") {
contentType(ContentType.Application.Json)
setBody("""{"title":" "}""")
}
assertEquals(HttpStatusCode.BadRequest, response.status)
}
}
08 Ship it: one jar, one Docker image
The Ktor Gradle plugin can bundle your server and all its dependencies into a single runnable "fat jar":
./gradlew buildFatJar
java -jar build/libs/*-all.jar
Wrap it in Docker and it runs the same on your laptop and in the cloud:
# Stage 1: build the fat jar
FROM gradle:8-jdk21 AS build
WORKDIR /app
COPY . .
RUN gradle buildFatJar --no-daemon
# Stage 2: run it on a small Java runtime
FROM eclipse-temurin:21-jre
COPY --from=build /app/build/libs/*-all.jar /app/server.jar
EXPOSE 8080
CMD ["java", "-jar", "/app/server.jar"]
Most hosting platforms, such as Render, Railway, Fly.io or Google Cloud Run, can deploy straight from a Dockerfile in your
Git repository. Because the server reads the PORT variable, it will listen wherever the platform tells it to.
Check each platform's current pricing; several offer a free or low-cost tier for small projects.
09 What's next
You now have a real, tested, deployable API. To make it production-ready, the usual next steps are:
- A real database, like PostgreSQL with Exposed, or MongoDB, instead of the in-memory map.
- Authentication with JWT, so each user only sees their own tasks.
- Sync endpoints with versions and change logs, so mobile apps can work offline and catch up later.
Build a real backend
Offline-First Android App
Build a Ktor backend with task versioning, change logs, tombstones and cursor-based sync, and connect it to an offline-first Android app.
