Skip to content

如何在 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 Negotiation)ContentNegotiation 插件有两个主要用途:在客户端和服务器之间协商媒体类型,以及以特定格式序列化/反序列化内容。的过程。
  • 在 Ktor 中定义 REST API 的路由。

前提条件

你可以独立学习本教程,不过,我们强烈建议你先完成上一篇教程,了解如何处理请求并生成响应通过构建一个任务管理器应用程序,学习在 Kotlin 中使用 Ktor 处理路由、请求和形参的基础知识。。

我们建议你安装 IntelliJ IDEA,不过你也可以选择其他喜欢的 IDE。

Hello RESTful 任务管理器

在本教程中,你将把现有的任务管理器重写为 RESTful 服务。为此,你将使用多个 Ktor 插件插件提供常见功能性,例如序列化、内容编码、压缩等。。

虽然你可以手动将其添加到现有项目中,但生成一个新项目然后逐步添加上一篇教程中的代码会更简单。后续会逐步重述所有代码,因此你手头没有之前的项目也没关系。

创建带有插件的新项目

  1. 访问 Ktor 项目生成器。

  2. 在 Project artifact 字段中,输入 com.example.ktor-rest-task-app 作为项目工件的名称。 在 Ktor 项目生成器中命名项目工件

  3. 在插件部分搜索并通过点击 Add 按钮添加以下插件:

    1. Content Negotiation
    2. kotlinx.serialization
    3. Static Content

    在 Ktor 项目生成器中添加插件 添加插件后,你将在项目设置下方看到列出的所有插件。 Ktor 项目生成器中的插件列表

  4. 点击 Download 按钮以生成并下载你的 Ktor 项目。

添加初始代码

  1. 在 IntelliJ IDEA 中打开你的项目,如之前的创建、打开和运行 Ktor 项目教程中所述。

  2. 导航至 src/main/kotlin 并创建一个名为 model 的子包。

  3. 在 model 包内,新建一个 Task.kt 文件。

  4. 打开 Task.kt 文件,添加一个表示优先级的 enum 和一个表示任务的 class:

    kotlin
    package 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 类型进行了注解。

  5. 打开 Routing.kt 文件,并将现有代码替换为以下实现:

    kotlin
    package 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 请求创建了一条路由。这次,你不再需要手动转换任务列表,而是直接返回该列表。

  6. 在 IntelliJ IDEA 中,点击运行按钮 (IntelliJ IDEA 运行图标) 以启动应用程序。

  7. 在浏览器中访问 http://0.0.0.0:8080/tasks。你应该会看到 JSON 格式的任务列表,如下所示:

  8. 浏览器屏幕中显示的 JSON 数据

    显而易见,底层为我们完成了许多工作。这背后到底发生了什么?

理解内容协商 (Content Negotiation)

通过浏览器进行内容协商

创建项目时,你添加了 Content NegotiationContentNegotiation 插件有两个主要用途:在客户端和服务器之间协商媒体类型,以及以特定格式序列化/反序列化内容。 插件。该插件会检查客户端能够呈现的内容类型,并将其与当前服务可以提供的内容类型进行匹配。因此被称为 内容协商 (Content Negotiation)。

在 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 的文件,其中包含以下内容:

kotlin
fun Application.configureSerialization() {
    install(ContentNegotiation) {
        json()
    }
}

这段代码安装了 ContentNegotiation 插件,并配置了 kotlinx.serialization 插件。这样,当客户端发送请求时,服务器便可以返回序列化为 JSON 的对象。

对于来自浏览器的请求,ContentNegotiation 插件知道它只能返回 JSON,而浏览器会尝试显示发送给它的任何内容,因此请求成功执行。

