Which AWS service allows you to build and model your serverless application?

In this guide, you download, build, and deploy a sample Hello World application using AWS SAM. You then test the application in the AWS Cloud, and optionally test it locally on your development host.

This application implements a basic API backend. It consists of an Amazon API Gateway endpoint and an AWS Lambda function. When you send a GET request to the API Gateway endpoint, the Lambda function is invoked. This function returns a

   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

 Next steps can be found in the README file at ./sam-app/README.md
        
7 message.

The following diagram shows the components of this application:

Which AWS service allows you to build and model your serverless application?

When you initialize your sample application, you have the option to choose a Lambda deployment package type, either

   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

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

 Next steps can be found in the README file at ./sam-app/README.md
        
9. For more information about package types, see Lambda deployment packages in the AWS Lambda Developer Guide.

The following is a preview of commands that you run to create your Hello World application. For more information about each of these commands, see the sections later in this tutorial.

#Step 1 - Download a sample application
sam init

#Step 2 - Build your application
cd sam-app
sam build

#Step 3 - Deploy your application
sam deploy --guided

Prerequisites

This guide assumes that you've completed the steps for your operating system in Installing the AWS SAM CLI, including:

  1. Creating an AWS account.

  2. Configuring AWS Identity and Access Management (IAM) permissions.

  3. Installing Docker. Note: Docker is a prerequisite only for testing your application locally.

  4. Installing Homebrew. Note: Homebrew is a prerequisite only for Linux and macOS.

  5. Installing the AWS Serverless Application Model Command Line Interface (AWS SAM CLI). Note: Make sure that you have version 1.13.0 or later. Check the version by running the sam --version command.

Step 1: Download a sample AWS SAM application

Command to run:

sam init

Follow the on-screen prompts. For this tutorial, we recommend that you choose

 
 sam-app/
   ├── README.md
   ├── events/
   │   └── event.json
   ├── hello_world/
   │   ├── __init__.py
   │   ├── app.py            #Contains your AWS Lambda handler logic.
   │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
   ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
   └── tests/
       └── unit/
           ├── __init__.py
           └── test_handler.py
        
0, the
   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

 Next steps can be found in the README file at ./sam-app/README.md
        
8 package type, the runtime of your choice, and the
 
 sam-app/
   ├── README.md
   ├── events/
   │   └── event.json
   ├── hello_world/
   │   ├── __init__.py
   │   ├── app.py            #Contains your AWS Lambda handler logic.
   │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
   ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
   └── tests/
       └── unit/
           ├── __init__.py
           └── test_handler.py
        
2.

Example output:

   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

 Next steps can be found in the README file at ./sam-app/README.md
        

What AWS SAM is doing:

This command creates a directory with the name that you provided as the project name. The contents of the project directory are similar to the following:

 
 sam-app/
   ├── README.md
   ├── events/
   │   └── event.json
   ├── hello_world/
   │   ├── __init__.py
   │   ├── app.py            #Contains your AWS Lambda handler logic.
   │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
   ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
   └── tests/
       └── unit/
           ├── __init__.py
           └── test_handler.py
        

These project directory contents are created when you choose one of the Python runtimes and the

 
 sam-app/
   ├── README.md
   ├── events/
   │   └── event.json
   ├── hello_world/
   │   ├── __init__.py
   │   ├── app.py            #Contains your AWS Lambda handler logic.
   │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
   ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
   └── tests/
       └── unit/
           ├── __init__.py
           └── test_handler.py
        
2.

There are three especially important files:

  •  
     sam-app/
       ├── README.md
       ├── events/
       │   └── event.json
       ├── hello_world/
       │   ├── __init__.py
       │   ├── app.py            #Contains your AWS Lambda handler logic.
       │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
       ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
       └── tests/
           └── unit/
               ├── __init__.py
               └── test_handler.py
            
    4: Contains the AWS SAM template that defines your application's AWS resources.

  •  
     sam-app/
       ├── README.md
       ├── events/
       │   └── event.json
       ├── hello_world/
       │   ├── __init__.py
       │   ├── app.py            #Contains your AWS Lambda handler logic.
       │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
       ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
       └── tests/
           └── unit/
               ├── __init__.py
               └── test_handler.py
            
    5: Contains your actual Lambda handler logic.

  •  
     sam-app/
       ├── README.md
       ├── events/
       │   └── event.json
       ├── hello_world/
       │   ├── __init__.py
       │   ├── app.py            #Contains your AWS Lambda handler logic.
       │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
       ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
       └── tests/
           └── unit/
               ├── __init__.py
               └── test_handler.py
            
    6: Contains any Python dependencies that the application requires, and is used for sam build.

Step 2: Build your application

Command to run:

