Build Your First Serverless API in 10 Minutes with AWS SAM
Serverless computing has revolutionized how we build and deploy applications. Instead of managing servers, you can focus on writing code while AWS handles the infrastructure. But how do you develop, test, and deploy serverless applications efficiently? Enter AWS SAM (Serverless Application Model).
In this hands-on guide, I’ll walk you through building your first serverless application using AWS SAM, from setup to deployment.
What is AWS SAM?
AWS SAM is an open-source framework that simplifies building serverless applications on AWS. It provides:
Simplified syntax for defining serverless resources
Local testing capabilities to test Lambda functions on your machine
Built-in best practices for serverless applications
Easy deployment with a single command
Think of SAM as CloudFormation on steroids, specifically designed for serverless applications.
Prerequisites
Before we start, make sure you have:
An AWS account
AWS CLI installed and configured
AWS SAM CLI installed
Python 3.9+ (we’ll use Python for our Lambda function)
Docker (for local testing)
Installing AWS SAM CLI
For macOS:
brew install aws-sam-cliFor Windows (using Chocolatey):
choco install aws-sam-cliFor Linux:
# Download the installer
wget https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip
unzip aws-sam-cli-linux-x86_64.zip -d sam-installation
sudo ./sam-installation/installVerify installation:
sam --version
# Output: SAM CLI, version 1.x.xConfigure AWS CLI
If you haven’t configured AWS CLI yet:
aws configureEnter your:
AWS Access Key ID
AWS Secret Access Key
Default region
Default output format
Step 1: Initialize Your SAM Application
SAM CLI provides templates to kickstart your project. Let’s create a new application:
sam initYou’ll be prompted with several options. Here’s what to choose:
Which template source would you like to use?
1 - AWS Quick Start Templates
2 - Custom Template Location
Choice: 1
Choose an AWS Quick Start application template
1 - Hello World Example
2 - Multi-step workflow
...
Template: 1
Use the most popular runtime and package type? (Python and zip) [y/N]: y
Would you like to enable X-Ray tracing on the function(s) in your application? [y/N]: N
Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: N
Project name [sam-app]: hello-world-samNavigate to your project directory:
cd hello-world-samStep 2: Understanding the Project Structure
Your SAM application has this structure:
hello-world-sam/
├── hello_world/
│ ├── __init__.py
│ ├── app.py # Lambda function code
│ └── requirements.txt # Python dependencies
├── events/
│ └── event.json # Sample API Gateway event for testing
├── tests/
│ ├── unit/
│ │ ├── __init__.py
│ │ └── test_handler.py
│ └── requirements.txt
├── template.yaml # SAM template (infrastructure as code)
└── README.md
Let’s examine the key files:
The Lambda Function
import json
def lambda_handler(event, context):
“”“Sample pure Lambda function
Parameters
----------
event: dict, required
API Gateway Lambda Proxy Input Format
context: object, required
Lambda Context runtime methods and attributes
Returns
------
API Gateway Lambda Proxy Output Format: dict
“”“
return {
“statusCode”: 200,
“body”: json.dumps({
“message”: “hello world”,
}),
}
This is a simple Lambda function that returns a JSON response. Notice it follows the API Gateway proxy integration format.
The SAM Template
AWSTemplateFormatVersion: ‘2010-09-09’
Transform: AWS::Serverless-2016-10-31
Description: >
hello-world-sam
Sample SAM Template for hello-world-sam
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
Architectures:
- x86_64
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
Outputs:
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: !Ref HelloWorldFunction
HelloWorldFunctionIamRole:
Description: “Implicit IAM Role created for Hello World function”
Value: !GetAtt HelloWorldFunctionRole.Arn
This template defines:
A Lambda function
HelloWorldFunctionusing Python 3.9An API Gateway endpoint (GET) that triggers the Lambda
Outputs showing the API URL and function details
Test Event
This file simulates an API Gateway request for local testing:
{
“body”: “{\”message\”: \”hello world\”}”,
“resource”: “/hello”,
“path”: “/hello”,
“httpMethod”: “GET”,
“isBase64Encoded”: false,
“queryStringParameters”: {
“foo”: “bar”
},
“pathParameters”: {
“proxy”: “/path/to/resource”
},
“stageVariables”: {
“baz”: “qux”
},
...
}
Step 3: Build Your Application
Before testing or deploying, you need to build your application. This packages your Lambda function and its dependencies:
sam buildOutput:
Building codeuri: /path/to/hello-world-sam/hello_world runtime: python3.9 ...
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource
Build Succeeded
Built Artifacts : .aws-sam/build
Built Template : .aws-sam/build/template.yaml
The command sam build:
Creates a directory
.aws-sam/build
Downloads and packages dependencies from
requirements.txt
Prepares your code for deployment or local testing
Generates a build-ready template
Step 4: Test Locally with SAM CLI
One of SAM’s killer features is local testing. Let’s test our function locally before deploying to AWS.
Option 1: Invoke Function Directly
Test your Lambda function with a sample event:
sam local invoke HelloWorldFunction --event events/event.jsonOutput:
Invoking app.lambda_handler (python3.9)
Local image was not found.
Pulling container image from public.ecr.aws/lambda/python:3.9...
Mounting /path/to/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated...
START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: \$LATEST
END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72
REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 2.63 ms Billed Duration: 3 ms Memory Size: 128 MB Max Memory Used: 128 MB
{”statusCode”:200,”body”:”{\”message\”: \”hello world\”}”}
Option 2: Start a Local API Gateway
Start a local API Gateway emulator:
sam local start-apiOutput:
Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
...
Press CTRL+C to quitNow test your endpoint with curl:
curl http://127.0.0.1:3000/helloResponse:
{”message”: “hello world”}
You can also test with query parameters:
curl “http://127.0.0.1:3000/hello?name=John”Option 3: Generate Sample Events
SAM can generate sample events for various AWS services:
sam local generate-event apigateway aws-proxy > test-event.json
sam local invoke HelloWorldFunction --event test-event.jsonUnderstanding Local Testing
When you run
sam localSAM:
Downloads a Docker image that mimics the Lambda runtime
Mounts your code into the container
Executes your function in an environment nearly identical to AWS Lambda
Returns the response
This means you can develop and test without deploying to AWS!
Step 5: Deploy to AWS
Now for the exciting part—deploying to AWS!
First-Time Deployment: Guided Deploy
For your first deployment, use the guided mode:
sam deploy --guidedYou’ll be prompted with configuration questions:
Configuring SAM deploy
======================
Looking for config file [samconfig.toml] : Not found
Setting default arguments for ‘sam deploy’
=========================================
Stack Name [sam-app]: hello-world-sam-stack
AWS Region [us-east-1]: us-east-1
#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
#Preserves the state of previously provisioned resources when an operation fails
Disable rollback [y/N]: N
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]:
Looking for resources needed for deployment:
...
Here’s what each option means:
Stack Name: CloudFormation stack name (must be unique in your account/region)
AWS Region: Where to deploy your application
Confirm changes before deploy: Show a changeset before deploying
Allow SAM CLI IAM role creation: SAM creates IAM roles for your Lambda function
Disable rollback: Whether to keep resources if deployment fails
Authorization: Your API will be publicly accessible
Save arguments: Saves configuration to
samconfig.toml
for future deployments
Step 6: Test Your Deployed Application
Now let’s test the live API in AWS!
Get Your API Endpoint
From the deployment output, copy the API URL. It looks like:
https://abc123xyz.execute-api.us-east-1.amazonaws.com/Prod/hello/Or retrieve it from CloudFormation outputs:
aws cloudformation describe-stacks \
--stack-name hello-world-sam-stack \
--query ‘Stacks[0].Outputs[?OutputKey==`HelloWorldApi`].OutputValue’ \
--output textTest with curl
export API_URL=”https://abc123xyz.execute-api.us-east-1.amazonaws.com/Prod”
curl \$API_URL/helloResponse:
{”message”: “hello world”}Step 7: Cleaning Up Resources
When you’re done experimenting, delete your stack to avoid any potential charges:
sam delete --stack-name hello-world-sam-stackYou’ll be prompted:
Are you sure you want to delete the stack hello-world-sam-stack in the region us-east-1 ? [y/N]: y
Are you sure you want to delete the folder hello-world-sam-stack in S3 which contains the artifacts? [y/N]: yThis removes:
Lambda function
API Gateway
IAM roles
CloudWatch log groups
Deployment artifacts from S3
Verify deletion:
aws cloudformation describe-stacks --stack-name hello-world-sam-stackYou should get an error indicating the stack doesn’t exist.
What You’ve Learned
Congratulations! You’ve successfully:
✅ Initialized a SAM application from a template
✅ Built and packaged a serverless application
✅ Tested Lambda functions locally without deploying to AWS
✅ Deployed a complete serverless API to AWS
✅ Monitored and viewed logs for your Lambda function
✅ Modified and redeployed your application
✅ Cleaned up AWS resources
All with the default “Hello World” template, without modifying the infrastructure!
Conclusion
AWS SAM transforms serverless development by providing an intuitive framework that handles the complexity of Lambda, API Gateway, and related AWS services. With just a few commands, you built, tested, and deployed a production-ready serverless API—all while staying in the AWS free tier.
The beauty of SAM is its simplicity. The default “Hello World” template gives you everything you need to start building real applications. As you grow more comfortable, you can add databases, authentication, monitoring, and more—all using the same SAM workflow.