通过 JavaScript 进行内容协商

    在生产环境中,通常不会直接在浏览器中显示 JSON。相反,在浏览器中运行的 JavaScript 代码会发起请求,然后将返回的数据作为单页应用 (SPA) 的一部分进行显示。通常,此类应用程序是使用诸如 React、Angular 或 Vue.js 等框架编写的。

  1. 为了模拟这种情况,请打开 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 表格中。

  2. 在 IntelliJ IDEA 中,点击重新运行按钮(IntelliJ IDEA 重新运行图标)以重启应用程序。

  3. 访问 URL http://0.0.0.0:8080/static/index.html。点击 View The Tasks 按钮应该就能获取数据:

    显示按钮以及以 HTML 表格形式显示任务的浏览器窗口

添加 GET 路由

既然你已经熟悉了内容协商的过程,接下来就继续将上一篇教程通过构建一个任务管理器应用程序,学习在 Kotlin 中使用 Ktor 处理路由、请求和形参的基础知识。中的功能迁移到本教程中。

复用任务仓库

你可以直接复用任务仓库而无需任何修改,我们先来完成这一步。

  1. 在 model 包内新建一个 TaskRepository.kt 文件。

  2. 打开 TaskRepository.kt 并添加以下代码:

    kotlin
    package 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:

  1. 导航至 src/main/kotlin 中的 Routing.kt 文件。

  2. 将 Application.configureRouting() 函数内 /tasks 路由的代码更新为以下实现:

    kotlin
    package 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 筛选出的任务。
  3. 在 IntelliJ IDEA 中,点击重新运行按钮(IntelliJ IDEA 重新运行图标)以重启应用程序。

测试功能

使用浏览器

    你可以在浏览器中测试这些路由。例如,访问 http://0.0.0.0:8080/tasks/byPriority/Medium 即可查看以 JSON 格式显示的所有优先级为 Medium 的任务:

    显示以 JSON 格式呈现中等优先级任务的浏览器窗口

    鉴于此类请求通常来自 JavaScript,更细粒度的测试会是更好的选择。为此,你可以使用专门的工具,例如 Postman。

使用 Postman

  1. 在 Postman 中,新建一个 URL 为 http://0.0.0.0:8080/tasks/byPriority/Medium 的 GET 请求。

  2. 在 Headers 窗格中,将 Accept 标头的值设置为 application/json。

  3. 点击 Send 发送请求,并在响应查看器中查看响应结果。

    Postman 中的 GET 请求,显示以 JSON 格式呈现的中等优先级任务

使用 HTTP 请求文件

    在 IntelliJ IDEA Ultimate 中,你可以在 HTTP 请求文件中执行相同的步骤。

  1. 在项目根目录下,新建一个 REST Task Manager.http 文件。

  2. 打开 REST Task Manager.http 文件并添加以下 GET 请求:

    http
    GET http://0.0.0.0:8080/tasks/byPriority/Medium
    Accept: application/json
  3. 要在 IntelliJ IDEA 中发送该请求,请点击其旁边的装订区域图标(IntelliJ IDEA 装订区域图标)。

  4. 这将在 Services 工具窗口中打开并运行:

    HTTP 文件中的 GET 请求,显示以 JSON 格式呈现的中等优先级任务
测试路由的另一种方法是在 Kotlin Notebook 中使用 khttp 库。

为 POST 请求添加路由

