使用 Kotlin 构建 GraphQL API:逐步实践教程

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

引言:为什么选择 GraphQL 和 Kotlin?

\n

在现代 Web 开发中,选择正确的 API 构建方法可能决定整个项目的成败。由 Facebook 开发的 GraphQL 提供了 REST 的灵活替代方案,允许客户端只请求他们真正需要的数据。而 Kotlin,一种用于 JVM 的现代编程语言,则在此基础上增加了简洁性、空安全性和对协程的强大支持。

\n

在本教程中,我们将使用 Kotlin 和 graphql-kotlin-spring-server 框架,在实践中创建一个完整的 GraphQL API。您将学习如何配置服务器、定义数据模式、编写解析器以及测试 API。到文章结束时,您将能够独立地将 GraphQL 集成到您的 Kotlin 项目中。

\n\n

1. 项目设置与依赖项

\n

首先,我们创建一个支持 GraphQL 的 Spring Boot 新项目。我们将使用 Gradle 作为构建系统。

\n\n

1.1. 创建基本结构

\n

在 IntelliJ IDEA 中或通过 Spring Initializr 创建一个新项目。在 build.gradle.kts 中添加以下依赖项:

\n
plugins {\n    id("org.springframework.boot") version "3.2.0"\n    id("io.spring.dependency-management") version "1.1.4"\n    kotlin("jvm") version "1.9.21"\n    kotlin("plugin.spring") version "1.9.21"\n}\n\ndependencies {\n    implementation("org.springframework.boot:spring-boot-starter-web")\n    implementation("com.expediagroup:graphql-kotlin-spring-server:7.0.1")\n    implementation("org.jetbrains.kotlin:kotlin-reflect")\n    implementation("org.jetbrains.kotlin:kotlin-stdlib")\n    testImplementation("org.springframework.boot:spring-boot-starter-test")\n}
\n\n

1.2. 应用程序配置

\n

在 src/main/resources 中创建 application.yml 文件:

\n
server:\n  port: 8080\n\ngraphql:\n  packages:\n    - "com.example.graphqldemo"\n  schema:\n    introspection-enabled: true\n    exception-handlers-enabled: true
\n

这是基本配置。参数 introspection-enabled: true 允许使用 GraphiQL 进行测试。

\n\n

2. 定义 GraphQL 模式

\n

在 graphql-kotlin 中,模式会根据您的数据类(data classes)自动构建。这是主要优势之一——无需编写单独的 SDL 文件。

\n\n

2.1. 创建数据模型

\n

假设我们正在为图书馆创建一个 API。定义模型:

\n
package com.example.graphqldemo.model\n\ndata class Book(\n    val id: String,\n    val title: String,\n    val author: Author,\n    val year: Int,\n    val genre: String\n)\n\ndata class Author(\n    val id: String,\n    val name: String,\n    val books: List<Book> = emptyList()\n)\n\n// 用于变更的输入类型\ndata class BookInput(\n    val title: String,\n    val authorId: String,\n    val year: Int,\n    val genre: String\n)
\n\n

2.2. 数据服务

\n

创建一个简单的内存服务来存储数据:

\n
package com.example.graphqldemo.service\n\nimport com.example.graphqldemo.model.Author\nimport com.example.graphqldemo.model.Book\nimport com.example.graphqldemo.model.BookInput\nimport org.springframework.stereotype.Service\nimport java.util.UUID\n\n@Service\nclass LibraryService {\n    private val authors = mutableListOf(\n        Author("1", "J.K. Rowling"),\n        Author("2", "George Orwell")\n    )\n    private val books = mutableListOf(\n        Book("1", "Harry Potter and the Philosopher's Stone", authors[0], 1997, "Fantasy"),\n        Book("2", "1984", authors[1], 1949, "Dystopia")\n    )\n\n    fun getBooks(): List<Book> = books\n    fun getBookById(id: String): Book? = books.find { it.id == id }\n    fun getAuthors(): List<Author> = authors\n    fun addBook(input: BookInput): Book {\n        val author = authors.fin                

博客

书籍推荐