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. Show
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.md7 message. The following diagram shows the components of this 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.md8 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.md9. 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.
PrerequisitesThis guide assumes that you've completed the steps for your operating system in Installing the AWS SAM CLI, including:
Step 1: Download a sample AWS SAM applicationCommand to run:
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.py0, 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.md8 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.py2. 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.py2. There are three especially important files:
Step 2: Build your applicationCommand 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.py4 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.py8.) Then run this command:
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.py9 to be zipped and uploaded to Lambda. You can see the following top-level tree under 0:.aws-sam/ └── build/ ├── HelloWorldFunction/ └── template.yaml 1 is a directory that contains your 2 file, and also third-party dependencies that your application uses.Step 3: Deploy your application to the AWS CloudCommand to run:
Follow the on-screen prompts. To accept the default options provided in the interactive experience, respond with 3.For the prompt 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 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:
After successfully deploying your application, you see output like the following: 0If you see 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 locallyTo 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:
This step describes both options. Host your API locallyCommand to run: 1Example output: 2It 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: 3Example output: 4What 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 directlyCommand to run: 5Example output: 6What 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 7 that the sample application provides.Your initialized application comes with a default 8 event for API Gateway. A number of values are pre-populated for you. In this case, the 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 7 object: 7Example output: 8TroubleshootingAWS SAM CLI error: "Security Constraints Not Satisfied"When running sam deploy --guided, you're prompted with the question 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 --guided2 (the default response), you see the following error: 9The 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 --guided2 to this prompt, you're saying that this is not OK. To fix this, you have the following options:
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.md0 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 --guided5 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 --guided5 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.md1 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 --guided7 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 --guided7 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.md2 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.md3 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.md4 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.md5 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 upIf 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:
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.md6 Verify the deleted stackFor 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. ConclusionIn this tutorial, you've done the following:
Next stepsTo 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.
|