如何在 Kotlin 中使用 Ktor 建立 RESTful API
程式碼範例: tutorial-server-restful-api
使用的外掛程式:Routing路由是伺服器應用程式中處理傳入請求的核心外掛程式。、Static Content了解如何服務靜態內容,例如樣式表、指令碼、圖片等。、 Content NegotiationContentNegotiation 外掛程式有兩個主要用途:在用戶端與伺服器之間協商媒體類型,以及將內容以特定格式進行序列化/反序列化。、kotlinx.serialization
在本教學中,我們將說明如何使用 Kotlin 和 Ktor 建置後端服務,並以產生 JSON 檔案的 RESTful API 為例。
在上一篇教學透過建置任務管理器應用程式,學習在 Kotlin 中使用 Ktor 進行路由、處理請求與參數的基本概念。中,我們向您介紹了驗證、錯誤處理和單元測試的基礎知識。本教學將藉由建立一個用於管理任務的 RESTful 服務,進一步擴充這些主題。
您將學習如何執行以下操作:
- 建立使用 JSON 序列化的 RESTful 服務。
- 理解 Content NegotiationContentNegotiation 外掛程式有兩個主要用途:在用戶端與伺服器之間協商媒體類型,以及將內容以特定格式進行序列化/反序列化。 的流程。
- 在 Ktor 中定義 REST API 的路由。
先決條件
您可以獨立閱讀並完成本教學,但我們強烈建議您先完成上一篇教學,以了解如何處理請求並產生回應透過建置任務管理器應用程式,學習在 Kotlin 中使用 Ktor 進行路由、處理請求與參數的基本概念。。
我們建議您安裝 IntelliJ IDEA,但您也可以選擇使用其他慣用的 IDE。
Hello RESTful 任務管理器
在本教學中,您將把現有的任務管理器(Task Manager)改寫為 RESTful 服務。為此,您將使用數個 Ktor 外掛程式外掛程式提供常見的功能性,例如序列化、內容編碼、壓縮等。。
雖然您可以手動將其新增至現有專案中,但產生一個新專案並逐步加入上一篇教學中的程式碼會更簡單。您將在進行過程中重新演練所有程式碼,因此手邊沒有上一個專案也沒關係。
建立包含外掛程式的新專案
在 Project artifact 欄位中,輸入 com.example.ktor-rest-task-app 作為專案產物的名稱。

在外掛程式區段中,搜尋並點擊 Add 按鈕以新增以下外掛程式:
- Content Negotiation
- kotlinx.serialization
- Static Content
新增外掛程式後,您將看到專案設定下方列出了所有外掛程式。 
點擊 Download 按鈕以產生並下載您的 Ktor 專案。
新增初始程式碼
按照先前在建立、開啟和執行 Ktor 專案教學中所述,在 IntelliJ IDEA 中開啟您的專案。
導覽至 src/main/kotlin 並建立名為 model 的子套件。
在 model 套件中,建立一個新的 Task.kt 檔案。
開啟 Task.kt 檔案,新增一個表示優先等級的
enum和一個表示任務的class:kotlinpackage com.example.model import kotlinx.serialization.Serializable enum class Priority { Low, Medium, High, Vital } @Serializable data class Task( val name: String, val description: String, val priority: Priority )在上一篇教學中,您使用擴充函式將
Task轉換為 HTML。而在這裡,Task類別標註了來自kotlinx.serialization程式庫的Serializable型別。開啟 Routing.kt 檔案,並將現有程式碼替換為以下實作:
kotlinpackage com.example import com.example.model.* import io.ktor.server.application.* import io.ktor.server.http.content.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Application.configureRouting() { routing { staticResources("static", "static") get("/tasks") { call.respond( listOf( Task("cleaning", "Clean the house", Priority.Low), Task("gardening", "Mow the lawn", Priority.Medium), Task("shopping", "Buy the groceries", Priority.High), Task("painting", "Paint the fence", Priority.Medium) ) ) } } }與上一篇教學類似,您為 URL
/tasks的 GET 請求建立了一條路由。這次您不再需要手動轉換任務清單,而是直接回傳該清單。在 IntelliJ IDEA 中,點擊執行按鈕 (
) 以啟動應用程式。
在瀏覽器中前往 http://0.0.0.0:8080/tasks。您應該會看到 JSON 格式的任務清單,如下所示:

