如何在CloudFormation模板中为API Gateway添加查询字符串参数
CloudFormation 配置API端点查询字符串参数方案
以下针对AWS API Gateway两种常用类型分别提供配置模板:
1. REST API(AWS::ApiGateway前缀资源)
核心在原有AWS::ApiGateway::Method资源中新增RequestParameters配置,示例片段如下:
Resources: # 你原有/file路径对应的Method资源 FileDownloadMethod: Type: AWS::ApiGateway::Method Properties: HttpMethod: GET ResourceId: !Ref YourFileResource # 替换为你原有/file路径的资源ID RestApiId: !Ref YourRestApi # 替换为你原有API实例ID AuthorizationType: NONE # 保持你原有配置即可 # 新增查询参数配置 RequestParameters: # 格式:method.request.querystring.参数名: 布尔值,true为必填,false为可选 method.request.querystring.fileType: false # 可选:开启参数校验,确保传入参数格式符合要求 RequestValidatorId: !Ref ParamValidator Integration: Type: HTTP # 保持你原有集成类型即可,比如AWS_PROXY IntegrationHttpMethod: GET Uri: http://your-backend-service/file # 保持你原有后端地址即可 # 把查询参数透传给后端服务 RequestParameters: integration.request.querystring.fileType: method.request.querystring.fileType # 可选的参数校验器,不需要校验可省略 ParamValidator: Type: AWS::ApiGateway::RequestValidator Properties: Name: query-string-validator RestApiId: !Ref YourRestApi ValidateRequestParameters: true ValidateRequestBody: false
配置完成后部署对应API Stage即可生效,支持http://apiendpoint.com/file?fileType="A"的访问格式。
2. HTTP API(AWS::ApiGatewayV2前缀资源)
如果使用的是V2版本HTTP API,需要在Route资源中新增参数验证配置,示例片段如下:
Resources: # 你原有/file路径对应的Route资源 FileDownloadRoute: Type: AWS::ApiGatewayV2::Route Properties: ApiId: !Ref YourHttpApi # 替换为你原有HTTP API实例ID RouteKey: GET /file Target: !Join ['/', ['integrations', !Ref YourIntegration]] # 保持原有集成关联即可 # 新增查询参数配置 RequestParameterValidationEnabled: true RequestParameters: - Name: fileType In: querystring Required: false # 设为true则该参数为必填项 # 原有集成配置保持不变即可,HTTP API默认会透传查询参数到后端 YourIntegration: Type: AWS::ApiGatewayV2::Integration Properties: ApiId: !Ref YourHttpApi IntegrationType: HTTP_PROXY IntegrationUri: http://your-backend-service/file # 保持原有后端地址即可 IntegrationMethod: GET
内容的提问来源于stack exchange,提问作者Chris Teater
相关产品推荐
相关产品推荐