First, change into the project directory, where the

 
 sam-app/
   ├── README.md
   ├── events/
   │   └── event.json
   ├── hello_world/
   │   ├── __init__.py
   │   ├── app.py            #Contains your AWS Lambda handler logic.
   │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
   ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
   └── tests/
       └── unit/
           ├── __init__.py
           └── test_handler.py
        
4 file for the sample application is located. (By default, this directory is
 
 sam-app/
   ├── README.md
   ├── events/
   │   └── event.json
   ├── hello_world/
   │   ├── __init__.py
   │   ├── app.py            #Contains your AWS Lambda handler logic.
   │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
   ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
   └── tests/
       └── unit/
           ├── __init__.py
           └── test_handler.py
        
8.) Then run this command:

sam build

Example output:

  
 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
       

What AWS SAM is doing:

The AWS SAM CLI comes with abstractions for a number of Lambda runtimes to build your dependencies. It also includes copies the source code into staging folders so that everything is ready to be packaged and deployed. The sam build command builds any dependencies that your application has. It also copies your application source code to folders under

 
 sam-app/
   ├── README.md
   ├── events/
   │   └── event.json
   ├── hello_world/
   │   ├── __init__.py
   │   ├── app.py            #Contains your AWS Lambda handler logic.
   │   └── requirements.txt  #Contains any Python dependencies the application requires, used for sam build
   ├── template.yaml         #Contains the AWS SAM template defining your application's AWS resources.
   └── tests/
       └── unit/
           ├── __init__.py
           └── test_handler.py
        
9 to be zipped and uploaded to Lambda.

You can see the following top-level tree under

sam build
0:

 
 .aws-sam/
   └── build/
       ├── HelloWorldFunction/
       └── template.yaml
            

sam build
1 is a directory that contains your
sam build
2 file, and also third-party dependencies that your application uses.

Step 3: Deploy your application to the AWS Cloud

Command to run:

sam deploy --guided

Follow the on-screen prompts. To accept the default options provided in the interactive experience, respond with

sam build
3.

For the prompt

sam build
4, AWS SAM is informing you that the sample application configures an API Gateway API without authorization. When you deploy the sample application, AWS SAM creates a publicly available URL.

You can acknowledge this notification by answering "Y" to the prompt. For information about configuring authorization, see Controlling access to API Gateway APIs.

Example output:

 
    Deploying with following values
    ===============================
    Stack name                 : sam-app
    Region                     : us-east-1
    Confirm changeset          : False
    Deployment s3 bucket       : sam-bucket
    Capabilities               : ["CAPABILITY_IAM"]
    Parameter overrides        : {}

 Initiating deployment
 =====================

 Waiting for changeset to be created..

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

 2019-11-21 14:33:24 - Waiting for stack create/update to complete

 CloudFormation events from changeset
 -------------------------------------------------------------------------------------------------------------------------------------------------
 ResourceStatus                       ResourceType                         LogicalResourceId                    ResourceStatusReason
 -------------------------------------------------------------------------------------------------------------------------------------------------
 UPDATE_IN_PROGRESS                   AWS::IAM::Role                       HelloWorldFunctionRole               -
 UPDATE_COMPLETE                      AWS::IAM::Role                       HelloWorldFunctionRole               -
 UPDATE_IN_PROGRESS                   AWS::Lambda::Function                HelloWorldFunction                   -
 UPDATE_COMPLETE                      AWS::Lambda::Function                HelloWorldFunction                   -
 CREATE_IN_PROGRESS                   AWS::ApiGateway::RestApi             ServerlessRestApi                    -
 CREATE_COMPLETE                      AWS::ApiGateway::RestApi             ServerlessRestApi                    -
 CREATE_IN_PROGRESS                   AWS::ApiGateway::RestApi             ServerlessRestApi                    Resource creation Initiated
 CREATE_IN_PROGRESS                   AWS::ApiGateway::Deployment          ServerlessRestApiDeployment47fc2d5   Resource creation Initiated
                                                                          f9d
 CREATE_IN_PROGRESS                   AWS::Lambda::Permission              HelloWorldFunctionHelloWorldPermis   Resource creation Initiated
                                                                          sionProd
 CREATE_IN_PROGRESS                   AWS::Lambda::Permission              HelloWorldFunctionHelloWorldPermis   -
                                                                          sionProd
 CREATE_IN_PROGRESS                   AWS::ApiGateway::Deployment          ServerlessRestApiDeployment47fc2d5   -
                                                                          f9d