顯然系統已經為我們完成了大量工作。這背後究竟發生了什麼?
理解 Content Negotiation
透過瀏覽器進行內容協商
在建立專案時,您加入了 Content NegotiationContentNegotiation 外掛程式有兩個主要用途:在用戶端與伺服器之間協商媒體類型,以及將內容以特定格式進行序列化/反序列化。 外掛程式。此外掛程式會檢查用戶端能夠呈現的內容類型,並將其與目前服務所能提供的內容類型進行比對。這就是
在 HTTP 中,用戶端透過 Accept 標頭表明其可呈現的內容類型。此標頭的值為一個或多個內容類型。在上述範例中,您可以透過瀏覽器內建的開發人員工具來檢查此標頭的值。
請參考以下範例:
text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7請注意其中包含的 */*。此標頭表明它接受 HTML、XML 或圖片,但同時也接受任何其他內容類型。
Content Negotiation 外掛程式需要找到一種格式來將資料傳回瀏覽器。如果您查看專案中產生的程式碼,會在 src/main/kotlin 內找到名為 Serialization.kt 的檔案,其中包含以下內容:
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
} 這段程式碼安裝了 ContentNegotiation 外掛程式,同時也設定了 kotlinx.serialization 外掛程式。藉此,當用戶端發送請求時,伺服器即可回傳序列化為 JSON 的物件。
在瀏覽器發出請求的情況下,ContentNegotiation 外掛程式知道自己只能回傳 JSON,而瀏覽器會嘗試顯示接收到的任何內容。因此,請求得以成功執行。
透過 JavaScript 進行內容協商
為了模擬此情境,請開啟 src/main/resources/static 內的 index.html 頁面,並將預設內容替換為以下內容:
html<html> <head> <title>A Simple SPA For Tasks</title> <script type="application/javascript"> function fetchAndDisplayTasks() { fetchTasks() .then(tasks => displayTasks(tasks)) } function fetchTasks() { return fetch( "/tasks", { headers: { 'Accept': 'application/json' } } ).then(resp => resp.json()); } function displayTasks(tasks) { const tasksTableBody = document.getElementById("tasksTableBody") tasks.forEach(task => { const newRow = taskRow(task); tasksTableBody.appendChild(newRow); }); } function taskRow(task) { return tr([ td(task.name), td(task.description), td(task.priority) ]); } function tr(children) { const node = document.createElement("tr"); children.forEach(child => node.appendChild(child)); return node; } function td(text) { const node = document.createElement("td"); node.appendChild(document.createTextNode(text)); return node; } </script> </head> <body> <h1>Viewing Tasks Via JS</h1> <form action="javascript:fetchAndDisplayTasks()"> <input type="submit" value="View The Tasks"> </form> <table> <thead> <tr><th>Name</th><th>Description</th><th>Priority</th></tr> </thead> <tbody id="tasksTableBody"> </tbody> </table> </body> </html>此頁面包含一個 HTML 表單和一個空表格。提交表單後,JavaScript 事件處理常式會向
/tasks端點發送請求,並將Accept標頭設定為application/json。接著,回傳的資料會被反序列化並新增至 HTML 表格中。在 IntelliJ IDEA 中,點擊重新執行按鈕(
)以重新啟動應用程式。
前往 URL http://0.0.0.0:8080/static/index.html。您應該可以透過點擊 View The Tasks 按鈕來擷取資料:

在實際環境中,通常不會直接在瀏覽器中顯示 JSON。相反地,在瀏覽器中執行的 JavaScript 程式碼會發出請求,然後將回傳的資料作為單頁應用程式(SPA)的一部分進行顯示。通常,此類應用程式是使用像 React、Angular 或 Vue.js 等架構撰寫的。
新增 GET 路由
既然您已經熟悉了內容協商的流程,接下來請繼續將上一篇教學透過建置任務管理器應用程式,學習在 Kotlin 中使用 Ktor 進行路由、處理請求與參數的基本概念。中的功能遷移到本篇教學中。
重用任務儲存庫
您可以直接重用任務的 repository 而無需任何修改,讓我們先完成這一步。
在 model 套件中建立一個新的 TaskRepository.kt 檔案。
開啟 TaskRepository.kt 並加入以下程式碼:
kotlinpackage com.example.model object TaskRepository { private val tasks = mutableListOf( Task("cleaning", "Clean the house", Priority.Low), Task("gardening", "Mow the lawn", Priority.Medium), Task("shopping", "Buy the groceries", Priority.High), Task("painting", "Paint the fence", Priority.Medium) ) fun allTasks(): List<Task> = tasks fun tasksByPriority(priority: Priority) = tasks.filter { it.priority == priority } fun taskByName(name: String) = tasks.find { it.name.equals(name, ignoreCase = true) } fun addTask(task: Task) { if (taskByName(task.name) != null) { throw IllegalStateException("Cannot duplicate task names!") } tasks.add(task) } }
重用 GET 請求的路由
建立儲存庫後,您就可以實作 GET 請求的路由。之前的程式碼可以簡化,因為您不再需要處理將任務轉換為 HTML 的邏輯:
導覽至 src/main/kotlin 中的 Routing.kt 檔案。
使用以下實作更新
Application.configureRouting()函式內的/tasks路由程式碼:kotlinpackage com.example import com.example.model.Priority import com.example.model.TaskRepository import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.http.content.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Application.configureRouting() { routing { staticResources("static", "static") //updated implementation route("/tasks") { get { val tasks = TaskRepository.allTasks() call.respond(tasks) } get("/byName/{taskName}") { val name = call.parameters["taskName"] if (name == null) { call.respond(HttpStatusCode.BadRequest) return@get } val task = TaskRepository.taskByName(name) if (task == null) { call.respond(HttpStatusCode.NotFound) return@get } call.respond(task) } get("/byPriority/{priority}") { val priorityAsText = call.parameters["priority"] if (priorityAsText == null) { call.respond(HttpStatusCode.BadRequest) return@get } try { val priority = Priority.valueOf(priorityAsText) val tasks = TaskRepository.tasksByPriority(priority) if (tasks.isEmpty()) { call.respond(HttpStatusCode.NotFound) return@get } call.respond(tasks) } catch (ex: IllegalArgumentException) { call.respond(HttpStatusCode.BadRequest) } } } } }這樣一來,您的伺服器便能回應以下 GET 請求:
/tasks回傳儲存庫中的所有任務。/tasks/byName/{taskName}回傳依指定的taskName篩選的任務。/tasks/byPriority/{priority}回傳依指定的priority篩選的任務。
在 IntelliJ IDEA 中,點擊重新執行按鈕(
)以重新啟動應用程式。
測試功能
使用瀏覽器
您可以在瀏覽器中測試這些路由。例如,前往 http://0.0.0.0:8080/tasks/byPriority/Medium 以查看所有優先等級為 Medium 且以 JSON 格式顯示的任務:

鑑於這類請求通常來自 JavaScript,進行更精細的測試會更為理想。為此,您可以使用專業工具,例如 Postman。
使用 Postman
在 Postman 中,建立一個 URL 為
http://0.0.0.0:8080/tasks/byPriority/Medium的新 GET 請求。在 Headers 面板中,將 Accept 標頭的值設定為
application/json。點擊 Send 發送請求,並在回應檢視器中查看回應。

使用 HTTP 請求檔案
在專案根目錄中,建立一個新的 REST Task Manager.http 檔案。
開啟 REST Task Manager.http 檔案並加入以下 GET 請求:
httpGET http://0.0.0.0:8080/tasks/byPriority/Medium Accept: application/json若要在 IntelliJ IDEA 中發送請求,請點擊其旁邊的裝訂邊圖示(
)。
這將在 Services 工具視窗中開啟並執行:

在 IntelliJ IDEA Ultimate 中,您可以在 HTTP 請求檔案中執行相同的步驟。
新增 POST 請求的路由
在上一篇教學中,任務是透過 HTML 表單建立的。然而,由於您現在建置的是 RESTful 服務,因此不再需要這麼做。相反地,您將使用 kotlinx.serialization 架構,它會承擔大部分繁重的工作。
開啟 src/main/kotlin 內的 Routing.kt 檔案。
在
Application.configureRouting()函式中新增一個 POST 路由,如下所示:kotlin//... fun Application.configureRouting() { routing { //... route("/tasks") { //... //add the following new route post { try { val task = call.receive<Task>() TaskRepository.addTask(task) call.respond(HttpStatusCode.Created) } catch (ex: IllegalStateException) { call.respond(HttpStatusCode.BadRequest) } catch (ex: SerializationException) { call.respond(HttpStatusCode.BadRequest) } } } } }新增以下匯入語句:
kotlin//... import com.example.model.Task import io.ktor.server.request.receive import kotlinx.serialization.SerializationException當 POST 請求發送至
/tasks時,系統會使用kotlinx.serialization架構將請求主體轉換為Task物件。如果成功,任務將會新增至儲存庫中。如果反序列化流程失敗,伺服器會處理SerializationException;而如果任務名稱重複,則會處理IllegalStateException。重新啟動應用程式。
若要在 Postman 中測試此功能,請建立一個發往 URL
http://0.0.0.0:8080/tasks的新 POST 請求。在 Body 面板中加入以下代表新任務的 JSON 文件:
json{ "name": "cooking", "description": "Cook the dinner", "priority": "High" }
點擊 Send 發送請求。
您可以透過向 http://0.0.0.0:8080/tasks 發送 GET 請求,來驗證任務是否已成功新增。
在 IntelliJ IDEA Ultimate 中,您可以透過在 HTTP 請求檔案中加入以下內容來執行相同的步驟:
http### POST http://0.0.0.0:8080/tasks Content-Type: application/json { "name": "cooking", "description": "Cook the dinner", "priority": "High" }
新增刪除支援
您幾乎已經完成了為服務新增基本操作的工作。這些操作通常統稱為 CRUD(建立 Create、讀取 Read、更新 Update 和刪除 Delete)操作。現在您將實作刪除(Delete)操作。
在 TaskRepository.kt 檔案中,於
TaskRepository物件內加入以下方法,以根據任務名稱刪除任務:kotlinfun removeTask(name: String): Boolean { return tasks.removeIf { it.name == name } }開啟 Routing.kt 檔案,並在
routing()函式中新增一個端點以處理 DELETE 請求:kotlinfun Application.configureRouting() { //... routing { route("/tasks") { //... //add the following function delete("/{taskName}") { val name = call.parameters["taskName"] if (name == null) { call.respond(HttpStatusCode.BadRequest) return@delete } if (TaskRepository.removeTask(name)) { call.respond(HttpStatusCode.NoContent) } else { call.respond(HttpStatusCode.NotFound) } } } } }重新啟動應用程式。
將以下 DELETE 請求新增至您的 HTTP 請求檔案中:
http### DELETE http://0.0.0.0:8080/tasks/gardening若要在 IntelliJ IDEA 中發送 DELETE 請求,請點擊其旁邊的裝訂邊圖示(
)。
您將在 Services 工具視窗中看到回應:

使用 Ktor Client 建立單元測試
到目前為止,您一直使用手動方式測試應用程式,但正如您已經注意到的,這種方法既耗時且無法擴展規模。相反地,您可以實作 JUnit 測試了解如何使用專門的測試引擎來測試您的伺服器應用程式。,使用內建的 client 物件來擷取並反序列化 JSON。
開啟 src/test/kotlin 內的 ServerTest.kt 檔案。
將 ServerTest.kt 檔案的內容替換為以下程式碼:
kotlinpackage com.example import com.example.model.Priority import com.example.model.Task import io.ktor.client.call.* import io.ktor.client.plugins.contentnegotiation.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.serialization.kotlinx.json.* import io.ktor.server.testing.* import kotlin.test.* class ApplicationTest { @Test fun tasksCanBeFoundByPriority() = testApplication { configure() val client = createClient { install(ContentNegotiation) { json() } } val response = client.get("/tasks/byPriority/Medium") val results = response.body<List<Task>>() assertEquals(HttpStatusCode.OK, response.status) val expectedTaskNames = listOf("gardening", "painting") val actualTaskNames = results.map(Task::name) assertContentEquals(expectedTaskNames, actualTaskNames) } @Test fun invalidPriorityProduces400() = testApplication { configure() val response = client.get("/tasks/byPriority/Invalid") assertEquals(HttpStatusCode.BadRequest, response.status) } @Test fun unusedPriorityProduces404() = testApplication { configure() val response = client.get("/tasks/byPriority/Vital") assertEquals(HttpStatusCode.NotFound, response.status) } @Test fun newTasksCanBeAdded() = testApplication { configure() val client = createClient { install(ContentNegotiation) { json() } } val task = Task("swimming", "Go to the beach", Priority.Low) val response1 = client.post("/tasks") { header( HttpHeaders.ContentType, ContentType.Application.Json ) setBody(task) } assertEquals(HttpStatusCode.Created, response1.status) val response2 = client.get("/tasks") assertEquals(HttpStatusCode.OK, response2.status) val taskNames = response2 .body<List<Task>>() .map { it.name } assertContains(taskNames, "swimming") } }請注意,您需要在 Ktor client 中安裝
ContentNegotiation和kotlinx.serialization外掛程式,方式與在伺服器端相同。將以下相依性新增至您的 build.gradle.kts 檔案中:
kotlintestImplementation(ktorLibs.client.contentNegotiation)
使用 JsonPath 建立單元測試
使用 Ktor client 或類似的程式庫測試服務非常方便,但從品質保證(QA)的角度來看存在一個缺點。由於伺服器不直接處理原始 JSON,因此無法完全確保其對 JSON 結構的假設是否正確。
例如以下假設:
- 值被儲存在
array中,但實際上使用的是object。 - 屬性被儲存為
numbers,但實際上它們是strings。 - 成員依宣告順序進行序列化,但事實上並非如此。
如果您的服務旨在供多個用戶端使用,那麼對 JSON 結構保持信心至關重要。為了達成此目標,可以使用 Ktor Client 從伺服器擷取文字,然後使用 JSONPath 程式庫來分析此內容。
開啟 gradle/libs.versions.toml 檔案,並在其中定義 JSONPath 版本及其程式庫別名:
toml[versions] json-path = "2.9.0" [libraries] json-path = { module = "com.jayway.jsonpath:json-path", version.ref = "json-path" }在您的 build.gradle.kts 檔案中,將 JSONPath 程式庫新增至
dependencies區塊:kotlintestImplementation(libs.json.path)導覽至 src/test/kotlin 資料夾並建立一個新的 ApplicationJsonPathTest.kt 檔案。
開啟 ApplicationJsonPathTest.kt 檔案並加入以下內容:
kotlinpackage com.example import com.jayway.jsonpath.DocumentContext import com.jayway.jsonpath.JsonPath import io.ktor.client.* import com.example.model.Priority import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.testing.* import kotlin.test.* class ApplicationJsonPathTest { @Test fun tasksCanBeFound() = testApplication { configure() val jsonDoc = client.getAsJsonPath("/tasks") val result: List<String> = jsonDoc.read("$[*].name") assertEquals("cleaning", result[0]) assertEquals("gardening", result[1]) assertEquals("shopping", result[2]) } @Test fun tasksCanBeFoundByPriority() = testApplication { configure() val priority = Priority.Medium val jsonDoc = client.getAsJsonPath("/tasks/byPriority/$priority") val result: List<String> = jsonDoc.read("$[?(@.priority == '$priority')].name") assertEquals(2, result.size) assertEquals("gardening", result[0]) assertEquals("painting", result[1]) } suspend fun HttpClient.getAsJsonPath(url: String): DocumentContext { val response = this.get(url) { accept(ContentType.Application.Json) } return JsonPath.parse(response.bodyAsText()) } }JsonPath 查詢的運作方式如下:
$[*].name表示「將文件視為陣列,並傳回每個項目的 name 屬性值」。$[?(@.priority == '$priority')].name表示「傳回陣列中 priority 等於提供值之所有項目的 name 屬性值」。
您可以使用這類查詢來確認自己對回傳 JSON 的理解是否正確。當您進行程式碼重構和服務重新部署時,序列化過程中的任何修改都會被辨識出來,即使這些修改不會破壞目前架構的反序列化。這使您能夠充滿信心地重新發布公開可用的 API。
後續步驟
恭喜!您現已成功為任務管理器應用程式建立了 RESTful API 服務,並掌握了使用 Ktor Client 和 JsonPath 進行單元測試的精髓。
請繼續閱讀下一篇教學了解如何使用 Ktor 和 Thymeleaf 範本在 Kotlin 中建置網站。,以了解如何重用您的 API 服務來建置 Web 應用程式。
