ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

使用 AWS SDK for Kotlin 操作 Amazon API Gateway 的完整实践指南

使用 AWS SDK for Kotlin 操作 Amazon API Gateway 的完整实践指南 示例工程教程后端【免费下载链接】aws-doc-sdk-examplesWelcome 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.项目地址https://gitcode.com/gh_mirrors/aw/aws-doc-sdk-examples点击查看免费下载本文基于 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 项目。你需要安装 JDKKotlin/JVM 项目所需安装 Gradle并建立包含kotlin(jvm)插件与 AWS SDK for Kotlin 依赖的build.gradle.kts构建脚本通过dependencies引入aws.sdk.kotlin:apigatewayAPI 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 APICreateRestApi运行方式与参数示例入口 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 访问 APIdescription部署描述便于在 Deployment 集合中区分不同版本。调用成功后返回的response.id即部署 id可打印用于后续追踪。查询类操作Deployments、Stages、Method、API Keys获取部署集合GetDeploymentsGetDeployments.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安全遍历。获取阶段列表GetStagesGetStages.kt 同样只接收 1 个参数restApiIdval 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 详情GetMethodGetMethod.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 KeysGetAPIKeysGetAPIKeys.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 APIDeleteRestApi破坏性操作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保存返回的newApiIdOrder(2) getDeploymentsTest对newApiId调用getAllDeployments(newApiId)查询部署集合Order(3) getAllStagesTest对newApiId调用getAllStages(newApiId)查询阶段列表Order(4) deleteRestApi对newApiId调用deleteAPI(newApiId)清理资源。这四步串起来正是创建 → 查询部署 → 查询阶段 → 删除的标准资源生命周期闭环也印证了原文档中建议创建独立的测试专用资源进行实验的实践原则——测试先创建、最后删除避免在账号中遗留临时资源。运行与验证建议命令行运行以 Gradle 工程为例编译后在命令行运行任一示例的main函数并传入对应参数# 创建 API传入将用作 API 名称的参数 gradle run --argsmy-demo-api # 查询部署集合 gradle run --argsxxxx99ewyg # 创建部署API id 阶段名 gradle run --argsxxxx99ewyg prod # 查询 MethodAPI id 资源 id HTTP 方法 gradle run --argsxxxx99ewyg 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-examplesWelcome 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.项目地址https://gitcode.com/gh_mirrors/aw/aws-doc-sdk-examples点击查看免费下载相关推荐使用 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 仓库示例工程教程后端上一篇面试前准备公司名称下一篇ES6数组some与every方法gh_mirrors/es/es6features项目解析创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表