SAM & the Serverless Framework

SAM and the Serverless Framework describe serverless apps as code and deploy them with one command.

Wiring Lambda, API Gateway, permissions, and triggers by hand is tedious. The AWS Serverless Application Model (SAM) and the third-party Serverless Framework let you declare the whole stack in a short YAML file and deploy it in one command.

What SAM gives you

  • A compact syntax for functions, APIs, tables, and triggers.
  • sam build and sam deploy to package and ship.
  • sam local invoke to test functions on your laptop.

Under the hood SAM expands into a CloudFormation template, so you also get versioned, repeatable infrastructure.

Example

Example · yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  ApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs20.x
      MemorySize: 256
      Environment:
        Variables:
          NODE_ENV: production
      Events:
        Api:
          Type: HttpApi
          Properties:
            Path: /{proxy+}
            Method: ANY

When to use it

  • A developer uses AWS SAM to define a Lambda function, API Gateway, and DynamoDB table in one template.yaml and deploys everything with sam deploy.
  • A team runs sam local start-api to test Lambda functions behind API Gateway on a local HTTP server before pushing to AWS.
  • A CI pipeline uses sam build and sam deploy --no-confirm-changeset to ship serverless app updates without manual approval prompts.

More examples

Minimal SAM template.yaml

Defines a serverless function with an HTTP API trigger using SAM's concise shorthand, replacing 50+ lines of CloudFormation.

Example · yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Runtime: nodejs20.x
    Timeout: 30

Resources:
  ApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handler.handler
      Events:
        Api:
          Type: HttpApi
          Properties:
            Path: /hello
            Method: GET

Build and deploy with SAM CLI

Builds the Lambda package with dependencies, then deploys the stack, prompting for configuration on the first run.

Example · bash
# Install dependencies and build the deployment package
sam build

# Deploy interactively the first time (creates samconfig.toml)
sam deploy --guided

Run Lambda locally for testing

Spins up a local HTTP server emulating API Gateway so you can test Lambda functions without deploying to AWS.

Example · bash
# Start a local API Gateway emulator
sam local start-api

# In another terminal, test the function
curl http://127.0.0.1:3000/hello

Discussion

  • Be the first to comment on this lesson.