CREATE_COMPLETE                      AWS::ApiGateway::Deployment          ServerlessRestApiDeployment47fc2d5   -
                                                                          f9d
 CREATE_IN_PROGRESS                   AWS::ApiGateway::Stage               ServerlessRestApiProdStage           -
 CREATE_IN_PROGRESS                   AWS::ApiGateway::Stage               ServerlessRestApiProdStage           Resource creation Initiated
 CREATE_COMPLETE                      AWS::ApiGateway::Stage               ServerlessRestApiProdStage           -
 CREATE_COMPLETE                      AWS::Lambda::Permission              HelloWorldFunctionHelloWorldPermis   -
                                                                          sionProd
 UPDATE_COMPLETE_CLEANUP_IN_PROGRES   AWS::CloudFormation::Stack           sam-app                              -
 S
 UPDATE_COMPLETE                      AWS::CloudFormation::Stack           sam-app                              -
 -------------------------------------------------------------------------------------------------------------------------------------------------

 Stack sam-app outputs:
 ---------------------------------------------------------------------------------------------------------------------------------------------------
 OutputKey-Description                                                     OutputValue
 ---------------------------------------------------------------------------------------------------------------------------------------------------
 HelloWorldFunctionIamRole - Implicit IAM Role created for Hello World     arn:aws:iam::123456789012:role/sam-app-
 function                                                                  HelloWorldFunctionRole-104VTJ0TST7M0
 HelloWorldApi - API Gateway endpoint URL for Prod stage for Hello World   https://0ks2zue0zh.execute-api.us-east-1.amazonaws.com/Prod/hello/
 function
 HelloWorldFunction - Hello World Lambda Function ARN                      arn:aws:lambda:us-east-1:123456789012:function:sam-app-
                                                                          HelloWorldFunction-1TY92MJX0BXU5
 ---------------------------------------------------------------------------------------------------------------------------------------------------

 Successfully created/updated stack - sam-app in us-east-1
        

What AWS SAM is doing:

This command deploys your application to the AWS Cloud. It takes the deployment artifacts that you build with the sam build command, packages and uploads them to an Amazon Simple Storage Service (Amazon S3) bucket that the AWS SAM CLI creates, and deploys the application using AWS CloudFormation. In the output of the sam deploy command, you can see the changes being made to your AWS CloudFormation stack.

If your application created an HTTP endpoint, the outputs that

sam build
5 generates also show you the endpoint URL for your test application. You can use curl to send a request to your application using that endpoint URL. For example:

curl https://.execute-api.us-east-1.amazonaws.com/Prod/hello/

After successfully deploying your application, you see output like the following:

sam init
0

If you see

sam build
6 after running the curl command, you've successfully deployed your serverless application to the AWS Cloud, and you're calling your live Lambda function. Otherwise, see the Troubleshooting section later in this tutorial.

Step 4: (Optional) Test your application locally

To use the AWS SAM CLI to test locally, you must have Docker installed and configured. For instructions, see Installing Docker to use with the AWS SAM CLI.

When you're developing your application, you might find it useful to test locally. The AWS SAM CLI provides the sam local command to run your application using Docker containers that simulate the execution environment of Lambda. There are two options to do this:

  • Host your API locally.

  • Invoke your Lambda function directly.

This step describes both options.

Host your API locally

Command to run:

sam init
1

Example output:

sam init
2

It can take a while for the Docker image to load. After it's loaded, you can use curl to send a request to your application that's running on your local host:

sam init
3

Example output:

sam init
4

What AWS SAM is doing:

The start-api command starts up a local endpoint that replicates your REST API endpoint. The command also downloads an execution container that you can run your function in locally. The end result is the same output that you saw when you called your function in the AWS Cloud.

Invoke your Lambda function directly

Command to run:

sam init
5

Example output:

sam init
6

What AWS SAM is doing:

The invoke command directly invokes your Lambda functions, and can pass input event payloads that you provide. With this command, you pass the event payload in the file

sam build
7 that the sample application provides.

Your initialized application comes with a default

sam build
8 event for API Gateway. A number of values are pre-populated for you. In this case, the
sam build
1 doesn't care about the particular values, so a stubbed request is OK. You can specify a number of values to substitute in to the request to simulate what you would expect from an actual request. The following is an example of generating your own input event and comparing the output with the default
sam build
7 object:

sam init
7

Example output:

sam init
8

Troubleshooting

AWS SAM CLI error: "Security Constraints Not Satisfied"

When running sam deploy --guided, you're prompted with the question

sam build
4. If you respond to this prompt with
  
 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
       
2 (the default response), you see the following error:

sam init
9

The prompt is informing you that the application you're about to deploy might have an Amazon API Gateway API configured without authorization. By responding

  
 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
       
2 to this prompt, you're saying that this is not OK.

To fix this, you have the following options:

  • Configure your application with authorization. For information about configuring authorization, see Controlling access to API Gateway APIs.

  • Respond to this question with

      
     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
           
    4 to indicate that you're OK with deploying an application that has an API Gateway API configured without authorization.

AWS SAM CLI error: "no such option: --app-template"

