Kotlin GraphQL 库:后端开发者完整指南

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

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

开始课程

Kotlin GraphQL 库:API 使用完整指南



GraphQL 是一种 API 查询语言,允许客户端只请求他们真正需要的数据。在 Kotlin 生态系统中,有多个强大的库可用于处理 GraphQL。本文将详细介绍三个主要库:graphql-kotlin、Apollo Kotlin 和 KGraphQL,并展示它们的使用示例。



1. graphql-kotlin — Expedia Group 的服务器端库



graphql-kotlin 是用于在 Kotlin 中创建 GraphQL 服务器的最流行库。它完全支持所有 GraphQL 规范功能,并与 Spring Boot、Ktor 和 Micronaut 框架完美集成。



安装与配置



要引入该库,请在 build.gradle.kts 中添加依赖:



dependencies {    // 核心库    implementation("com.expediagroup:graphql-kotlin-spring-server:6.5.0")        // 用于从注解生成模式    implementation("com.expediagroup:graphql-kotlin-schema-generator:6.5.0")}


创建简单的 GraphQL API



定义数据模型和查询解析器:



// 数据模型data class User(val id: Int, val name: String, val email: String)

// 查询解析器class UserQuery : Query { fun getUser(id: Int): User? { return users.find { it.id == id } } companion object { val users = listOf( User(1, "Anna Petrova", "anna@example.com"), User(2, "Ivan Sidorov", "ivan@example.com") ) }}

// 变更解析器class UserMutation : Mutation { fun createUser(name: String, email: String): User { val newUser = User(users.size + 1, name, email) users.add(newUser) return newUser }}


现在在 Spring Boot 配置中注册解析器:



@Configurationclass GraphQLConfig {    @Bean    fun userQuery(): UserQuery = UserQuery()        @Bean    fun userMutation(): UserMutation = UserMutation()}


API 查询



GraphQL 查询示例:



query {  getUser(id: 1) {    name    email  }}


响应将仅包含请求的字段:



{  "data": {    "getUser": {      "name": "Anna Petrova",      "email": "anna@example.com"    }  }}


2. Apollo Kotlin — 适用于 Android 和 JVM 的客户端库



Apollo Kotlin 是一个专为 Kotlin 和 Android 设计的强大 GraphQL 客户端。它提供类型安全的查询和自动代码生成。



引入库



dependencies {    implementation("com.apollographql.apollo:apollo-runtime:3.8.0")    implementation("com.apollographql.apollo:apollo-normalized-cache-sqlite:3.8.0")}


创建查询



首先在 GetUserQuery.graphql 文件中定义 GraphQL 查询:



query GetUser($id: Int!) {  getUser(id: $id) {    id    name    email  }}


然后在 Kotlin 中使用生成的代码:



val apolloClient = ApolloClient.builder()    .serverUrl("http://localhost:8080/graphql")    .build()

suspend fun fetchUser(userId: Int): User? { val response = apolloClient .query(GetUserQuery(userId)) .execute() return response.data?.getUser?.let { user -> User( id = user.id, name = user.name, email = user.email ) }}


3. KGraphQL — 适用于 Ktor 的轻量级库



KGraphQL 是一个极简库,用于在 Ktor 应用中创建 GraphQL 服务器。它

推荐