Sub topic 9
Defining the API and function with AWS SAM
This chapter assumes you can write a Lambda handler, know what a route and a proxy integration are, and can use the AWS CLI. You will describe the API and its function in one template, so the whole setup can be reviewed, versioned and deployed as a unit.
Why define the API as code
Creating routes by hand in the console works for a first experiment. It is hard to repeat and hard to review. The AWS Serverless Application Model (SAM) is an extension of CloudFormation. You write a short template, and the Transform line expands it into the full set of CloudFormation resources: the API, the function, its execution role, the integration, and the permission that lets API Gateway invoke the function.
The template
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.comWhat each part does
AWS::Serverless::HttpApicreates the HTTP API. TheCorsConfigurationblock is covered in a later chapter.AWS::Serverless::Functioncreates the Lambda function.Handler: app.handlermeans the functionhandlerinsrc/app.py.CodeUripoints at the folder that SAM packages.- Each entry under
EventswithType: HttpApicreates one route.PathandMethodcombine into the route key, so these two events produceGET /items/{id}andPOST /items. This matches therouteKeyvalues your handler branches on. ApiId: !Ref ItemsApiattaches the route to this API. If you leave it out, SAM creates a separate implicit API, which is a common cause of "my routes ended up on a different URL".Outputsprints the base URL after deployment.!Refon an HttpApi returns its API ID.
Both routes point at one function, so the handler does the routing. You can instead declare one function per route. That gives each its own permissions and scaling, at the cost of more deployed code.
Build and deploy
Run these commands from the folder that holds template.yaml and src/app.py.
sam validate
sam build
sam deploy --guidedsam build copies your code into .aws-sam/build. sam deploy --guided asks for a stack name and region, then saves your answers to samconfig.toml. Later deployments only need sam deploy. When it finishes, the ApiUrl output is printed.
Common errors
| Symptom | Likely cause |
|---|---|
| `Handler not found` at runtime | `Handler` does not match the file and function name, or `CodeUri` points at the wrong folder |
| Route returns `{"message":"Not Found"}` | The path or method in `Events` differs from what you called |
| Routes appear on a second API | `ApiId` is missing from an event |
| Deploy fails with `CAPABILITY_IAM` | The role SAM creates needs approval, so accept it when prompted or pass `--capabilities CAPABILITY_IAM` |
Exercise
You add a third event with Path: /items/{id} and Method: DELETE but forget ApiId. What happens, and how do you fix it?
Show answer
SAM creates an implicit HTTP API for that event, so the DELETE route is served from a different URL than the other two routes. Add ApiId: !Ref ItemsApi to the event's Properties and redeploy.