无服务器应用模型(SAM)
使用 AWS 无服务器应用模型(SAM)框架定义、开发和部署无服务器应用程序。
无服务器应用模型(SAM) 是 CoddyKit 上的免费 AWS for Backend Developers (EC2, S3, RDS, Lambda) 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AWS for Backend Developers (EC2, S3, RDS, Lambda) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AWS for Backend Developers (EC2, S3, RDS, Lambda) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is AWS SAM?
Welcome to the AWS Serverless Application Model (SAM)! SAM is an open-source framework that helps you build, test, and deploy serverless applications on AWS faster and easier.
Think of it as a simplified way to define your serverless resources like Lambda functions and API Gateway endpoints.
SAM: CloudFormation's Helper
At its core, SAM is an extension of AWS CloudFormation. It provides a shorthand syntax for common serverless components.
When you deploy a SAM application, SAM transforms your simplified template into a full AWS CloudFormation template, ensuring you get all the benefits of CloudFormation's robust deployment capabilities.
SAM Template Structure
SAM applications are defined in a SAM template, typically a YAML file named template.yaml. Key sections include:
AWSTemplateFormatVersion: Standard CloudFormation version.Transform: AWS::Serverless-2016-10-31: This line tells CloudFormation to process the template using SAM.Resources: Where you define your serverless components (functions, APIs, databases).
Defining a Serverless Function
The primary resource for a Lambda function in SAM is AWS::Serverless::Function. This resource simplifies defining a Lambda function and its related configurations.
You specify properties like Handler (the function entry point), Runtime (e.g., python3.9), and CodeUri (the path to your function's code).
Integrating with API Gateway
To expose your Lambda function via an HTTP endpoint, you can directly define Events within your AWS::Serverless::Function resource.
Using the Api event type automatically provisions an Amazon API Gateway endpoint. You specify the Path and Method for your API route.
Your First SAM Template
Here's a basic template.yaml that defines a Python Lambda function triggered by an API Gateway GET request on the /hello path.
The CodeUri: hello_world/ indicates that the Lambda code is in a local directory named hello_world.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: A simple "Hello World" SAM app.
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.lambda_handler
Runtime: python3.9
CodeUri: hello_world/
MemorySize: 128
Timeout: 30
Events:
HelloWorldApi:
Type: Api
Properties:
Path: /hello
Method: GETThe Lambda Function Code
This is the Python code (app.py) that resides inside the hello_world/ directory. This function will be executed when the API Gateway endpoint is invoked.
It simply returns a JSON response with a "Hello from SAM Lambda!" message.
import json
def lambda_handler(event, context):
"""
Handles API Gateway requests and returns a simple greeting.
"""
print("Received an event:", event) # For logging
return {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": json.dumps({
"message": "Hello from SAM Lambda!"
}),
}
# Example local invocation (for direct script testing)
if __name__ == "__main__":
test_event = {
"httpMethod": "GET",
"path": "/hello",
"requestContext": {"requestId": "test-id-123"},
"headers": {"User-Agent": "test-client"}
}
response = lambda_handler(test_event, None)
print("Local Response:", response)Building Your SAM Application
Before you can deploy or even test your application locally, you need to build it. The sam build command processes your template, gathers dependencies, and prepares your code for deployment.
It creates a .aws-sam/build directory containing the processed artifacts.
sam build
Testing Locally with SAM CLI
The SAM CLI provides powerful tools for local testing, saving you time and money by avoiding repeated deployments to AWS.
sam local invoke: Invokes a single Lambda function locally with a given event.sam local start-api: Starts a local HTTP server that emulates API Gateway, allowing you to interact with your serverless API from your browser orcurl.
sam local start-api
Deploying Your Serverless App
Once your application is built and tested locally, you can deploy it to AWS using the sam deploy command.
The first time you deploy, it's recommended to use the --guided flag. This provides an interactive prompt to configure settings like stack name, AWS Region, and S3 bucket for deployment artifacts.
sam deploy --guided
SAM CLI Quick Check
Which SAM CLI command is used to test your serverless API Gateway locally, allowing you to interact with it from your browser or curl?
Recap & Next Steps
Congratulations! You've learned the fundamentals of the AWS Serverless Application Model (SAM).
- SAM simplifies serverless development by extending CloudFormation.
- You can define Lambda functions and API Gateway endpoints easily in a
template.yaml. - The SAM CLI allows you to
build, testlocally, anddeployyour serverless applications efficiently.
SAM is a powerful tool for developing modern, event-driven applications on AWS!
常见问题解答
「无服务器应用模型(SAM)」课时是免费的吗?
是的 — 「无服务器应用模型(SAM)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AWS for Backend Developers (EC2, S3, RDS, Lambda) 课程的其余内容,请升级到 CoddyKit PRO。 AWS for Backend Developers (EC2, S3, RDS, Lambda) 课程共包含 4 节课。
「无服务器应用模型(SAM)」这节课中我会学到什么?
使用 AWS 无服务器应用模型(SAM)框架定义、开发和部署无服务器应用程序。 你通过在浏览器中直接运行的动手代码来练习 AWS for Backend Developers (EC2, S3, RDS, Lambda),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AWS for Backend Developers (EC2, S3, RDS, Lambda) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AWS for Backend Developers (EC2, S3, RDS, Lambda) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「无服务器应用模型(SAM)」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AWS for Backend Developers (EC2, S3, RDS, Lambda) 课中编写并运行代码吗?
能。每节 AWS for Backend Developers (EC2, S3, RDS, Lambda) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。