Swagger/OpenAPI 为 Kotlin 生成代码:完整指南
现代 REST API 的开发需要自动化处理日常任务。最有效的方法之一是基于 OpenAPI(原 Swagger)规范生成代码。在本文中,我们将详细介绍如何使用 Swagger/OpenAPI 生成工具为 Kotlin 语言生成代码,有哪些可用的库以及如何正确使用它们。
什么是 Swagger/OpenAPI,为什么 Kotlin 开发者需要它?
OpenAPI 是一种以 YAML 或 JSON 格式描述 REST API 的标准。它允许:
- 为 Android 应用自动生成客户端代码
- 创建服务器端存根和控制器
- 保持文档的实时更新
- 加速后端和前端并行开发的团队协作
对于既用于服务器端开发(Ktor, Spring Boot)又用于移动应用(Android)的 Kotlin 来说,从 OpenAPI 生成代码已成为不可或缺的工具。
Kotlin 的主要代码生成工具
1. OpenAPI Generator(官方生成器)
最流行的工具是 OpenAPI Generator。它支持多种语言和框架,包括 Kotlin。
通过 Gradle 安装:
plugins { id("org.openapi.generator") version "7.2.0"}
openApiGenerate { generatorName.set("kotlin") inputSpec.set("$rootDir/src/main/resources/openapi.yaml") outputDir.set("$buildDir/generated") packageName.set("com.example.api") configOptions.set(mapOf( "dateLibrary" to "kotlinx-datetime", "useCoroutines" to "true" ))}2. 为 Spring Boot 生成客户端
如果您的服务器是用 Spring Boot 编写的,您可以生成 Kotlin 客户端:
openApiGenerate { generatorName.set("kotlin-spring") inputSpec.set("${projectDir}/api-spec.yaml") outputDir.set("${buildDir}/generated") apiPackage.set("com.example.api") modelPackage.set("com.example.model") configOptions.set(mapOf( "library" to "spring-boot", "useTags" to "true" ))}3. 为 Ktor 生成代码
Ktor 是一个现代的 Kotlin 异步框架。OpenAPI Generator 也支持它:
openApiGenerate { generatorName.set("kotlin-ktor") inputSpec.set("api.yaml") outputDir.set("generated") configOptions.set(mapOf( "dateLibrary" to "kotlinx-datetime", "serializationLibrary" to "kotlinx_serialization" ))}工作示例:从规范到代码
考虑一个简单的例子。假设我们有一个规范 pets.yaml:
openapi: "3.0.0"info: title: Pet Store API version: "1.0"paths: /pets: get: operationId: listPets responses: '200': description: OK content: application/json: schema: type: array items: $ref: '#/components/schemas/Pet'components: schemas: Pet: type: object properties: id: type: integer name: type: string生成后,我们将得到:
// Pet.kt (生成的 data class)data class Pet( val id: Int, val name: String)
// PetsApi.kt (生成的接口)interface PetsApi { suspend fun listPets(): List<Pet>}高级设置与自定义
使用自定义 Mustache 模板
OpenAPI Generator 使用 Mustache 模板。您可以覆盖它们:
openApiGenerate { templateDir.set("$rootDir/templates/kotlin") // 添加