When running the sam init command, you see the following error:

   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

 Next steps can be found in the README file at ./sam-app/README.md
        
0

This means that you are using an earlier version of the AWS SAM CLI that does not support the

  
 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
       
5 parameter. To fix this, you can either update your version of AWS SAM CLI to 0.33.0 or later, or omit the
  
 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
       
5 parameter from the sam init command.

AWS SAM CLI error: "no such option: --guided"

When running the sam deploy command, you see the following error:

   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

 Next steps can be found in the README file at ./sam-app/README.md
        
1

This means that you are using an earlier version of the AWS SAM CLI that does not support the

  
 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
       
7 parameter. To fix this, you can either update your version of AWS SAM CLI to 0.33.0 or later, or omit the
  
 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
       
7 parameter from the sam deploy command.

AWS SAM CLI error: "Failed to create managed resources: Unable to locate credentials"

When running the sam deploy command, you see the following error:

   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

 Next steps can be found in the README file at ./sam-app/README.md
        
2

This means that you have not set up AWS credentials to enable the AWS SAM CLI to make AWS service calls. To fix this, you must set up AWS credentials. For more information, see Setting up AWS credentials.

AWS SAM CLI error: "Running AWS SAM projects locally requires Docker. Have you got it installed?"

When running the sam local start-api command, you see the following error:

   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

 Next steps can be found in the README file at ./sam-app/README.md
        
3

This means that you do not have Docker properly installed. Docker is required to test your application locally. To fix this, follow the instructions for installing Docker for your development host. Go to Installing the AWS SAM CLI, choose the appropriate platform, and then follow the instructions in the section titled Install Docker.

Curl error: "Missing Authentication Token"

When trying to invoke the API Gateway endpoint, you see the following error:

   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

 Next steps can be found in the README file at ./sam-app/README.md
        
4

This means that you've attempted to send a request to the correct domain, but the URI isn't recognizable. To fix this, verify the full URL, and update the curl command with the correct URL.

Curl error: "curl: (6) Could not resolve: ..."

When trying to invoke the API Gateway endpoint, you see the following error:

   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

 Next steps can be found in the README file at ./sam-app/README.md
        
5

This means that you've attempted to send a request to a domain that's not valid. This can happen if your serverless application failed to deploy successfully, or if you have a typo in your curl command. Verify that the application deployed successfully by using the AWS CloudFormation console or the AWS CLI, and verify that your curl command is correct.

Clean up

If you no longer need the AWS resources that you created in this tutorial, you can remove them by deleting the AWS CloudFormation stack that you deployed.

To delete the AWS CloudFormation stack using the AWS Management Console, follow these steps:

  1. Sign in to the AWS Management Console and open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation.

  2. In the left navigation pane, choose Stacks.

  3. In the list of stacks, choose sam-app (or the name of the stack that you created).

  4. Choose Delete.

When done, the status of the stack changes to DELETE_COMPLETE.

Alternatively, you can delete the AWS CloudFormation stack by running the following AWS CLI command:

   
 -----------------------
 Generating application:
 -----------------------
 Name: sam-app
 Runtime: python3.7
 Dependency Manager: pip
 Application Template: hello-world
 Output Directory: .

 Next steps can be found in the README file at ./sam-app/README.md
        
6

Verify the deleted stack

For both methods of deleting the AWS CloudFormation stack, you can verify that it was deleted by going to the AWS CloudFormation console. In the left navigation pane, choose Stacks, and then in the dropdown list next to the search box, choose Deleted. You should see your stack's name in the list of deleted stacks.

Conclusion

In this tutorial, you've done the following:

  1. Created, built, and deployed a serverless application to AWS using AWS SAM.

  2. Tested your application locally using the AWS SAM CLI and Docker.

  3. Deleted the AWS resources that you no longer need.

Next steps

To learn more about the AWS SAM CLI and begin building your own serverless applications, choose one of the following links:

Which AWS service allows you to build and model your serverless application as a visual?

AWS Step Functions is a visual workflow service that helps developers use AWS services to build distributed applications, automate processes, orchestrate microservices, and create data and machine learning (ML) pipelines.

Which AWS services would you recommend to build a serverless solution?

AWS Lambda is an event-driven, pay-as-you-go compute service that lets you run code without provisioning or managing servers.

What is the AWS serverless application model?

The AWS Serverless Application Model (SAM) is an open-source framework for building serverless applications. It provides shorthand syntax to express functions, APIs, databases, and event source mappings. With just a few lines per resource, you can define the application you want and model it using YAML.

Which AWS service allows you to share your serverless applications packages using SAM with other AWS accounts?

To share an application you've built, publish it to the AWS Serverless Application Repository. Each application is packaged with an AWS Serverless Application Model (SAM) template that defines the AWS resources used. Publicly shared applications also include a link to the application's source code.