Here we are going to see the basic Python AWS Lambda Hello World example using SAM (Serverless Application Model)

Prerequisites:

SAM uses AWS-CLI so its required to install AWS CLI to work with SAM, after all the above installations, we have to set up the AWS credentials, it varies based on your OS type we have an exclusive article for this or you can configure the credentials directly like below.

Python AWS SAM Lambda Example

I am working on the below versions:

$ sam --version
SAM CLI, version 1.23.0

$ aws --version
aws-cli/2.0.30 Python/3.7.4 Darwin/19.6.0 botocore/2.0.0dev34

Configure AWS Credentials:

The AWS configure command is used to map the AWS Account with the installed AWS CLI, that way the CLI can get access with your AWS Account.

$aws configure
$ aws configure
AWS Access Key ID [****************OE7N]: your_aws_access_key
AWS Secret Access Key [****************7qwh]: your_aws_secret_access_key
Default region name [None]: us-west-2
Default output format [None]: 

Create SAM Project:

sam init command is used to generate the SAM project structure. For this example, I have generated the Sam project with python3.8 however, when implementing the code, we can change it to various versions of Python3x, .NET, Go, Node.js, Java or Ruby.

$sam init –runtime python3.8
$ sam init --runtime python3.8
Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1
What package type would you like to use?
        1 - Zip (artifact is a zip uploaded to S3)      
        2 - Image (artifact is an image uploaded to an ECR image repository)
Package type: 1

Project name [sam-app]: hello-world-sam

Cloning app templates from https://github.com/aws/aws-sam-cli-app-templates

AWS quick start application templates:
        1 - Hello World Example
        2 - EventBridge Hello World
        3 - EventBridge App from scratch (100+ Event Schemas)
        4 - Step Functions Sample App (Stock Trader)
        5 - Elastic File System Sample App
Template selection: 1

    -----------------------
    Generating application:
    -----------------------
    Name: hello-world-sam
    Runtime: python3.8
    Dependency Manager: pip
    Application Template: hello-world
    Output Directory: .
    
    Next steps can be found in the README file at ./hello-world-sam/README.md

Project structure:

hello-world-sam $ 
.
├── README.md
├── __init__.py
├── events
│   └── event.json
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── requirements.txt
├── template.yaml
└── tests
    ├── __init__.py
    ├── integration
    │   ├── __init__.py
    │   └── test_api_gateway.py
    ├── requirements.txt
    └── unit
        ├── __init__.py
        └── test_handler.py

Among all of the above files the most important file that we need to work on is app.py, it is the python lambda function.

The template.yaml is the one that has the SAM template.

The event.json has the sample event for testing.

The requirement.txt specifies the lambda function dependencies.

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

  Sample SAM Template for hello-world-sam

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.8
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  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

The above simple template file used to build the AWS Lambda using SAM

app.py
import json

