Amazon API Gateway for Developers: REST vs HTTP APIs, Stages, Authorizers, Throttling, Caching and Lambda Integration
What API Gateway Does
API Gateway is a managed front door for APIs. It receives HTTP requests, authenticates and throttles them, optionally transforms or caches, and forwards them to Lambda, HTTP backends, AWS services or mock responses. It scales automatically and you pay per request.
| Type | Best for | Notes |
| HTTP API | Most new serverless APIs: simple, cheaper (up to ~70% less) and faster | JWT authorizers (Cognito, any OIDC), Lambda authorizers, IAM, CORS, auto deploy. No API keys, usage plans, request validation, caching or WAF directly |
| REST API | Full-featured APIs | API keys and usage plans, caching, request/response validation and mapping templates, WAF, canary deployments, private APIs, resource policies, client certificates |
| WebSocket API | Real-time two-way (chat, live dashboards) | Routes by message content ($connect, $disconnect, $default, custom) |
Lambda Proxy Integration
In proxy integration API Gateway passes the whole request to Lambda as an event, and Lambda must return a response in the expected format. It is the simplest and most common setup.
python
import json
def handler(event, context):
# REST API (v1) event keys: httpMethod, path, pathParameters, queryStringParameters, headers, body, requestContext
# HTTP API (v2) event keys: routeKey, rawPath, pathParameters, queryStringParameters, headers, body, requestContext.http.method
method = event.get("httpMethod") or event["requestContext"]["http"]["method"]
body = json.loads(event["body"]) if event.get("body") else {}
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json", "Access-Control-Allow-Origin": "https://app.example.com"},
"isBase64Encoded": False,
"body": json.dumps({"method": method, "echo": body}),
}
| Integration | Meaning |
| Lambda proxy | Whole request goes to Lambda. You build the whole response |
| Lambda custom (non-proxy) | REST API only: mapping templates (VTL) reshape request and response |
| HTTP proxy / HTTP | Forward to a public or private (via VPC link) HTTP endpoint |
| AWS service integration | Call DynamoDB, SQS, Step Functions, S3... directly without Lambda |
| Mock | Return a fixed response, useful for tests |
bash
# Quick HTTP API with Lambda
aws apigatewayv2 create-api --name todo --protocol-type HTTP --target arn:aws:lambda:ap-south-1:111111111111:function:todo
aws lambda add-permission --function-name todo --statement-id apigw --action lambda:InvokeFunction \
--principal apigateway.amazonaws.com --source-arn "arn:aws:execute-api:ap-south-1:111111111111:abc123/*"
Stages, Deployments and Variables
- A stage is a named, deployed snapshot of the API (
dev, test, prod) with its own URL https://id.execute-api.region.amazonaws.com/prod
- In REST APIs you must create a deployment after changes. Forgetting to deploy is a classic reason for a change not appearing. HTTP APIs can auto-deploy
- Stage variables are key-value settings per stage, such as the Lambda alias:
arn:...:function:orders:${stageVariables.alias} so prod calls the prod alias
- Canary release on a REST stage sends a percentage of traffic to a new deployment
- Use custom domain names with ACM certificates and base path mappings
Authentication and Authorization
| Method | How it works | Use |
| IAM (SigV4) | Caller signs requests with AWS credentials. Policy decides | Service-to-service, internal tools |
| Cognito user pool authorizer (REST) / JWT authorizer (HTTP) | Validates a token from a user pool or OIDC provider | Mobile and web app users |
| Lambda authorizer (token or request) | Your function validates a custom token and returns an IAM policy (can be cached by token for a TTL) | Custom auth, third-party tokens, API keys in headers |
| API keys + usage plans | Identify callers and set quotas and throttles (not for authentication) | Meter partner access |
| Resource policy | Allow or deny by IP, VPC, account | Private or restricted APIs |
| Mutual TLS | Client certificates | B2B APIs |
python
# Lambda authorizer (REST API, TOKEN type) returns an IAM policy
def handler(event, context):
token = event["authorizationToken"]
effect = "Allow" if token == "valid-demo-token" else "Deny"
return {
"principalId": "user-42",
"policyDocument": {"Version": "2012-10-17", "Statement": [
{"Action": "execute-api:Invoke", "Effect": effect, "Resource": event["methodArn"]}]},
"context": {"tenant": "acme"}, # available to the backend as requestContext.authorizer.tenant
}
Throttling, Quotas and Caching
| Control | Detail |
| Account-level throttle | Default 10,000 requests per second with burst capacity 5,000 per Region (can be raised) |
| Stage and method throttling | Set rate and burst per stage or method |
| Usage plans (REST) | Per API key rate, burst and quota per day/week/month |
| Throttled request | Client gets 429 Too Many Requests |
| Caching (REST) | Per-stage cache of 0.5 to 237 GB, default TTL 300 seconds (0 to 3600). Key includes chosen parameters. Invalidate with header Cache-Control: max-age=0 if the caller is authorized |
CORS
- Browsers send a preflight OPTIONS request. The API must answer with
Access-Control-Allow-Origin, -Methods and -Headers
- HTTP API has a CORS setting. With REST API proxy integration your Lambda must also return the CORS headers in normal responses, and you add an OPTIONS method
Validation and Transformation (REST)
- Request validators reject bad bodies or missing parameters with 400 before invoking the backend, using JSON Schema models
- Mapping templates (Velocity) reshape data for non-proxy integrations and service integrations
- Gateway responses customize default errors (for example 403 and 429 bodies)
Common Error Codes (Exam Favorite)
| Code | Meaning and fix |
| 400 | Bad request, validation failed, or body mapping error |
| 401 | Unauthorized: missing or invalid token (authorizer rejected) |
| 403 | Forbidden: IAM, resource policy, WAF block, missing API key, or authorizer denied |
| 404 | Route or resource not found (also wrong stage name) |
| 429 | Throttled: slow down, raise limits, use backoff |
| 500 / 502 Bad Gateway | Integration problem. 502 often means the Lambda response was malformed (not the proxy format) or Lambda crashed |
| 503 | Service unavailable |
| 504 Gateway Timeout | Integration took too long. API Gateway timeout is 29 seconds by default (can be raised for some API types). Use asynchronous patterns for long work |
Async Pattern for Long Tasks
text
POST /reports → API Gateway → Lambda: validates, writes job to SQS or DynamoDB, returns 202 + jobId
Worker Lambda / container processes the job
GET /reports/{jobId} → status and result link (S3 presigned URL)
Monitoring
- CloudWatch metrics:
Count, 4XXError, 5XXError, Latency, IntegrationLatency, CacheHitCount
- Enable access logs (JSON format with
$context.requestId) and X-Ray tracing
- Turn on execution logging in non-production only if needed (it can log sensitive data)
Practice Tasks
- Create an HTTP API with a Lambda integration and test with curl
- Add a JWT authorizer using a Cognito user pool
- Create a REST API with an API key and usage plan limited to 10 requests per minute
- Enable stage caching and observe
CacheHitCount
- Cause a 502 by returning a plain string from Lambda proxy and fix it
Conclusion
Choose HTTP API for simple and cheap serverless APIs and REST API when you need caching, usage plans, validation or WAF. Use Lambda proxy integration, authorize with Cognito/JWT, IAM or Lambda authorizers, deploy REST changes to a stage, remember CORS, throttling (429) and the 29-second integration timeout, and decode 4xx/5xx errors correctly.
Quick Summary: types; Lambda proxy; stages; auth methods; throttling and caching; CORS; validation; error codes; async pattern; monitoring.