0Pricing
Serverless Backend with AWS Lambda & API Gateway · Урок

Определение бессерверных ресурсов

Пишите шаблоны SAM для определения функций Lambda, конечных точек API Gateway, таблиц DynamoDB и других бессерверных компонентов

«Определение бессерверных ресурсов» — бесплатный урок Serverless Backend with AWS Lambda & API Gateway на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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!

Часто задаваемые вопросы

Урок «Определение бессерверных ресурсов» бесплатный?

Да — полный текст урока «Определение бессерверных ресурсов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс 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 с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Serverless Backend with AWS Lambda & API Gateway?

Предыдущий опыт не требуется. Serverless Backend with AWS Lambda & API Gateway на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 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