Getting Started with AWS SAM: A Complete Guide to Serverless Development

AWS Serverless Application Model (SAM) has revolutionized how developers build and deploy serverless applications. In this comprehensive guide, we’ll explore what AWS SAM is, its benefits, and how to get started with practical examples.

What is AWS SAM?

AWS SAM is an open-source framework for building serverless applications on AWS. It extends AWS CloudFormation to provide a simplified way of defining the Amazon API Gateway APIs, AWS Lambda functions, and Amazon DynamoDB tables needed by your serverless application.

Why Use AWS SAM?

  1. Simplified Infrastructure as Code: SAM reduces hundreds of lines of CloudFormation template code into just a few lines
  2. Local Testing: Test your serverless applications locally before deployment
  3. Built-in Best Practices: Comes with built-in best practices for serverless applications
  4. Integrated Development Experience: Seamless integration with AWS services and development tools

Getting Started with AWS SAM

Prerequisites

  • AWS CLI installed and configured
  • Docker (for local testing)
  • AWS SAM CLI
  • Python, Node.js, or your preferred runtime

Basic Project Structure

my-sam-app/
│
├── template.yaml
├── src/
│   └── hello/
│       └── app.py
└── tests/
    └── unit/
        └── test_handler.py

Your First SAM Application

Let’s create a simple serverless API that responds with a hello message. Here’s the template.yaml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM Template

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/hello/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get

And here’s the corresponding Lambda function (src/hello/app.py):

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': {
            'message': 'Hello from AWS SAM!'
        }
    }

Working with SAM CLI

Common SAM Commands

  1. Initialize a new project:
sam init --runtime python3.9 --name my-sam-app
  1. Build your application:
sam build
  1. Test locally:
sam local start-api
  1. Deploy to AWS:
sam deploy --guided

Advanced SAM Features

Adding DynamoDB Table

Here’s how to add a DynamoDB table to your serverless application:

Resources:
  UsersTable:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: userId
        Type: String
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5

API Gateway Integration

Example of a more complex API setup:

Resources:
  UserFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      Runtime: nodejs14.x
      Events:
        GetUser:
          Type: Api
          Properties:
            Path: /users/{userId}
            Method: get
        CreateUser:
          Type: Api
          Properties:
            Path: /users
            Method: post
AWS SAM

Best Practices

  1. Environment Variables
  • Use SAM’s built-in parameter store integration
  • Keep sensitive information in AWS Secrets Manager
  1. Resource Naming
  • Use consistent naming conventions
  • Leverage SAM’s intrinsic functions for dynamic naming
  1. Local Testing
  • Utilize sam local invoke for function testing
  • Use sam local start-api for API testing
  1. Monitoring and Logging
  • Enable X-Ray tracing
  • Set up CloudWatch Logs insights

Common Pitfalls to Avoid

  1. Not setting appropriate IAM permissions
  2. Forgetting to clean up local builds
  3. Ignoring local testing capabilities
  4. Not using SAM policy templates

Conclusion

AWS SAM significantly simplifies serverless application development by providing a powerful abstraction layer over CloudFormation. With its local testing capabilities and streamlined deployment process, it’s become an essential tool for serverless developers.

Remember to always follow security best practices, properly manage your dependencies, and leverage SAM’s local testing capabilities to ensure your applications are production-ready.

Next Steps

  1. Explore SAM CLI’s debugging capabilities
  2. Learn about SAM policy templates
  3. Integrate with CI/CD pipelines
  4. Experiment with different event sources

By following this guide and exploring the examples provided, you’re well on your way to becoming proficient with AWS SAM. Happy serverless development!

Reference: Aws SAM doc

Recent post: Apollo Graphql federation

1 thought on “Getting Started with AWS SAM: A Complete Guide to Serverless Development”

Leave a Comment