Sub topic 10
Stages and deploying the API
This chapter covers what a stage is in an HTTP API, how a deployment makes route changes live, and how to run separate environments from one SAM template. It assumes you can write a SAM template with an AWS::Serverless::HttpApi and a Lambda function, as in the previous chapter. It also assumes the AWS CLI and the SAM CLI are installed and configured.
What a stage is
An HTTP API holds routes and integrations. A stage is a named, addressable snapshot of that API that clients can call. A route does nothing until a stage exposes it. Each stage has its own settings:
- The URL clients call.
- Stage variables.
- Default throttling.
- Access logging.
- The auto-deploy flag.
One API can have several stages, such as dev, test and prod. All of them serve the same routes, but each can have different settings.
The $default stage and named stages
The stage name decides the invoke URL.
| Stage name | Invoke URL | Notes |
|---|---|---|
| `$default` | `https://{api-id}.execute-api.{region}.amazonaws.com/items` | No path prefix. |
| `prod` | `https://{api-id}.execute-api.{region}.amazonaws.com/prod/items` | The stage name is the first path segment. |
If you omit StageName, SAM creates the $default stage. A client that calls a named-stage API without the prefix gets {"message":"Not Found"} from API Gateway. The request never reaches Lambda, so your function logs show nothing.
The stage name also appears in the event your function receives. With payload format 2.0, requestContext.stage holds the stage name. For a named stage, rawPath includes the prefix, for example /prod/items/42. The routeKey does not include it. Branch on routeKey so the same code works in every stage.
Deployments and auto-deploy
Changing a route, an integration or an authorizer does not change what clients see until you deploy it to a stage. An HTTP API can do this automatically. When a stage has auto-deploy enabled, API Gateway deploys each configuration change to that stage on its own. SAM sets this flag on the stage it creates, so a sam deploy that changes routes goes live as soon as CloudFormation finishes.
Auto-deploy is convenient, but it removes the review step between editing and serving. If you create the API outside SAM with auto-deploy off, you must deploy by hand:
API_ID="abc123"
aws apigatewayv2 create-deployment --api-id "$API_ID" --stage-name prod
aws apigatewayv2 get-stages --api-id "$API_ID" \
--query 'Items[].{name:StageName,auto:AutoDeploy}'A common mistake is to add a route, see no error, and still get a 404. When that happens, check AutoDeploy on the stage first.
One template, several environments
There are two ways to run several environments.
- Several stages on one API. You manage one API, and every stage serves the same routes. The environments share a Lambda function unless you route them with aliases. A change to a route reaches every auto-deploy stage at once.
- One stack per environment. Each environment has its own API, function and IAM role. A broken dev deployment cannot affect prod. This is the safer default for teams.
The template below supports the second approach. It takes the stage name as a parameter and uses it as the stage name.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless::TransformThat fragment is wrong for real use, so here is the correct full template:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
Stage:
Type: String
Default: dev
AllowedValues:
- dev
- prod
Resources:
ItemsApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: !Ref Stage
StageVariables:
tableSuffix: !Ref Stage
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
Outputs:
ApiUrl:
Value: !Sub https://${ItemsApi}.execute-api.${AWS::Region}.amazonaws.com/${Stage}The output URL ends with /${Stage}. If you used $default, you would leave that suffix off.
Stage variables
A stage variable is a key-value pair that belongs to a stage. Use it for small per-stage differences that are not secrets. API Gateway passes the variables to your function in event["stageVariables"]. You can also use them in integration settings, for example to point a route at a different Lambda alias per stage. Do not store credentials in them. Anyone who can read the stage configuration can see them.
def handler(event, context):
stage = event["requestContext"]["stage"]
suffix = (event.get("stageVariables") or {}).get("tableSuffix", "dev")
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": '{"stage": "%s", "table": "items-%s"}' % (stage, suffix),
}The or {} matters. When a stage has no variables, stageVariables may be missing or null. The code above reads it safely in both cases.
For configuration that differs between environments in a larger way, Lambda environment variables set in the template are usually clearer. Stage variables are most useful when API Gateway itself needs the value.
Deploying and calling the API
Build and deploy one stack per environment. The stack name keeps the environments apart.
sam build
sam deploy \
--stack-name items-dev \
--parameter-overrides Stage=dev \
--capabilities CAPABILITY_IAM \
--resolve-s3
API_URL=$(aws cloudformation describe-stacks \
--stack-name items-dev \
--query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" \
--output text)
curl -i "$API_URL/items/42"To create prod, run the same commands with --stack-name items-prod and Stage=prod. Add sam deploy --guided the first time if you want SAM to save these choices in samconfig.toml.
Common problems
- 404 with
{"message":"Not Found"}. The stage prefix is missing from the URL, the route does not exist, or the change was never deployed. If Lambda logs show no invocation, the request stopped at API Gateway. - A route works in one stage and not in another. With auto-deploy off, the stages were deployed at different times. Compare the stages with
get-stages. - Handler logic that checks
rawPath. It breaks when you move from$defaultto a named stage. UserouteKeyorpathParameters. - Renaming the stage in a template. CloudFormation replaces the stage, so the invoke URL changes. Clients that hard-code the old URL fail until they are updated.
Exercise
You deploy an API with StageName: prod. A colleague calls https://abc123.execute-api.us-east-1.amazonaws.com/items/42 and receives {"message":"Not Found"}. Your Lambda log group has no new entries. What is the most likely cause, and how do you fix it?
Show answer
The URL is missing the stage prefix. For a named stage the first path segment is the stage name, so API Gateway finds no matching route and returns 404 without invoking Lambda. Call https://abc123.execute-api.us-east-1.amazonaws.com/prod/items/42.
Exercise
In a payload 2.0 event from the prod stage, rawPath is /prod/items/42. Which event field should your handler branch on so the same code works in every stage, and what is its value for this request?
Show answer
Branch on event["requestContext"]["routeKey"]. Its value is GET /items/{id}, which does not include the stage name.