0Pricing
Serverless Backend with AWS Lambda & API Gateway · 课时

定义无服务器资源

编写 SAM 模板,定义 Lambda 函数、API Gateway 端点、DynamoDB 表和其他无服务器组件

定义无服务器资源 是 CoddyKit 上的免费 Serverless Backend with AWS Lambda & API Gateway 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Serverless Backend with AWS Lambda & API Gateway 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What are SAM Templates?

AWS Serverless Application Model (SAM) templates are a powerful way to define your serverless applications using Infrastructure as Code (IaC).

Instead of manually configuring resources in the AWS console, you describe them in a YAML or JSON file. This makes your deployments repeatable, version-controlled, and easier to manage.

Anatomy of a SAM Template

A SAM template has a clear structure. The most important parts are:

  • AWSTemplateFormatVersion: Specifies the template format version.
  • Transform: Always AWS::Serverless-2016-10-31 for SAM.
  • Description: A brief description of your application.
  • Resources: Where you define all your AWS components.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: My First SAM App

Resources:
  # Your serverless resources go here

Defining a Serverless Function

The core of many serverless applications is the AWS Lambda function. In SAM, you declare a Lambda using the AWS::Serverless::Function resource type.

You need to specify its handler, runtime, and where its code is located.

Resources:
  MyLambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.lambda_handler
      Runtime: python3.9
      CodeUri: s3://my-bucket/my-app.zip
      MemorySize: 128
      Timeout: 30

Key Lambda Properties

Let's break down some common AWS::Serverless::Function properties:

  • Handler: The entry point in your code (e.g., filename.function_name).
  • Runtime: The programming language runtime (e.g., python3.9, nodejs18.x).
  • CodeUri: Path to your function's deployment package (local or S3).
  • MemorySize: RAM allocated to the function (MB).
  • Timeout: Max execution time (seconds).

API Gateway as an Event Source

To make your Lambda function accessible via an HTTP endpoint, you integrate it with Amazon API Gateway. In SAM, you do this by adding an Events property to your function.

The HttpApi type is often preferred for its simplicity and cost-effectiveness.

Resources:
  MyApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.lambda_handler
      Runtime: python3.9
      CodeUri: s3://my-bucket/api-app.zip
      Events:
        MyApiEvent:
          Type: HttpApi
          Properties:
            Path: /hello
            Method: GET

Defining a DynamoDB Table

For data persistence, you can define a DynamoDB table directly in your SAM template. SAM provides a convenient AWS::Serverless::SimpleTable resource type.

This creates a basic DynamoDB table with a primary key. For more advanced configurations, you can use AWS::DynamoDB::Table.

Resources:
  MyDataTable:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: id
        Type: String
      ProvisionedThroughput:
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1

IAM Permissions for Resources

Your Lambda functions often need permission to interact with other AWS services, like DynamoDB. You grant these permissions using IAM (Identity and Access Management) policies.

SAM allows you to attach policies directly to your Lambda function's execution role using the Policies property.

Resources:
  MyLambdaWithDbAccess:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.lambda_handler
      Runtime: python3.9
      CodeUri: s3://my-bucket/db-app.zip
      Policies:
        - DynamoDBReadWriteAccess:
            TableName: !Ref MyDataTable # Grants access to MyDataTable
      Events:
        MyApiEvent:
          Type: HttpApi
          Properties:
            Path: /items
            Method: GET
  MyDataTable:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: id
        Type: String

Exporting Important Values

After deploying your serverless application, you often need to know the endpoint URL of your API or the name of your DynamoDB table.

The Outputs section in your SAM template allows you to export these values, making them easily accessible after deployment.

Outputs:
  ApiUrl:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/hello"

A Full Serverless Template

Here's a more complete SAM template that defines an HTTP API endpoint, a Lambda function to handle requests, and a DynamoDB table for data storage.

Notice how different resource types are declared and linked together.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: A complete serverless API with Lambda and DynamoDB

Resources:
  MyApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.lambda_handler
      Runtime: python3.9
      CodeUri: s3://my-bucket/full-app.zip
      Policies:
        - DynamoDBReadWriteAccess:
            TableName: !Ref MyItemsTable
      Events:
        MyApiEvent:
          Type: HttpApi
          Properties:
            Path: /items
            Method: GET

  MyItemsTable:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: itemId
        Type: String

Outputs:
  ApiEndpoint:
    Description: "API Gateway endpoint URL"
    Value: !Sub "https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/items"

SAM Template Check

Which of the following are valid top-level sections in a SAM template?

Recap: Defining Serverless Resources

In this lesson, you learned how to define various serverless resources within a SAM template. We covered:

  • The basic structure of a SAM template.
  • Declaring AWS::Serverless::Function for Lambda.
  • Integrating Lambda with API Gateway using Events.
  • Defining AWS::Serverless::SimpleTable for DynamoDB.
  • Granting permissions with IAM Policies.
  • Using the Outputs section to export values.

Next, we'll learn how to deploy these templates to AWS!

常见问题解答

「定义无服务器资源」课时是免费的吗?

是的 — 「定义无服务器资源」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Serverless Backend with AWS Lambda & API Gateway 课程的其余内容,请升级到 CoddyKit PRO。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。

「定义无服务器资源」这节课中我会学到什么?

编写 SAM 模板,定义 Lambda 函数、API Gateway 端点、DynamoDB 表和其他无服务器组件 你通过在浏览器中直接运行的动手代码来练习 Serverless Backend with AWS Lambda & API Gateway,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Serverless Backend with AWS Lambda & API Gateway 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Serverless Backend with AWS Lambda & API Gateway 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「定义无服务器资源」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Serverless Backend with AWS Lambda & API Gateway 课中编写并运行代码吗?

能。每节 Serverless Backend with AWS Lambda & API Gateway 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. AWS SAM 简介
  2. 定义无服务器资源
  3. 部署 SAM 应用
  4. 使用 SAM CLI 进行本地测试与调试
← 返回 Serverless Backend with AWS Lambda & API Gateway