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)