By the end you'll know
- What API Gateway does in front of a Lambda function, and which of its three kinds of API to choose
- How routes, integrations and stages fit together
- What an HTTP request looks like by the time it reaches your function, and what the function must send back
- How to tell an error from your code apart from one from API Gateway
- How to lock a route so only signed AWS requests get through
- What throttling, CORS and access logs do, and what they don't
Before you start
- You need: the
juniper-ryeprofile, signed in, and Lesson 20's virtual environment. Lesson 21 explains the function, its role and its logs. - The script:
api-lab.pyfrom the practice folder'slesson-22. Everything it creates is namedjr-lesson22-*and taggedlesson=22, and itsdeletestep removes it. - How the script talks to AWS: through boto3, as in Lessons 20 and 21. Its requests to the API itself use Python's own
urllib, as a website or app would, with no AWS library involved, except to sign the staff-only requests. - To see every call the script makes that changes something, put
SHOW=1in front of any step. The "By hand" section has the same lab as AWS CLI commands. - Where you run things: your own machine, labeled (Your machine).
- Every output below is from real runs on November 14, 2026. The script hides the API's ID as
<api-id>.
A new API is public
Every route you add answers anyone on the internet who finds the address, and every request is billed, along with the function runs behind it. Lock routes that aren't meant for the public, keep a throttle limit on the stage, and delete lab APIs the same day. In this lab, the staff list of every order starts open to anyone, until the protect step locks it.
The short version
- API Gateway gives a function a web address, and handles the parts of HTTP the function shouldn't: routing, authorization, throttling and CORS.
- Choose an HTTP API unless you need a REST API's extras. It costs $1.00 per million requests, against $3.50.
- A route sends a method and path to an integration, here the Lambda function; a stage publishes the routes.
- Errors shaped
{"message": ...}come from API Gateway; anything else came from your code. A crash in your code reaches the caller as a bare 500. - Throttling protects your bill and your backend, roughly. CORS only tells browsers what they may read; it stops nobody else.
What this lesson costs
| Part | Cost, in us-east-2 |
|---|---|
| HTTP API requests | $1.00 per million |
| REST API requests, for comparison | $3.50 per million |
| API Gateway's free tier | 12 months, for accounts on the paid plan; the free plan pays from credits |
| This lab's requests, about 70 | About $0.0001 |
| The function's runs | Inside Lambda's free allowance |
| The table and the logs | Under 1 cent |
| This lesson | Under 1 cent, from credits |
A front door for the function
In Lesson 21 the order function could only be run by something with AWS credentials: your script, or S3. The bakery's website has neither. It speaks HTTP: it sends a POST with some JSON and expects a status code back. API Gateway is the piece in between. It gives the function an HTTPS address, turns each request into an event, runs the function, and turns what the function returns into a response.
API Gateway offers three kinds of API:
| Kind | Per million requests | Choose it for |
|---|---|---|
| HTTP API | $1.00 | Most new APIs in front of Lambda or another web service. Simpler and faster to set up. The lab uses this. |
| REST API | $3.50 | Extras HTTP APIs lack: API keys and usage plans, request validation, response caching, AWS WAF, private APIs inside a VPC |
| WebSocket API | $1.00 per million messages, plus connection minutes | Two-way connections that stay open, like a live order board |
The names are historical: both HTTP and REST APIs serve ordinary REST-style JSON APIs.
Is it allowed, and what does it cost?
(Your machine)
cd ~/Apps/aws-practice/lesson-22
source ../lesson-20/.venv/bin/activate
python api-lab.py fence
== Is this allowed in us-east-2?
API Gateway allowed
Lambda allowed
IAM roles allowed
CloudWatch Logs allowed
DynamoDB allowed
== What API Gateway costs, in us-east-2
HTTP API: $1.00 per million requests
REST API: $3.50 per million requests
its free tier is for the first 12 months of a paid-plan account; the free plan pays from credits
this lab: about 100 requests: about $0.0001
Lambda's runs: inside its free allowance; the table and logs: under 1 cent
The prices come from AWS's Price List API, as in Lessons 15 and 21. The lab came to about 70 requests in the end.
Routes, an integration and a stage
In the console: API Gateway > Create API > HTTP API > Build, add the function as an integration, then the routes, and keep the $default stage.
python api-lab.py build
== The orders table
== The function's role: its logs, and three actions on one table
== The function, as in Lesson 21, now answering HTTP requests
active after 8 seconds (most of it waiting for the new role)
== The HTTP API
== Waiting for the new stage to answer
answered after 3 seconds; until then every route said 404 {"message":"Not Found"}
== jr-lesson22-orders-api
address: https://<api-id>.execute-api.us-east-2.amazonaws.com
route: GET /orders -> jr-lesson22-orders, anyone
route: GET /orders/{id} -> jr-lesson22-orders, anyone
route: POST /orders -> jr-lesson22-orders, anyone
stage: $default, deploys every change; at most 20 requests a second, bursts of 10
CORS: browsers may call it from https://www.juniperandrye-lab.com only
| Part | Is | In the lab |
|---|---|---|
| Route | A method and a path, like POST /orders. matches any one path segment. | Place an order, look one up, list them all |
| Integration | Where a route sends the request | The function, as a Lambda proxy: the whole request goes in, the function's answer comes out |
| Stage | A published version of the routes, with its own settings | $default, at the root of the address, deploying every change |
| Resource policy on the function | Lets API Gateway run the function, as S3 needed in Lesson 21 | For this API only |
| Throttling | A limit on requests per second, per stage or route | 20 a second, bursts of 10 |
| CORS settings | Which websites' pages may read the answers | The bakery's site only |
For 3 seconds after it was made, every route answered 404 {"message":"Not Found"}. The stage was still being set up. A script that builds an API and calls it straight away needs to wait for it, like Lesson 20's waiters; there's no waiter for this, so the script polls.
What the function receives, and returns
API Gateway turns each request into an event like this, trimmed to the parts the function uses:
{
"routeKey": "GET /orders/{id}",
"rawPath": "/orders/8873db",
"pathParameters": {"id": "8873db"},
"headers": {"content-type": "application/json", "user-agent": "Python-urllib/3.13"},
"body": null,
"isBase64Encoded": false,
"requestContext": {"http": {"method": "GET", "sourceIp": "your IP"}, "requestId": "..."}
}
The function answers with a status code, headers and a body as a string:
def answer(status, body):
return {"statusCode": status, "headers": {"content-type": "application/json"}, "body": json.dumps(body)}
def handler(event, context):
route = event["routeKey"]
if route == "GET /orders/{id}":
oid = event["pathParameters"]["id"]
found = ddb.get_item(TableName=TABLE, Key={"order": {"S": oid}}).get("Item")
if not found:
return answer(404, {"error": "no order " + oid})
return answer(200, {"order": oid, "item": found["item"]["S"], "qty": int(found["qty"]["N"])})
...
One function handles all three routes by checking routeKey. The other way is one function per route, each with its own narrow role; both are common. The function's role here allows PutItem, GetItem and Scan on one table, and nothing else.
Calling it
python api-lab.py call
== POST /orders {"item": "sourdough", "qty": 2}
201, 182 ms: {"order": "8873db", "item": "sourdough", "qty": 2}
== POST /orders {"item": "rye"}
201, 188 ms: {"order": "da53d3", "item": "rye", "qty": 1}
== GET /orders/8873db
200, 167 ms: {"order": "8873db", "item": "sourdough", "qty": 2}
response headers: apigw-requestid, connection, content-length, content-type, date
== The same request, ten times
fastest 165 ms, middle 173 ms, slowest 180 ms (from your machine, there and back)
About 170 ms from a laptop to Ohio and back, of which the function used 12 to 18 ms, according to the access log later. The rest is the network and setting up an encrypted connection, which the script does afresh for every request. A browser or app reuses its connection and would see less. 201 Created for a new order and 200 OK for a lookup are the function's choice: it sets statusCode, and API Gateway passes it on.
The same calls with curl, from any machine, with your own address in place of <api-id>:
curl -s -X POST https://<api-id>.execute-api.us-east-2.amazonaws.com/orders -H 'content-type: application/json' -d '{"item": "rye"}'
curl -s https://<api-id>.execute-api.us-east-2.amazonaws.com/orders/8873db
Whose error is it?
python api-lab.py errors
== 1. A body that isn't JSON: POST /orders
400: {"error": "the body must be JSON"}
== 2. JSON with no item: POST /orders
400: {"error": "item is required"}
== 3. An order that doesn't exist: GET /orders/abc123
404: {"error": "no order abc123"}
== 4. A route the API doesn't have: DELETE /orders/abc123
404: {"message":"Not Found"}
== 5. A path the API doesn't have: GET /menu
404: {"message":"Not Found"}
== 6. JSON that's a list: the code crashes: POST /orders
500: {"message":"Internal Server Error"}
Two shapes of answer, from two places. {"error": ...} is the function's own answer: it checked the request and chose the status. {"message": ...} is API Gateway's: the request never reached the function, or the function failed.
| Error | Answered by | Teaches |
|---|---|---|
| 1, 2: 400 | The function | Check input and say what's wrong. A clear 400 is a feature. |
3: 404 no order abc123 | The function | The route exists; the order doesn't |
4, 5: 404 Not Found | API Gateway | No route matched, so the function never ran, and wasn't billed |
| 6: 500 | API Gateway, for the function | [] has no .get(), so the code crashed. The caller learns nothing; the details are in the logs. |
The bare 500 is deliberate: a crash's message and traceback can reveal your code, table names or worse, so API Gateway hides them. The access log at the end shows what happened: "The Lambda function returned the following error". In Lesson 21's terms, the function's FunctionError became API Gateway's 500. Error 6 is also a bug the function should catch: check the body is a JSON object, and answer 400.
A staff-only route
GET /orders lists every order, for the bakery's staff. As built, anyone with the address can read it.
In the console: the API > Routes > GET /orders > Attach authorization > IAM (built-in).
python api-lab.py protect
== GET /orders, the staff list, before: open to anyone with the address
200: {"orders": 2, "items": ["rye", "sourdough"]}
== The route now needs requests signed with AWS credentials (AuthorizationType=AWS_IAM)
== Without a signature
403: {"message":"Forbidden"}
== Signed with your juniper-rye credentials (Signature Version 4, service execute-api)
200: {"orders": 2, "items": ["rye", "sourdough"]}
== POST /orders, unchanged: still open, for the website
201: {"order": "60b7a6", "item": "croissant", "qty": 1}
One setting on one route: unsigned requests now get 403, and API Gateway turns them away before the function runs. A signed request carries a signature made with AWS credentials, Signature Version 4, the same scheme every AWS API call uses. The script signs its request with botocore, in five lines:
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
req = AWSRequest(method="GET", url=url + "/orders")
SigV4Auth(session.get_credentials().get_frozen_credentials(), "execute-api", "us-east-2").add_auth(req)
headers = dict(req.headers.items())
API Gateway checks the signature, then checks that the signer's IAM policies allow execute-api:Invoke on that route. Your profile has full access; a staff role would get only that action, on that one route.
| Authorization | Callers prove who they are with | Use it for |
|---|---|---|
| None | Nothing | Truly public routes, like placing an order |
| IAM | A request signed with AWS credentials | Other AWS services, scripts and internal tools that already have AWS credentials |
| JWT | A token from a sign-in service, like Amazon Cognito, Auth0 or Supabase | People signed in to your website or app |
| Lambda authorizer | Whatever your own function checks | Anything the other two can't express |
API keys aren't on the list: HTTP APIs don't have them, and on REST APIs they're for counting and limiting callers, not for security. A key in a website's code is readable by anyone.
Throttling
python api-lab.py throttle
== The limit lowered from 20 a second (bursts of 10) to 2 a second (bursts of 2)
== 30 requests at once, 10 at a time, against a limit of 2 a second with bursts of 2
404: 26 requests, like {"error": "no order none"}
429: 4 requests, like {"message":"Too Many Requests"}
in 0.8 seconds
404 is the function answering "no order none": those got through. 429 never reached it.
== Lambda's own limit: at most 10 copies of all your functions running at once, in this account
== The limit set back to 20 a second, bursts of 10
The limit was 2 a second, and 26 of 30 requests got through in under a second. AWS applies throttle limits on a best-effort basis: they're spread across many servers and aren't exact. Treat a stage limit as protection against floods, a runaway script or an attack, not as a precise quota. The four that got 429 Too Many Requests never reached the function.
Throttling happens in two places. API Gateway's limits are per stage or route, with an account-wide default of 10,000 requests a second per Region. Behind it, Lambda limits how many copies of your functions run at once, across the whole account: 10, for this new account. Accounts usually get 1,000, and new ones can start lower until they're used more; Service Quotas is where you ask for more. In an earlier run of this same step, two requests came back 500 instead: most likely the function hitting that limit of 10 with 10 requests at once, which API Gateway reports as a 500, not a 429.
CORS: what browsers may read
The bakery's website, at www.juniperandrye-lab.com, will call the API from a page in the customer's browser. The API is on a different domain, so the browser first asks the API, with an OPTIONS request called a preflight, whether pages from that site may make the call and read the answer. That's CORS, cross-origin resource sharing.
python api-lab.py cors
== A browser on https://www.juniperandrye-lab.com asks: may I POST here?
204
access-control-allow-headers: content-type
access-control-allow-methods: GET,POST
access-control-allow-origin: https://www.juniperandrye-lab.com
access-control-max-age: 300
== A browser on https://example.com asks: may I POST here?
429
no access-control headers: the browser blocks the page from reading the answer
The bakery's site got permission; the other site got none. API Gateway answered the preflight itself, from the API's CORS settings, without running the function. access-control-max-age: 300 lets the browser remember the answer for 5 minutes.
The other site's 429 is the lowered limit, still in effect 15 seconds after the throttle step set it back. Limit changes, like most settings, take a little while to apply everywhere. In an earlier run the same request got 204 with no access-control headers, which is the normal answer: the preflight succeeds, and the missing headers are the refusal.
CORS isn't security. It's an instruction to browsers, about what a page from another site may read. curl, a script, or anyone's server ignores it completely; the call step never sent an Origin header and was never refused. Protect data with authorization, as on the staff route, and use CORS so your own website can work.
The access log
In the console: the API > Monitor > Logging > the $default stage.
python api-lab.py logs
== /jr-lesson22/api-access, the last 30 minutes
(64 lines, after 62 seconds of waiting for them all to arrive)
time route status ms lambda error
00:27:43 GET /orders/{id} 404 582 578 -
00:27:45 POST /orders 201 45 42 - (and 1 more like it)
00:27:45 GET /orders/{id} 200 22 18 - (and 3 more like it)
00:27:48 POST /orders 400 16 12 -
00:27:55 GET /orders 200 38 18 -
00:27:56 POST /orders 201 21 20 -
00:33:08 GET /orders/{id} 404 493 488 -
00:33:10 POST /orders 201 21 15 - (and 1 more like it)
00:33:10 GET /orders/{id} 200 16 12 - (and 10 more like it)
00:33:13 POST /orders 400 21 17 - (and 1 more like it)
00:33:13 GET /orders/{id} 404 16 12 -
00:33:14 POST /orders 500 15 11 The Lambda function returned the followi
00:33:15 GET /orders 200 23 22 -
00:33:20 GET /orders 403 0 - Forbidden
00:33:20 GET /orders 200 40 16 -
00:33:21 POST /orders 201 18 14 -
00:33:37 GET /orders/{id} 404 12 11 - (and 12 more like it)
00:33:37 GET /orders/{id} 429 2 - Too Many Requests
00:33:37 GET /orders/{id} 404 17 15 - (and 6 more like it)
00:33:38 GET /orders/{id} 429 1 - Too Many Requests (and 1 more like it)
00:33:38 GET /orders/{id} 404 17 13 - (and 4 more like it)
00:33:38 GET /orders/{id} 429 4 - Too Many Requests
00:33:38 GET /orders/{id} 404 17 13 - (and 4 more like it)
00:33:54 - 204 3 0 -
00:33:55 - 429 5 - Too Many Requests
== By status
200: 18
201: 6
204: 1
400: 3
403: 1
404: 29
429: 5
500: 1
One line per request, in a format you choose, written by API Gateway to a CloudWatch Logs group. The stage's format here records the request ID, time, route, status, total milliseconds, the function's milliseconds and any error; the script groups repeated lines. Things to see in it:
- The first request after
buildtook 493 ms, nearly all of it the function's cold start (Lesson 21). Every later one took 12 to 22 ms in the function. - The 403 and the 429s show
-for the function: API Gateway refused them first, so the function never ran. - The 500 says "The Lambda function returned the following error", the detail the caller never saw.
- The two lines with route
-are the CORS preflights, which match no route. - The lines at 00:27 are from an earlier run, five minutes before, which had deleted its log group; they turned up in this run's new group with the same name. Lines can arrive late, which is also why the step waited 62 seconds. Give each environment its own log group names, so one run's lines can't mix with another's.
The format deliberately leaves out callers' IP addresses, which API Gateway offers as $context.identity.sourceIp. In production you'd usually keep them, for spotting abuse, and treat the logs as personal data.
Take it down
In the console: delete the API; then the function, its role, both log groups and the table, as in Lesson 21.
python api-lab.py delete
== Deleting the API (its routes, integration and stage go with it)
== Deleting the function
== Deleted both log groups
== Deleting the role
== Deleting the table
== Anything left from Lesson 22
nothing: all clear
Deleting the API takes its routes, integration, stage and address with it; anyone who calls the old address gets an error from DNS, not from you.
By hand: the same API with the AWS CLI
The fastest way is quick create, which makes the API, a catch-all route, the integration and the $default stage in one command. (Your machine) Start from Lesson 21's "By hand" function, then:
export AWS_PROFILE=juniper-rye AWS_REGION=us-east-2
FN_ARN=$(aws lambda get-function --function-name jr-lesson22-orders --query Configuration.FunctionArn --output text)
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
API_ID=$(aws apigatewayv2 create-api --name jr-lesson22-orders-api --protocol-type HTTP --target "$FN_ARN" \
--query ApiId --output text)
Then let API Gateway run the function, and try it:
aws lambda add-permission --function-name jr-lesson22-orders --statement-id api-gateway \
--action lambda:InvokeFunction --principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:us-east-2:$ACCOUNT:$API_ID/*"
curl -s https://$API_ID.execute-api.us-east-2.amazonaws.com/orders/none
Or, instead of quick create, the lab's version, with named routes, throttling, CORS and an access log. Run the same add-permission afterwards, for its new $API_ID:
API_ID=$(aws apigatewayv2 create-api --name jr-lesson22-orders-api --protocol-type HTTP --query ApiId --output text \
--cors-configuration '{"AllowOrigins":["https://www.juniperandrye-lab.com"],"AllowMethods":["GET","POST"],"AllowHeaders":["content-type"],"MaxAge":300}')
INTEGRATION_ID=$(aws apigatewayv2 create-integration --api-id $API_ID --integration-type AWS_PROXY \
--integration-uri "$FN_ARN" --payload-format-version 2.0 --query IntegrationId --output text)
aws apigatewayv2 create-route --api-id $API_ID --route-key 'POST /orders' --target integrations/$INTEGRATION_ID
aws apigatewayv2 create-route --api-id $API_ID --route-key 'GET /orders/{id}' --target integrations/$INTEGRATION_ID
aws apigatewayv2 create-route --api-id $API_ID --route-key 'GET /orders' --target integrations/$INTEGRATION_ID \
--authorization-type AWS_IAM
aws logs create-log-group --log-group-name /jr-lesson22/api-access
aws apigatewayv2 create-stage --api-id $API_ID --stage-name '$default' --auto-deploy \
--default-route-settings ThrottlingRateLimit=20,ThrottlingBurstLimit=10 \
--access-log-settings file://access-log.json
aws apigatewayv2 delete-api --api-id $API_ID
access-log.json, with your own account ID in place of 111122223333:
{"DestinationArn": "arn:aws:logs:us-east-2:111122223333:log-group:/jr-lesson22/api-access",
"Format": "{\"requestId\":\"$context.requestId\",\"route\":\"$context.routeKey\",\"status\":\"$context.status\"}"}
The access log format must include $context.requestId or $context.extendedRequestId; the first version of the lab's script left it out, and creating the stage failed with exactly that message.
In real systems
- APIs have their own domain name, like
api.juniperandrye.example, with an ACM certificate (Lesson 14), so the address doesn't change when the API is rebuilt. - Every route that isn't truly public has authorization, usually JWT for people and IAM for systems, and a test that an unsigned request gets 403.
- Functions validate their input and return clear 400s, so a bad request never becomes a 500.
- Stages and routes have throttle limits sized to what the backend can take, and Lambda's concurrency limit is raised before launch, not after the first busy day.
- Access logs and alarms on 5xx responses feed monitoring (Lesson 32).
- The API is Terraform or AWS SAM, with separate stages or separate APIs for development and production.
- Public REST APIs often sit behind AWS WAF; HTTP APIs can be put behind CloudFront with WAF instead (Lesson 14).
Spot the problem
Work out what's wrong before you read the explanation.
"A stranger posted our customers' orders online." The bakery added GET /orders for the staff's tablet app, and hid the address in the app. A week later someone found the address in the app's code and downloaded every order. What's wrong? The route had no authorization, so the address was the only protection, and an address isn't a secret. The fix: require authorization on the route, IAM for an internal tool or JWT for staff who sign in, and give the tablet's identity permission for that route only. Then check: does a request without credentials now get 403 {"message":"Forbidden"}, and never reach the function?
Keep this
| Remember | Why |
|---|---|
| HTTP API unless you need a REST API's extras | $1.00 per million requests, against $3.50 |
| Route, integration, stage | What's asked for, where it goes, where it's published |
| A new stage needs a few seconds | Until then every route said 404 |
is API Gateway's; the rest is yours | And your crash becomes a bare 500 |
| Every route is public until you lock it | One setting turned the staff list into a 403 |
| Throttling is best effort | 26 of 30 got through a limit of 2 a second |
| Lambda has its own limit, account-wide | 10 at once, on this new account |
| CORS is for browsers, not security | Scripts and curl ignore it |
| Access logs show what callers don't | Including the 500's real cause |
Where you are now
The bakery's order function has a web address: routes to place and look up orders, open to the website, and a staff list that turns away anyone without AWS credentials. You saw a new stage answer after 3 seconds, told the function's errors apart from API Gateway's, watched a crash become a bare 500 with its cause only in the logs, found that a throttle limit of 2 a second let 26 of 30 through, met this account's Lambda limit of 10, and read every request in the access log. Next, Lesson 23 takes the work off the request path: SQS, SNS and EventBridge, so a new order can be queued, announced and acted on without the customer waiting.
Check yourself
Which kind of API did the lab use, and why?
DELETE /orders/abc123 got a 404 with a Not Found message. Who answered?
The function crashed on a list instead of an object. What did the caller see?
After protect, why did an unsigned GET /orders get 403?
The limit was 2 requests a second. How many of the 30 got through?
What does CORS stop?
The first request after build took 493 ms; later ones about 15. Why?
Key terms
- API Gateway: AWS's service for giving backends, like Lambda functions, an HTTPS address.
- HTTP API, REST API, WebSocket API: API Gateway's three kinds of API.
- Route: a method and path, like
GET /orders/{id}. - Integration: where a route sends requests; a Lambda proxy integration passes the whole request to a function.
- Stage: a published set of routes with its own settings;
$defaultis at the address's root. - Payload format 2.0: the shape of the event an HTTP API sends a function, and of the answer it expects.
- Authorization: checking a caller before the route runs: IAM, JWT or a Lambda authorizer.
- Signature Version 4 (SigV4): AWS's way of signing a request with credentials.
- Throttling: refusing requests over a rate, with
429 Too Many Requests. - Concurrency limit: the most copies of an account's Lambda functions that can run at once.
- CORS (cross-origin resource sharing): how an API tells browsers which other sites' pages may read its answers.
- Preflight: the
OPTIONSrequest a browser sends to ask about CORS first. - Access log: one line per request, written by API Gateway in a format you choose.
Go deeper
- Networking track: What happens when you visit a site and TLS and HTTPS. Web development track: Data from an API, for the website side. Python track: Talking to APIs.
- AWS: choosing between HTTP and REST APIs (opens in a new tab), API Gateway pricing (opens in a new tab), and Lambda integrations for HTTP APIs (opens in a new tab).
- AWS: controlling access to HTTP APIs (opens in a new tab), throttling (opens in a new tab), CORS (opens in a new tab), and access logging variables (opens in a new tab).
- Try: run
build, then add a JWT authorizer toGET /ordersinstead of IAM, using a free Supabase project as the sign-in service (the Web development track's Login with Supabase sets one up), and call the route with a signed-in user's token. Rundeletewhen you're done.