def lambda_handler(event, context):
    """Sample pure Lambda function

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
            # "location": ip.text.replace("\n", "")
        }),
    }

Build the application

$sam build
hello-world-sam $ sam build
Building codeuri: /hello-world-sam/hello_world runtime: python3.8 metadata: {} functions: ['HelloWorldFunction']
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided

deploy the application

$sam deploy –guided
$ sam deploy --guided

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Not found

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [sam-app]: hello-world-sam-application
        AWS Region [us-west-2]: us-west-2
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [y/N]: y
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]: y
        HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
        Save arguments to configuration file [Y/n]: y
        SAM configuration file [samconfig.toml]: 
        SAM configuration environment [default]: dev

        Looking for resources needed for deployment: Found!

                Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-vlxz3w3to6ye
                A different default S3 bucket can be set in samconfig.toml

        Saved arguments to config file
        Running 'sam deploy' for future deployments will use the parameters saved above.
        The above parameters can be changed by modifying samconfig.toml
        Learn more about samconfig.toml syntax at 
        https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html

Uploading to hello-world-sam-application/58ec98812dacd95efee12c7e720890f1  585177 / 585177  (100.00%)

        Deploying with following values
        ===============================
        Stack name                   : hello-world-sam-application
        Region                       : us-west-2
        Confirm changeset            : True
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-vlxz3w3to6ye
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================
Uploading to hello-world-sam-application/b78c4ab547b82834a429f1f54a09b62f.template  1125 / 1125  (100.00%)

Waiting for changeset to be created..

CloudFormation stack changeset
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation                                                     LogicalResourceId                                             ResourceType                                                  Replacement                                                 
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Add                                                         HelloWorldFunctionHelloWorldPermissionProd                    AWS::Lambda::Permission                                       N/A                                                         
+ Add                                                         HelloWorldFunctionRole                                        AWS::IAM::Role                                                N/A                                                         
+ Add                                                         HelloWorldFunction                                            AWS::Lambda::Function                                         N/A                                                         
+ Add                                                         ServerlessRestApiDeployment47fc2d5f9d                         AWS::ApiGateway::Deployment                                   N/A                                                         
+ Add                                                         ServerlessRestApiProdStage                                    AWS::ApiGateway::Stage                                        N/A                                                         
+ Add                                                         ServerlessRestApi                                             AWS::ApiGateway::RestApi                                      N/A                                                         
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:us-west-2:816569674899:changeSet/samcli-deploy1622384684/659cd0b5-e7fb-4767-a161-df496376c15e


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2021-05-30 19:55:02 - Waiting for stack create/update to complete

CloudFormation events from changeset
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                                ResourceType                                                  LogicalResourceId                                             ResourceStatusReason                                        
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                                            AWS::IAM::Role                                                HelloWorldFunctionRole                                        Resource creation Initiated                                 
CREATE_IN_PROGRESS                                            AWS::IAM::Role                                                HelloWorldFunctionRole                                        -                                                           
CREATE_COMPLETE                                               AWS::IAM::Role                                                HelloWorldFunctionRole                                        -                                                           
CREATE_IN_PROGRESS                                            AWS::Lambda::Function                                         HelloWorldFunction                                            -                                                           
CREATE_COMPLETE                                               AWS::Lambda::Function                                         HelloWorldFunction                                            -                                                           
CREATE_IN_PROGRESS                                            AWS::Lambda::Function                                         HelloWorldFunction                                            Resource creation Initiated                                 
CREATE_IN_PROGRESS                                            AWS::ApiGateway::RestApi                                      ServerlessRestApi                                             -                                                           
CREATE_IN_PROGRESS                                            AWS::ApiGateway::RestApi                                      ServerlessRestApi                                             Resource creation Initiated                                 
CREATE_COMPLETE                                               AWS::ApiGateway::RestApi                                      ServerlessRestApi                                             -                                                           
CREATE_IN_PROGRESS                                            AWS::ApiGateway::Deployment                                   ServerlessRestApiDeployment47fc2d5f9d                         Resource creation Initiated                                 
CREATE_IN_PROGRESS                                            AWS::Lambda::Permission                                       HelloWorldFunctionHelloWorldPermissionProd                    Resource creation Initiated                                 
CREATE_IN_PROGRESS                                            AWS::Lambda::Permission                                       HelloWorldFunctionHelloWorldPermissionProd                    -                                                           
CREATE_IN_PROGRESS                                            AWS::ApiGateway::Deployment                                   ServerlessRestApiDeployment47fc2d5f9d                         -                                                           
CREATE_COMPLETE                                               AWS::ApiGateway::Deployment                                   ServerlessRestApiDeployment47fc2d5f9d                         -                                                           
CREATE_IN_PROGRESS                                            AWS::ApiGateway::Stage                                        ServerlessRestApiProdStage                                    Resource creation Initiated                                 
CREATE_IN_PROGRESS                                            AWS::ApiGateway::Stage                                        ServerlessRestApiProdStage                                    -                                                           
CREATE_COMPLETE                                               AWS::ApiGateway::Stage                                        ServerlessRestApiProdStage                                    -                                                           
CREATE_COMPLETE                                               AWS::Lambda::Permission                                       HelloWorldFunctionHelloWorldPermissionProd                    -                                                           
CREATE_COMPLETE                                               AWS::CloudFormation::Stack                                    hello-world-sam-application                                   -                                                           
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Outputs                                                                                                                                                                                                                                                
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                                                                                                                                                                          
Description         Implicit IAM Role created for Hello World function                                                                                                                                                                                 
Value               arn:aws:iam::816569674899:role/hello-world-sam-application-HelloWorldFunctionRole-NAYYRTABIVUF                                                                                                                                     

Key                 HelloWorldApi                                                                                                                                                                                                                      
Description         API Gateway endpoint URL for Prod stage for Hello World function                                                                                                                                                                   
Value               https://6v73c82ade.execute-api.us-west-2.amazonaws.com/Prod/hello/                                                                                                                                                                 

Key                 HelloWorldFunction                                                                                                                                                                                                                 
Description         Hello World Lambda Function ARN                                                                                                                                                                                                    
Value               arn:aws:lambda:us-west-2:816569674899:function:hello-world-sam-application-HelloWorldFunction-dAjHSaNEq6pl                                                                                                                         
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Successfully created/updated stack - hello-world-sam-application in us-west-2

If everything went well you can see the above success message.

Verify:

Login to your AWS account-> Switch to Lambda-> Select the lambda-> Code Source-> Run

Python - AWS SAM Lambda Example

References:

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment