GitHub Repository

You can find the project source code on GitHub.

This tutorial implements a serverless application and deploy it to AWS Lambda using AWS SAM.

Prerequisites

  1. Complete AWS SAM Prerequisites
  2. Install the AWS SAM CLI

Project Setup

Create a SAM application with the following options:

➜  tutorials > ✗ sam init
Which template source would you like to use?
	1 - AWS Quick Start Templates
	2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
	1 - Hello World Example
	2 - Data processing
	3 - Hello World Example with Powertools for AWS Lambda
	4 - Multi-step workflow
	5 - Scheduled task
	6 - Standalone function
	7 - Serverless API
	8 - Infrastructure event management
	9 - Lambda Response Streaming
	10 - Serverless Connector Hello World Example
	11 - Multi-step workflow with Connectors
	12 - GraphQLApi Hello World Example
	13 - Full Stack
	14 - Lambda EFS example
	15 - DynamoDB Example
	16 - Machine Learning
Template: 1

Use the most popular runtime and package type? (Python and zip) [y/N]: y

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: N

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: N

Would you like to set Structured Logging in JSON format on your Lambda functions?  [y/N]: N
cd sam-app

Counter Function Setup

Update /hello_world/requirements.txt to include upstash-redis:

/hello_world/requirements.txt
requests
upstash-redis

Update /hello_world/app.py:

/hello_world/app.py
from upstash_redis import Redis

redis = Redis.from_env()

def lambda_handler(event, context):
    count = redis.incr('counter')
    return {
        'statusCode': 200,
        'body': f'Counter: {count}'
    }

Update /template.yaml to pass Upstash Redis environment variables:

/template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app

  Sample SAM Template for sam-app

Globals:
  Function:
    Timeout: 3
    MemorySize: 128

Parameters:
  UpstashRedisRestURL:
    Type: String
  UpstashRedisRestToken:
    Type: String

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get
      Environment:
        Variables:
          UPSTASH_REDIS_REST_URL: !Ref UpstashRedisRestURL
          UPSTASH_REDIS_REST_TOKEN: !Ref UpstashRedisRestToken

Outputs:
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn

Database Setup

Create a Redis database using Upstash Console or Upstash CLI. Copy UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN for the next steps.

Build

sam build

Deploy

Enter your database related environment variables when prompted.

sam deploy --guided

Visit the HelloWorld API Gateway URL to see the response.