如何在AWS SAM模板中创建Empty和Error默认模型并配置Lambda函数使用Empty模型
在AWS SAM模板中创建API Gateway默认模型并关联Lambda
AWS SAM确实不会自动生成控制台里默认的Empty和Error模型,要实现和手动创建一致的效果,直接在SAM模板里按以下步骤配置:
1. 定义Empty和Error模型
在模板的Resources块里,添加两个AWS::ApiGateway::Model资源,完全匹配控制台默认的模型结构:
Resources: # 创建Empty模型(对应控制台的Empty默认模型) ApiEmptyModel: Type: AWS::ApiGateway::Model Properties: RestApiId: !Ref MyApi Name: Empty ContentType: application/json Schema: {} # 空Schema,和控制台默认一致 # 创建Error模型(对应控制台的Error默认模型) ApiErrorModel: Type: AWS::ApiGateway::Model Properties: RestApiId: !Ref MyApi Name: Error ContentType: application/json Schema: type: object properties: message: type: string required: - message
2. 配置API Gateway及方法响应
定义API Gateway时,在Swagger的响应部分关联这两个模型,同时配置Lambda集成:
MyApi: Type: AWS::Serverless::Api Properties: StageName: prod DefinitionBody: swagger: "2.0" info: title: !Ref AWS::StackName paths: /my-endpoint: get: responses: '200': description: 成功响应 schema: $ref: "#/definitions/Empty" # 绑定Empty模型到200响应 '500': description: 错误响应 schema: $ref: "#/definitions/Error" # 绑定Error模型到500响应 x-amazon-apigateway-integration: uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambda.Arn}/invocations httpMethod: POST type: aws_proxy definitions: Empty: !Ref ApiEmptyModel Error: !Ref ApiErrorModel
3. 关联Lambda函数
最后定义Lambda,并通过API事件关联到上面的API端点:
MyLambda: Type: AWS::Serverless::Function Properties: CodeUri: src/ Handler: index.handler Runtime: python3.12 Events: MyApiEvent: Type: Api Properties: RestApiId: !Ref MyApi Path: /my-endpoint Method: get
补充说明
- 如果用的是
aws_proxy集成类型,Lambda的返回结果会直接映射为API响应,无需额外配置响应模板;如果需要自定义响应映射,可以调整集成部分的responses配置。 - 这样配置后,API Gateway的方法响应就会和你在控制台手动创建的效果完全一致,包含Empty和Error两个默认模型,且200响应绑定了Empty模型。
内容的提问来源于stack exchange,提问作者Igor Augusto
相关产品推荐
相关产品推荐

