- 示例工程
- 教程
- 后端
【免费下载链接】aws-doc-sdk-examples
Welcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.
本文基于 aws-doc-sdk-examples 仓库中 kotlin/services/apigateway/README.md 及其配套源码,系统讲解如何用 AWS SDK for Kotlin 完成 Amazon API Gateway 的核心管理操作,包括创建 REST API、创建部署(Deployment)、查询 API Keys / Deployments / Stages / Method,以及删除 REST API。读完本文,你将掌握 7 个可直接运行的 Kotlin 示例的用法、参数含义、运行方式,以及其背后的测试验证机制,能够独立完成 API Gateway 资源的创建、查询与清理。
前提准备:环境、凭证与安全须知
开发环境与构建工具
这些示例采用 AWS SDK for Kotlin 编写,官方推荐的工程构建方式是使用Gradle配置并构建 AWS SDK for Kotlin 项目。你需要:
- 安装 JDK(Kotlin/JVM 项目所需);
- 安装 Gradle,并建立包含
kotlin("jvm")插件与 AWS SDK for Kotlin 依赖的build.gradle.kts构建脚本; - 通过
dependencies引入aws.sdk.kotlin:apigateway(API Gateway 服务客户端)及所需的 Kotlin 协程支持。
所有示例代码都位于仓库目录 kotlin/services/apigateway/src/main/kotlin/com/kotlin/gateway,包名为com.kotlin.gateway,可直接将其纳入 Gradle 工程的src/main/kotlin下编译运行。
凭证与区域配置
示例统一通过ApiGatewayClient.fromEnvironment { region = "us-east-1" }创建客户端,这意味着程序运行时会从环境变量、共享凭证文件或 IAM 角色中自动读取 AWS 凭证。请确保你的运行环境中已正确配置凭证(例如AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY环境变量,或~/.aws/credentials),并且该凭证对应的 IAM 用户/角色拥有 API Gateway 的相关操作权限。
重要安全提示(务必阅读)
原文档明确提醒以下两点:
- 费用提示:这些示例会对你所指定凭证对应的账号与 AWS 区域执行真实操作,运行后可能产生 AWS 服务费用。
- 破坏性操作警告:部分示例会对 AWS 资源执行破坏性操作,例如删除 RestApi 资源。运行删除或修改资源的操作时务必极其小心,最好创建独立的测试专用资源进行实验,避免影响生产环境。
示例总览
仓库中共提供 7 个 API Gateway 相关示例,覆盖了 API 生命周期管理中最常用的读写操作:
| 示例 | 功能说明 |
|---|---|
| CreateRestApi | 创建一个新的 RestApi 资源 |
| CreateDeployment | 为指定的 RestApi 创建部署(Deployment)资源 |
| DeleteRestApi | 删除一个已存在的 RestApi 资源(破坏性操作) |
| GetAPIKeys | 获取当前账号下的 ApiKeys 资源信息 |
| GetDeployments | 获取指定 RestApi 的部署集合信息 |
| GetMethod | 描述一个已存在的 Method 资源 |
| GetStages | 获取指定 RestApi 的阶段(Stage)信息 |
其中 CreateRestApi / GetDeployments / GetStages / DeleteRestApi 四个操作在测试用例 APIGatewayTest.kt 中构成了一个完整的"创建 → 查询 → 清理"闭环流程,下文会详细拆解。
创建 REST API:CreateRestApi
运行方式与参数
示例入口 CreateRestApi.kt 的main函数接收 1 个命令行参数:
Usage: <restApiId> Where: restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).需要注意的是,原文档将restApiId描述为"已存在的 RestApi 标识",但传入该值后实际被用作新 API 的**名称(name)**传入CreateRestApiRequest,这一点从源码调用可以确认——main中读取参数后调用createAPI(restApiId),而createAPI内部构造请求时将其赋给name字段:
// snippet-start:[apigateway.kotlin.create_api.main] suspend fun createAPI(restApiName: String?): String? { val request = CreateRestApiRequest { description = "Created using the Gateway Kotlin API" name = restApiName } ApiGatewayClient.fromEnvironment { region = "us-east-1" }.use { apiGateway -> val response = apiGateway.createRestApi(request) println("The id of the new api is ${response.id}") return response.id } } // snippet-end:[apigateway.kotlin.create_api.main]关键实现要点
- 请求模型:
CreateRestApiRequest的name用于指定新 API 的名称,description用于描述,示例中固定为"Created using the Gateway Kotlin API"; - 返回结果:调用
apiGateway.createRestApi(request)后,响应对象的id字段即新 RestApi 的字符串标识(形如xxxx99ewyg),该 id 是后续所有查询、部署、删除操作的前提参数; - 协程模型:函数声明为
suspend,所有 AWS SDK for Kotlin 的异步调用都需要在协程作用域中执行,这与 Kotlin 协程生态保持一致; - 客户端生命周期:使用
.use { }扩展函数确保客户端在使用完毕后自动关闭,避免资源泄漏。
创建部署:CreateDeployment
运行方式与参数
CreateDeployment.kt 接收 2 个命令行参数:
Usage: <restApiId> <stageName> Where: restApiId - The string identifier of the associated RestApi. (for example, xxxx99ewyg). stageName - The name of the stage.核心代码
// snippet-start:[apigateway.kotlin.create_deployment.main] suspend fun createNewDeployment(restApiIdVal: String?, stageNameVal: String?): String? { val request = CreateDeploymentRequest { restApiId = restApiIdVal description = "Created using the AWS API Gateway Kotlin API" stageName = stageNameVal } ApiGatewayClient.fromEnvironment { region = "us-east-1" }.use { apiGateway -> val response = apiGateway.createDeployment(request) println("The id of the deployment is " + response.id) return response.id } } // snippet-end:[apigateway.kotlin.create_deployment.main]关键实现要点
CreateDeploymentRequest中的三个核心字段对应了部署(Deployment)的完整语义:
restApiId:目标 RestApi 的标识,表示"为哪个 API 创建部署";stageName:部署目标阶段的名称。在 API Gateway 中,API 修改后必须创建 Deployment 并关联到某个 Stage,外部才能通过该 Stage 的调用 URL 访问 API;description:部署描述,便于在 Deployment 集合中区分不同版本。
调用成功后返回的response.id即部署 id,可打印用于后续追踪。
查询类操作:Deployments、Stages、Method、API Keys
获取部署集合:GetDeployments
GetDeployments.kt 接收 1 个参数<restApiId>,通过GetDeploymentsRequest { restApiId = restApiIdVal }调用apiGateway.getDeployments(request):
val response = apiGateway.getDeployments(request) response.items?.forEach { deployment -> println("The deployment id is ${deployment.id}") println("The deployment description is ${deployment.description}") }响应中的items是该 RestApi 下的部署集合,每个元素包含id与description等属性。从源码结构看,getDeployments返回的是分页集合类型,items为可空列表,因此示例使用?.forEach安全遍历。
获取阶段列表:GetStages
GetStages.kt 同样只接收 1 个参数<restApiId>:
val stagesRequest = GetStagesRequest { restApiId = restApiIdVal } ApiGatewayClient.fromEnvironment { region = "us-east-1" }.use { apiGateway -> val response = apiGateway.getStages(stagesRequest) response.item?.forEach { stage -> println("Stage name is ${stage.stageName}") } }该示例遍历响应中的item列表,打印每个 Stage 的stageName。Stage 对应 API 的部署环境(如prod、test),也是实际提供调用 URL 的入口,stageName在发布和调用环节都至关重要。
获取 Method 详情:GetMethod
GetMethod.kt 需要 3 个参数,是参数最多的示例:
Usage: <restApiId> <resourceId> <httpMethod> Where: restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg). resourceId - The string identifier of an resource. (for example, xxxx99ewyg). httpMethod - The HTTP method. (for example, GET).三个参数分别用于定位"哪个 API 下的哪个资源上的哪种 HTTP 方法",对应GetMethodRequest的restApiId、resourceId、httpMethod字段:
suspend fun getSpecificMethod(restApiIdVal: String?, resourceIdVal: String?, httpMethodVal: String?) { val methodRequest = GetMethodRequest { httpMethod = httpMethodVal restApiId = restApiIdVal resourceId = resourceIdVal } ApiGatewayClient.fromEnvironment { region = "us-east-1" }.use { apiGateway -> val response = apiGateway.getMethod(methodRequest) // Retrieve a method response associated with a given HTTP status code. val details = response.methodResponses if (details != null) { for ((key, value) in details) { println("Key is $key and Value is $value") } } } }示例的重点展示对象是response.methodResponses——这是一个以 HTTP 状态码为键、方法响应配置为值的映射(Map),遍历时逐项打印键值对。这是了解某个 Method 为不同状态码(如 200、404)配置了何种响应模型的最直接方式。
获取 API Keys:GetAPIKeys
GetAPIKeys.kt 是所有示例中唯一无需命令行参数的,main函数直接调用getKeys():
suspend fun getKeys() { ApiGatewayClient.fromEnvironment { region = "us-east-1" }.use { apiGateway -> val response = apiGateway.getApiKeys(GetApiKeysRequest { }) response.items?.forEach { key -> println("Key is $key") } } }它通过空请求GetApiKeysRequest { }拉取当前账号下的所有 API Key,并逐个打印。API Key 常用于标识调用方、配合 Usage Plan 实现流量控制与配额管理;该示例是快速盘点账号内 API Key 资产的便捷工具。
删除 REST API:DeleteRestApi(破坏性操作)
DeleteRestApi.kt 接收 1 个参数<restApiId>,执行删除操作:
suspend fun deleteAPI(restApiIdVal: String?) { val request = DeleteRestApiRequest { restApiId = restApiIdVal } ApiGatewayClient.fromEnvironment { region = "us-east-1" }.use { apiGateway -> apiGateway.deleteRestApi(request) println("The API was successfully deleted") } }DeleteRestApiRequest只需指定restApiId即可完成删除。这是原文档特别强调的破坏性操作:一旦执行,该 RestApi 及其关联的部署、阶段、方法等资源将一并移除,不可恢复。强烈建议仅在测试账号或临时创建的 API 上执行,并确保参数准确无误。
从源码验证完整调用链:测试用例拆解
仓库为这些示例提供了配套测试 APIGatewayTest.kt,它不仅是自动化验证工具,更直观地揭示了这些示例在生产中的真实调用顺序与依赖关系。
测试对参数的初始化:AWS Secrets Manager 存储测试数据
测试类APIGatewayTest通过@BeforeAll的setup()方法从AWS Secrets Manager的test/apigateway密钥中读取测试参数:
private suspend fun getSecretValues(): String { val secretName = "test/apigateway" val valueRequest = GetSecretValueRequest { secretId = secretName } SecretsManagerClient { region = "us-east-1" }.use { secretClient -> val valueResponse = secretClient.getSecretValue(valueRequest) return valueResponse.secretString.toString() } }密钥内容通过 Gson 反序列化为SecretValues内部类,包含restApiId、restApiName、httpMethod、stageName四个字段。其中restApiName还会追加一个 1~10000 的随机数后缀,避免并发或重复运行时命名冲突:
val randomNum = random.nextInt(10000 - 1 + 1) + 1 restApiName = values.restApiName.toString() + randomNum测试顺序与调用链
测试使用 JUnit 5 的@TestMethodOrder(OrderAnnotation::class)按@Order依次执行,完整演示了 API 生命周期:
@Order(1) createRestApiTest:调用createAPI(restApiId)创建 API,保存返回的newApiId;@Order(2) getDeploymentsTest:对newApiId调用getAllDeployments(newApiId)查询部署集合;@Order(3) getAllStagesTest:对newApiId调用getAllStages(newApiId)查询阶段列表;@Order(4) deleteRestApi:对newApiId调用deleteAPI(newApiId)清理资源。
这四步串起来正是"创建 → 查询部署 → 查询阶段 → 删除"的标准资源生命周期闭环,也印证了原文档中"建议创建独立的测试专用资源进行实验"的实践原则——测试先创建、最后删除,避免在账号中遗留临时资源。
运行与验证建议
命令行运行
以 Gradle 工程为例,编译后在命令行运行任一示例的main函数并传入对应参数:
# 创建 API(传入将用作 API 名称的参数) gradle run --args='my-demo-api' # 查询部署集合 gradle run --args='xxxx99ewyg' # 创建部署(API id + 阶段名) gradle run --args='xxxx99ewyg prod' # 查询 Method(API id + 资源 id + HTTP 方法) gradle run --args='xxxx99ewyg a1b2c3 GET'运行测试
在完成 AWS 凭证配置、并在 Secrets Manager 中创建好名为test/apigateway的密钥(包含restApiId、restApiName、httpMethod、stageName四个字段)后,可直接运行 JUnit 测试类验证完整流程:
gradle test注意事项清单
- 所有示例默认使用
us-east-1区域,如需其他区域请修改客户端构造代码中的region; - 运行示例前确认 IAM 权限包含 API Gateway 的
CreateRestApi、CreateDeployment、GetDeployments、GetStages、GetMethod、GetApiKeys、DeleteRestApi对应动作; - 涉及删除的示例务必使用测试专用资源;
- 运行真实操作可能产生 AWS 费用,请参考 AWS 定价信息评估成本。
总结
本文围绕 aws-doc-sdk-examples 仓库 kotlin/services/apigateway/README.md 中列出的 7 个 Kotlin 示例,逐一讲解了它们的运行参数、请求模型与核心实现:从CreateRestApi的 API 创建、CreateDeployment的部署发布,到GetDeployments/GetStages/GetMethod/GetAPIKeys四类查询,再到DeleteRestApi的清理回收。通过 APIGatewayTest.kt 的测试用例,还能看到这些操作如何组合成完整的资源生命周期管理流程。这套示例代码可以作为你在 Kotlin 项目中接入 Amazon API Gateway 的起步模板,直接复用其客户端构造、请求构建与协程调用模式。
- 示例工程
- 教程
- 后端
【免费下载链接】aws-doc-sdk-examples
Welcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.
相关推荐
使用 AWS SDK for Kotlin 操作 Amazon Kinesis:数据流完整实战指南
使用 AWS SDK for Kotlin 操作 Amazon Kinesis:数据流完整实战指南 Amazon Kinesis 让开发者能够实时收集、处理和分
示例工程教程后端如何用 ESP-IDF 生成 DFU 镜像并通过 USB 直接升级设备固件?
如何用 ESP IDF 生成 DFU 镜像并通过 USB 直接升级设备固件? 如果目标芯片上不想再接 USB 转串口芯片(如 CP210x、FTDI),只希望通
示例工程教程后端使用 AWS SDK for Kotlin 操作 Amazon RDS:完整示例与源码级实战指南
使用 AWS SDK for Kotlin 操作 Amazon RDS:完整示例与源码级实战指南 本篇技术指南以 aws doc sdk examples 仓库
示例工程教程后端
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考