在上一篇教程中,任务是通过 HTML 表单创建的。不过,既然你现在正在构建 RESTful 服务,就不再需要这样做了。相反,你将使用 kotlinx.serialization 框架,它将替你完成大部分繁重的工作。

  1. 打开 src/main/kotlin 中的 Routing.kt 文件。

  2. 在 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

    当向 /tasks 发送 POST 请求时,kotlinx.serialization 框架将用于把请求体转换为 Task 对象。如果转换成功,任务将被添加到仓库中。如果反序列化过程失败,服务器将处理 SerializationException;而如果任务重复,它将处理 IllegalStateException。

  3. 重启应用程序。

  4. 要在 Postman 中测试此功能,请新建一个指向 URL http://0.0.0.0:8080/tasks 的 POST 请求。

  5. 在 Body 面板中添加以下表示新任务的 JSON 文档:

    json
    {
        "name": "cooking",
        "description": "Cook the dinner",
        "priority": "High"
    }
    Postman 中用于添加新任务的 POST 请求
  6. 点击 Send 发送请求。

  7. 你可以通过向 http://0.0.0.0:8080/tasks 发送 GET 请求来验证任务是否已添加。

  8. 在 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(创建、读取、更新和删除)操作。现在你将实现删除操作。

  1. 在 TaskRepository.kt 文件的 TaskRepository 对象中添加以下方法,以根据名称删除任务:

    kotlin
    fun removeTask(name: String): Boolean {
        return tasks.removeIf { it.name == name }
    }
  2. 打开 Routing.kt 文件,并在 routing() 函数中添加一个端点来处理 DELETE 请求:

    kotlin
    fun 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)
                    }
                }
            }
        }
    }
  3. 重启应用程序。

  4. 在你的 HTTP 请求文件中添加以下 DELETE 请求:

    http
    ###
    
    DELETE http://0.0.0.0:8080/tasks/gardening
  5. 要在 IntelliJ IDEA 中发送 DELETE 请求,请点击其旁边的装订区域图标(IntelliJ IDEA 装订区域图标)。

  6. 你将在 Services 工具窗口中看到响应:

    HTTP 请求文件中的 DELETE 请求

使用 Ktor Client 创建单元测试

到目前为止,你一直在手动测试应用程序,但正如你已经注意到的那样,这种方法非常耗时且无法扩展。相反,你可以实现 JUnit 测试了解如何使用专用的测试引擎测试您的服务器应用程序。,使用内置的 client 对象来获取并反序列化 JSON。

  1. 打开 src/test/kotlin 中的 ServerTest.kt 文件。

  2. 将 ServerTest.kt 文件的内容替换为以下内容:

    kotlin
    package 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")
        }
    }

    请注意,你需要以在服务器端相同的方式,将 ContentNegotiation 和 kotlinx.serialization 插件安装到 Ktor Client 中。

  3. 在你的 build.gradle.kts 文件中添加以下依赖项:

    kotlin
    testImplementation(ktorLibs.client.contentNegotiation)

使用 JsonPath 创建单元测试

使用 Ktor Client 或类似库来测试你的服务虽然很方便,但从质量保证 (QA) 的角度来看存在一个缺点。由于服务器不直接处理 JSON,因此无法确定其对 JSON 结构的假设是否正确。

例如以下假设:

  • 值存储在 array 中,而实际上使用的是 object。
  • 属性存储为 numbers,而它们实际上是 strings。
  • 成员按声明顺序序列化,而实际上并非如此。

如果你的服务打算供多个客户端使用,对 JSON 结构充满信心至关重要。为此,可以使用 Ktor Client 从服务器检索文本,然后使用 JSONPath 库分析该内容。

  1. 打开 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" }
  2. 在你的 build.gradle.kts 文件中,将 JSONPath 库添加到 dependencies 代码块中:

    kotlin
    testImplementation(libs.json.path)
  3. 导航至 src/test/kotlin 文件夹并新建一个 ApplicationJsonPathTest.kt 文件。

  4. 打开 ApplicationJsonPathTest.kt 文件并将以下内容添加到其中:

    kotlin
    package 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 表示“返回数组中优先级等于所提供值的每个条目的 name 属性值”。

    你可以使用此类查询来确认你对返回的 JSON 的理解。当你进行代码重构和服务重新部署时,任何序列化方面的修改都会被发现,即便它们没有破坏当前框架下的反序列化。这让你可以放心地重新发布公开可用的 API。

后续步骤

恭喜!你现在已经完成了为任务管理器应用程序创建 RESTful API 服务的工作,并了解了使用 Ktor Client 和 JsonPath 进行单元测试的方方面面。

继续阅读 下一篇教程了解如何使用 Ktor 和 Thymeleaf 模板在 Kotlin 中构建网站。 ,了解如何复用你的 API 服务来构建 Web 应用程序。