如何通过AWS CDK为API Gateway REST API配置HTTP Endpoint URL及stage变量
AWS CDK配置API Gateway serviceHost阶段变量实现方案
完全可以通过AWS CDK实现该需求,具体实现逻辑和可运行代码示例如下:
实现步骤
- 在API Gateway的部署阶段配置中定义
serviceHost阶段变量 - 若需要将该变量传递到后端请求的请求头、查询参数等位置,可在集成配置中添加对应的参数映射规则
TypeScript代码示例
import * as cdk from '@aws-cdk/core'; import * as apigateway from '@aws-cdk/aws-apigateway'; import * as lambda from '@aws-cdk/aws-lambda'; export class ApiGatewayStageVarStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // 示例后端Lambda,可替换为你实际使用的HTTP集成、VPC集成等其他集成类型 const backendHandler = new lambda.Function(this, 'BackendHandler', { runtime: lambda.Runtime.NODEJS_18_X, code: lambda.Code.fromAsset('lambda'), handler: 'index.handler', }); const api = new apigateway.RestApi(this, 'ServiceApi', { deployOptions: { stageName: 'prod', // 1. 在此处定义serviceHost阶段变量 stageVariables: { serviceHost: 'your-expected-service-host-value.com', }, }, }); const serviceIntegration = new apigateway.LambdaIntegration(backendHandler, { // 2. 配置参数映射,将stage变量注入到发往后端的请求头中,可根据需求调整映射位置 requestParameters: { 'integration.request.header.X-Service-Host': 'stageVariables.serviceHost', }, }); // 为API资源绑定集成规则,示例为根路径的GET方法,可替换为你实际的资源配置 api.root.addMethod('GET', serviceIntegration); } }
说明
如果你使用的是HTTP集成而非Lambda集成,配置逻辑完全一致,仅需将LambdaIntegration替换为对应的HttpIntegration即可,参数映射规则保持不变。
内容的提问来源于stack exchange,提问作者sudipt dabral
相关产品推荐
相关产品推荐

