DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

sreekarsai08
sreekarsai08

Posted on

Build HelloWorld API using AWS SAM

Serverless Application Model (AWS SAM):

The AWS Serverless Application Model (AWS SAM) is an open-source framework that you can use to build serverless applications on AWS.

A serverless application is a combination of Lambda functions, event sources, and other resources that work together to perform tasks. Note that a serverless application is more than just a Lambda functionโ€”it can include additional resources such as APIs, databases, and event source mappings.

Benefits:

  • Single-deployment configuration

  • Extension of AWS CloudFormation

  • Built-in best practices

  • Local debugging and testing

  • Deep integration with development tools

Prerequisites:

Architecture Overview:

Architecture Diagram

Download stage:

sam init

Choose AWS Quick Start Templates

Choose AWS Quick Start Templates

Choose Hello World Example

Choose Hello World Example

Give y

Give y - we are going with python and zip package

Give y

Give y - This will enable X-Ray tracing for function

Give project name

Give project name as firstserverlessapp

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:

firstserverlessapp/
โ”œโ”€โ”€ 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

There are three especially important files:

  • template.yaml: Contains the AWS SAM template that defines your application's AWS resources.

  • hello_world/app.py: Contains your actual Lambda handler logic.

  • hello_world/requirements.txt: Contains any Python dependencies that the application requires, and is used for sam build.

Build stage:

sam build

SAM Build

You can see the following top-level tree under .aws-sam:

AWS SAM

Deploy stage:

sam deploy --guided

Deploy SAM

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

{"message": "hello world"}

Test locally:

sam local start-api

Sam local

curl http://127.0.0.1:3000/hello

Invoke Lambda function:

sam local invoke "HelloWorldFunction" -e events/event.json

Invoke lambda

Clean up:

aws cloudformation delete-stack --stack-name **sam-app** --region **region**

Replace sam-app with stack name and region with your aws region

Top comments (0)

๐Ÿ” If you came here from Google, why not take a look at some of our top posts?