如何通过Serverless Framework配置自身部署的AWS API Gateway Responses?
问题描述
我希望通过Serverless Framework配置AWS API Gateway的非集成响应,目标配置项如图所示。
当前我的serverless.yml内容如下:
#Deploy an api gateway with custom responses. --- service: test-apigw frameworkVersion: ">=3.20" provider: name: aws stage: dev region: us-east-1 stackName: ${self:service} apiName: test-apigw endpointType: REGIONAL functions: hello: handler: handler.endpoint events: - http: path: /hello-world method: ANY private: true package: individually: true excludeDevDependencies: false
我知道可以通过resources项配置,但使用CloudFormation代码时需要已部署API Gateway的ARN或引用,或者通过CFN声明API Gateway(我希望避免这种方式)。请问是否可以针对当前serverless.yml部署的名为test-apigw的API Gateway配置这些网关响应?
解决方案
完全可以做到,不需要手动声明API Gateway,只需利用Serverless Framework自动生成的CloudFormation资源引用,在resources里添加对应的AWS::ApiGateway::GatewayResponse资源即可。
Serverless Framework会自动为创建的API Gateway生成一个CloudFormation逻辑IDApiGatewayRestApi,直接在资源中引用这个ID就能关联到自动创建的API。
以下是修改后的serverless.yml示例,以配置401和403的自定义网关响应为例(匹配你目标配置的常见场景):
#Deploy an api gateway with custom responses. --- service: test-apigw frameworkVersion: ">=3.20" provider: name: aws stage: dev region: us-east-1 stackName: ${self:service} apiName: test-apigw endpointType: REGIONAL functions: hello: handler: handler.endpoint events: - http: path: /hello-world method: ANY private: true package: individually: true excludeDevDependencies: false resources: Resources: # 配置401 Unauthorized自定义响应 ApiGateway401Response: Type: AWS::ApiGateway::GatewayResponse Properties: ResponseParameters: gatewayresponse.header.Content-Type: "'application/json'" gatewayresponse.header.Access-Control-Allow-Origin: "'*'" gatewayresponse.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'" ResponseTemplates: application/json: | { "error": "Unauthorized access", "message": "$context.error.messageString" } ResponseType: UNAUTHORIZED RestApiId: Ref: ApiGatewayRestApi StatusCode: '401' # 配置403 Forbidden自定义响应 ApiGateway403Response: Type: AWS::ApiGateway::GatewayResponse Properties: ResponseParameters: gatewayresponse.header.Content-Type: "'application/json'" gatewayresponse.header.Access-Control-Allow-Origin: "'*'" gatewayresponse.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'" ResponseTemplates: application/json: | { "error": "Access forbidden", "message": "$context.error.messageString" } ResponseType: FORBIDDEN RestApiId: Ref: ApiGatewayRestApi StatusCode: '403'
关键说明:
Ref: ApiGatewayRestApi:直接引用Serverless自动生成的API Gateway资源,无需手动指定ARN或ID。ResponseType:对应API Gateway的响应类型,比如UNAUTHORIZED、FORBIDDEN、BAD_REQUEST_BODY等,可根据你的目标配置调整。ResponseParameters:配置响应头时,值需要用单引号包裹,确保CloudFormation正确解析。ResponseTemplates:自定义响应的内容格式,这里用JSON示例,你可以根据需求修改模板内容。
部署这个配置后,Serverless Framework会自动将这些自定义网关响应关联到你现有的test-apigw API Gateway上,完全不需要额外声明API资源。
内容的提问来源于stack exchange,提问作者David Merinos
相关产品推荐
相关产品推荐

