Sam Deploy部署报错:需指定DefinitionBody或DefinitionUri求解决
错误原因分析
错误Require value for either DefinitionBody or DefinitionUri是因为你显式声明了AWS::Serverless::Api资源(ApiGatewayApi),但没有为该资源提供API定义的核心参数:
DefinitionBody:内嵌的OpenAPI/Swagger定义内容DefinitionUri:指向OpenAPI/Swagger文件的本地路径或S3地址
SAM对显式Api资源强制要求必须指定API定义,无法自动生成;而隐式Api(通过Lambda的Api事件自动创建)则不需要手动定义。
修复方案
方案一:保留显式Api资源,添加自动生成的API定义
修改ApiGatewayApi的Properties,添加DefinitionBody,让SAM基于Lambda的Api事件自动生成OpenAPI定义:
ApiGatewayApi: Type: AWS::Serverless::Api Properties: StageName: Prod DefinitionBody: Fn::Transform: Name: AWS::Include Parameters: Location: !Sub '${AWS::ServerlessRepositoryUrl}/applications/Amazon-Serverless-Application-Model/latest/templates/ApiGatewayDefinitionBody.yml'
方案二:使用SAM隐式Api(更简单推荐)
直接删除显式的ApiGatewayApi资源,让SAM自动根据Lambda的Api事件创建Api:
- 删除Resources中的
ApiGatewayApi节点 - 移除所有Lambda函数Events里的
RestApiId: !Ref ApiGatewayApi配置 - 修改Outputs中的
Api节点,将!Ref ApiGatewayApi改为!Ref ServerlessRestApi(SAM隐式Api的默认逻辑ID)
修改后的Lambda事件示例(以CreateFunction为例):
Events: CreateItem: Type: Api Properties: Path: /create Method: post
修改后的Outputs Api节点:
Api: Description: API Gateway endpoint URL for Prod stage for Create function Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod"
额外注意点
- 你的
GetFunction中Path写的是get,建议改为/get,避免路径解析异常 - 所有Lambda的Events节点的Key(比如
CreateItem)可以改成更具语义的名称,比如GetItem、GetAllItems,方便区分,但不影响功能
内容的提问来源于stack exchange,提问作者OldFish5354
相关产品推荐
相关产品推荐

