Section 1: Serverless foundations
Your first function with AWS SAM
AWS SAM (Serverless Application Model) is an extension of CloudFormation with shorthand for serverless resources, plus a CLI for building, testing locally and deploying.
Create the project
sam init --runtime python3.13 --app-template hello-world --name bookings-api
cd bookings-api
The generated template.yaml is the heart of the project. A trimmed version:
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Runtime: python3.13
Architectures: [arm64]
MemorySize: 256
Timeout: 10
Resources:
ListSessionsFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: sessions.list_handler
Events:
Api:
Type: HttpApi
Properties:
Path: /sessions
Method: get
The Transform line tells CloudFormation to expand SAM resources into regular ones. One AWS::Serverless::Function with an HttpApi event creates the function, its execution role, an HTTP API, a route and the permission for API Gateway to invoke the function.
Why arm64
Graviton based Lambda functions are priced lower per gigabyte second than x86 and perform well for most Python and Node.js code. Unless a dependency ships only x86 binaries, choose arm64.
The handler
# src/sessions.py
import json
def list_handler(event, context):
sessions = [{"id": "s-1", "title": "Intro to pottery", "seats_left": 4}]
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps(sessions),
}
Build, run locally, deploy
sam build
sam local start-api # runs the API on localhost using Docker
curl http://127.0.0.1:3000/sessions
sam deploy --guided # first deploy asks for stack name and region
sam deploy --guided saves your answers to samconfig.toml, so later deploys are just sam deploy. At the end, SAM prints the API endpoint URL. Call it with curl and you have a live serverless API.
Read what was created
Open CloudFormation in the console and look at the stack's resources. Knowing exactly which role, API and permission SAM generated is the first step to controlling them, which we do in the next lessons.