Ktor is a lightweight, asynchronous web framework that makes it easy to create high-performance RESTful APIs. Building RESTful APIs using Ktor is a great choice for Kotlin developers. In this blog, we’ll see how we can build a simple RESTful API using Ktor. Let’s get started:
Prerequisites
- Basic knowledge of Kotlin programming language
- JDK (Java Development Kit) installed
- A code editor (e.g., IntelliJ IDEA, Visual Studio Code)
- cURL or Postman for testing the API endpoints
Step 1. Go to https://ktor.io/create/ and from there generate a new ktor project and add routing plugin. It will download a sample ktor project for you.
Step 2. Add the following dependency in your project
dependencies{
implementation("io.ktor:ktor-serialization-gson:$ktor_version")
implementation("io.ktor:ktor-server-content-negotiation:$ktor_version")
}
Step 3. Application.kt is the main entry point of our application
Step 4. Define Data Model given as below, for example we’re taking a ToDo app data model.
data class Todo(val id: Int, val title: String, val completed: Boolean)
Step 5: Implement the API Endpoints
define the API endpoints under the routing
block, and also define in memory storage list before it.
val todos = mutableListOf<Todo>()
var currentId = 1
routing {
route("/todos") {
get {
call.respond(todos)
}
get("/{id}") {
val id = call.parameters["id"]?.toIntOrNull()
val todo = todos.find { it.id == id }
if (todo != null) {
call.respond(todo)
} else {
call.respond(HttpStatusCode.NotFound)
}
}
post {
val todo = call.receive<Todo>()
val newTodo = todo.copy(id = currentId++)
todos.add(newTodo)
call.respond(HttpStatusCode.Created, newTodo)
}
put("/{id}") {
val id = call.parameters["id"]?.toIntOrNull()
val todoIndex = todos.indexOfFirst { it.id == id }
if (todoIndex != -1) {
val updatedTodo = call.receive<Todo>()
todos[todoIndex] = updatedTodo.copy(id = id!!)
call.respond(HttpStatusCode.OK, updatedTodo)
} else {
call.respond(HttpStatusCode.NotFound)
}
}
delete("/{id}") {
val id = call.parameters["id"]?.toIntOrNull()
if (todos.removeIf { it.id == id }) {
call.respond(HttpStatusCode.NoContent)
} else {
call.respond(HttpStatusCode.NotFound)
}
}
}
}
Step 6. Run the Application
Run the main
function in your Application.kt
file.
Step 7. Test the Endpoints
Use tools like Postman or cURL to test your API endpoints:
- Create a new Todo item:
POSThttp://localhost:8080/todos

similarly, We can test other end points.
Conclusion
In conclusion, building RESTful APIs with Ktor offers a powerful and efficient solution for developing web applications in Kotlin. Throughout this blog post, we explored the fundamental steps involved in creating a RESTful API using Ktor, along with a practical example of building a Todo List API.
If you’re new to kotlin, you can explore about kotlin from here!