Sub topic 9
Defining the API and function with AWS SAM
This chapter assumes you can read a CloudFormation template, have the AWS CLI configured, and have installed the AWS SAM CLI (sam). You should also know the handler and routes from earlier chapters. Here you will describe the whole backend in one file, so you can deploy it repeatedly and get the same result.
What SAM adds to CloudFormation
AWS Serverless Application Model (SAM) is an extension of CloudFormation. A line at the top of the template, Transform: AWS::Serverless-2016-10-31, tells CloudFormation to expand short SAM resource types into the full set of resources they stand for.
One AWS::Serverless::Function with an HttpApi event becomes several CloudFormation resources:
- The Lambda function.
- An IAM execution role with basic logging permissions.
- An API Gateway route and Lambda integration for each event.
- A Lambda permission that allows API Gateway to invoke the function.
You would otherwise write each of these by hand.
The template
This template defines an HTTP API with CORS, one function, and two routes that invoke it.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
ItemsApi:
Type: AWS::Serverless::HttpApi
Properties:
CorsConfiguration:
AllowOrigins:
- https://example.com
AllowMethods:
- GET
- POST
AllowHeaders:
- content-type
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
MemorySize: 256
Timeout: 10
Events:
GetItem:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items/{id}
Method: GET
CreateItem:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items
Method: POST
Outputs:
ApiUrl:
Value: !Sub https://${ItemsApi}.execute-api.${AWS::Region}.amazonaws.comPlace the handler from the earlier chapter at src/app.py. CodeUri: src/ is the folder that gets packaged, and Handler: app.handler means the handler function in app.py.
Reading the template
The API resource
AWS::Serverless::HttpApi creates the API and its stage. If you set no StageName, SAM creates the $default stage with automatic deployment turned on. Changes to routes therefore go live as soon as the stack update finishes. A $default stage also means the URL has no stage prefix, which is why the output URL ends at amazonaws.com.
!Ref ItemsApi on an HTTP API returns the API ID. The Outputs section builds the invoke URL from that ID and the stack's region.
The function resource
MemorySize and Timeout are the two main tuning settings. Lambda allocates CPU in proportion to memory, so raising memory can shorten run time. Keep Timeout below the HTTP API's integration timeout, which is 30 seconds. A function that runs longer would still be cut off by the API, and the client would get an error.
The events
Each key under Events (GetItem, CreateItem) is a logical name. Each event of Type: HttpApi creates one route. SAM builds the route key from the method and path, so these events produce GET /items/{id} and POST /items. That is the same string your handler reads from requestContext.routeKey. SAM sets payload format 2.0 for these events, which matches the handler.
Path templates follow the routing rules from earlier. {id} matches one path segment, {proxy+} matches the rest of the path, and Path: $default with Method: ANY creates the catch-all route.
Explicit and implicit APIs
If an HttpApi event omits ApiId, SAM creates an implicit API named ServerlessHttpApi and attaches every such event to it. That is quick for a demo. It gives you nowhere to put CORS, authorizers or stage settings, because you have no API resource to configure. Declare the API explicitly and reference it with ApiId, as above.
Permissions for the function
SAM attaches the AWSLambdaBasicExecutionRole managed policy to the generated execution role. It only allows writing to CloudWatch Logs. If your function reads a DynamoDB table, add a Policies entry using a SAM policy template:
Policies:
- DynamoDBReadPolicy:
TableName: items-tablePrefer these narrow templates over broad managed policies. The function should receive only the access it needs.
Build, deploy and test
Run these commands from the folder that contains template.yaml:
sam validate --lint
sam build
sam deploy --guidedsam validate --lintchecks the template for syntax and common errors before you deploy.sam buildcopies your code and installs dependencies fromrequirements.txtinto.aws-sam/build/.sam deploy --guidedasks for a stack name and region, then offers to save the answers insamconfig.toml. Later you can runsam deploywithout prompts.
SAM uploads the build output to an S3 bucket it manages and creates or updates the CloudFormation stack. The stack's ApiUrl output appears at the end of the deploy. Use that value in the curl calls from the earlier chapter.
For quick feedback while developing, two commands help:
sam local start-apiruns the API on your machine inside a container that emulates Lambda. It needs Docker.sam sync --watchpushes code changes to the deployed stack without a full CloudFormation update. Use it on a development stack only, because it makes the deployed resources differ from the template.
To remove everything, run sam delete.
Common errors and gotchas
| Symptom | Likely cause |
|---|---|
| `Runtime and Handler` error at invoke: `No module named 'app'` | `CodeUri` points to the wrong folder, or the file is not named `app.py`. |
| 500 from a route that worked locally | Missing dependency in `requirements.txt`, or the function lacks an IAM permission. Check CloudWatch Logs. |
| Browser CORS error with `curl` working | `AllowOrigins` does not match the page's exact origin, including scheme and port. |
| Stack update fails on a route | Two events define the same method and path. |
| `sam deploy` fails with an insufficient capabilities error | The stack creates IAM roles. Confirm `CAPABILITY_IAM` when prompted, or pass `--capabilities CAPABILITY_IAM`. |
Exercises
Exercise
An HttpApi event on your function has no ApiId. You now need to add a JWT authorizer to that API. What must you change in the template, and why?
Show answer
Declare an explicit AWS::Serverless::HttpApi resource, set the authorizer in its Auth property, and add ApiId: !Ref to the event. Without ApiId, SAM creates an implicit API that you cannot configure in the template, so there is no place to define the authorizer.
Exercise
Your function runs for 40 seconds on a slow request, and its Timeout is 60. Clients see errors after about 30 seconds. Why, and how do you fix it?
Show answer
The HTTP API integration timeout is at most 30 seconds, so API Gateway gives up before Lambda finishes, whatever the function's own timeout says. Make the work finish within 30 seconds, or move it to an asynchronous design where the API returns quickly and the job completes in the background.