引言
Kotlin 是一种现代、简洁且安全的编程语言,在服务器端应用开发中越来越受欢迎。由于其与 Java 的兼容性以及 Ktor 等强大框架的支持,您可以在半小时内创建一个完整的 REST API。在本文中,我们将展示如何使用 Ktor 框架在 Kotlin 中编写 REST API,即使您是初学者也能轻松上手。
我们将创建一个简单的任务管理应用 (Todo API),支持 CRUD 操作:创建、读取、更新和删除。按照本指南操作,整个过程不会超过 30 分钟。
1. 项目准备与依赖
首先,您需要 IntelliJ IDEA (Community Edition) 和 Gradle。我们将创建一个支持 Ktor 的新 Kotlin 项目。
步骤 1: 创建 Gradle 项目
打开 IntelliJ IDEA 并创建一个新项目:File → New → Project。选择 Gradle 并指定语言为 Kotlin。点击 Finish。
步骤 2: 添加 Ktor 依赖
打开 build.gradle.kts 文件并添加以下依赖:
plugins {
kotlin("jvm") version "1.9.0"
application
}
repositories {
mavenCentral()
}
dependencies {
implementation("io.ktor:ktor-server-core:2.3.0")
implementation("io.ktor:ktor-server-netty:2.3.0")
implementation("io.ktor:ktor-server-content-negotiation:2.3.0")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.0")
implementation("ch.qos.logback:logback-classic:1.4.11")
}
application {
mainClass.set("ApplicationKt")
}
点击右上角的 Sync Now 按钮以加载依赖。
2. 创建数据模型和服务
在编写路由之前,我们先定义任务的数据模型和一个简单的内存数据存储服务。
TodoItem 模型
在 src/main/kotlin 文件夹中创建 TodoItem.kt 文件:
import kotlinx.serialization.Serializable
@Serializable
data class TodoItem(
val id: Int,
val title: String,
val completed: Boolean = false
)
TodoService 服务
创建 TodoService.kt 文件:
import java.util.concurrent.atomic.AtomicInteger
class TodoService {
private val items = mutableListOf<TodoItem>()
private val idCounter = AtomicInteger(1)
fun getAll(): List<TodoItem> = items.toList()
fun getById(id: Int): TodoItem? = items.find { it.id == id }
fun create(title: String): TodoItem {
val newItem = TodoItem(id = idCounter.getAndIncrement(), title = title)
items.add(newItem)
return newItem
}
fun update(id: Int, title: String?, completed: Boolean?): TodoItem? {
val index = items.indexOfFirst { it.id == id }
if (index == -1) return null
val current = items[index]
val updated = current.copy(
title = title ?: current.title,
completed = completed ?: current.completed
)
items[index] = updated
return updated
}
fun delete(id: Int): Boolean = items.removeAll { it.id == id }
}
3. 配置服务器和路由
现在创建主应用文件 Application.kt 并编写 REST API 路由。
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.routing.*
import io.ktor.server.response.*
import io.ktor.server.request.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.contentnegotiation.*
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
configureSerialization()
configureRouting()
}.start(wait = true)
}
fun