API Gateway & REST APIs
A comprehensive deep dive into Amazon API Gateway — API types, integration models, authorization, throttling, stages, caching, WebSocket APIs, and deployment patterns for the DVA-C02 exam.
What is Amazon API Gateway?
Amazon API Gateway is a fully managed service for creating, publishing, securing, and monitoring APIs at any scale. It acts as the front door for applications to access backend services — Lambda functions, EC2, ECS, DynamoDB, or any HTTP endpoint.
Core mental model: API Gateway handles all the cross-cutting concerns of an API (auth, throttling, caching, TLS, logging) so your backend only needs to handle business logic.
API Types Comparison
API Gateway offers three distinct API types. Choosing the right one is a common DVA-C02 exam question.
| Feature | REST API | HTTP API | WebSocket API |
|---|---|---|---|
| Latency | Medium | Lowest | N/A |
| Price | Standard | ~71% cheaper | Per message + connection |
| Lambda integration | Proxy + Custom | Proxy only | Proxy only |
| AWS service integration | ✅ | ❌ | ❌ |
| Usage plans & API keys | ✅ | ❌ | ❌ |
| Per-method throttling | ✅ | ❌ | ❌ |
| Response caching | ✅ | ❌ | ❌ |
| Request validation | ✅ | ❌ | ❌ |
| VTL mapping templates | ✅ | ❌ | ❌ |
| OIDC / JWT auth | ✅ (Lambda auth) | ✅ native | ❌ |
| Mutual TLS | ✅ | ✅ | ❌ |
| X-Ray tracing | ✅ | ✅ | ❌ |
| Persistent connections | ❌ | ❌ | ✅ |
Exam rule: If the question mentions usage plans, API keys, caching, VTL transforms, or AWS service integrations → it must be a REST API. HTTP API is the answer when the question emphasizes cost and simplicity.
Endpoint Types
When creating a REST API you choose one of three endpoint types:
| Type | Description | Use case |
|---|---|---|
| Edge-Optimized | Routed through CloudFront PoPs globally | Public APIs with geographically distributed clients |
| Regional | Deployed in a single AWS region | Same-region clients, custom CloudFront setup |
| Private | Only accessible inside a VPC via interface VPC endpoint | Internal microservices, private backends |
Request / Response Flow
Every request passes through this pipeline:
- Method Request — validates incoming request (headers, query params, body schema)
- Integration Request — transforms the request before sending to the backend
- Backend — Lambda, HTTP endpoint, or AWS service
- Integration Response — transforms the backend response
- Method Response — final response sent to the client
Integration Types
1. Lambda Proxy Integration (Most Common)
API Gateway passes the entire HTTP request as-is to Lambda and expects a structured response. No mapping templates needed. The simplest setup for serverless APIs.
1// Lambda receives the full API Gateway event
2exports.handler = async (event) => {
3 console.log('Method:', event.httpMethod);
4 console.log('Path:', event.path);
5 console.log('Path params:', event.pathParameters);
6 console.log('Query params:', event.queryStringParameters);
7 console.log('Headers:', event.headers);
8 console.log('Body:', event.body); // string — parse with JSON.parse()
9 console.log('Authorizer context:', event.requestContext.authorizer);
10
11 return {
12 statusCode: 200,
13 headers: {
14 'Content-Type': 'application/json',
15 'Access-Control-Allow-Origin': '*', // CORS
16 },
17 body: JSON.stringify({ message: 'Success', id: event.pathParameters?.id }),
18 };
19};2. Lambda Custom (Non-Proxy) Integration
API Gateway uses VTL (Velocity Template Language) mapping templates to transform the request before Lambda and transform the response before the client. Useful when you need to reshape payloads without changing Lambda code.
1{
2 "userId": "$input.params('userId')",
3 "action": "$input.json('$.action')",
4 "stage": "$stageVariables.env"
5}3. AWS Service Integration
Directly invoke AWS services without a Lambda intermediary. Common pattern: API Gateway → SQS queue (for decoupling).
| Setting | Value |
|---|---|
| Integration type | AWS Service |
| Service | SQS |
| Action | SendMessage |
| Request mapping template | Action=SendMessage&MessageBody=$input.body |
4. HTTP Integration
Proxy requests to any public HTTP endpoint. With HTTP Proxy integration, API Gateway passes the request through unchanged. With HTTP Custom, you can transform with VTL.
5. Mock Integration
API Gateway returns a response directly — no backend called. Useful for CORS preflight responses and prototyping.
1{
2 "statusCode": 200
3}Stages and Deployments
Changes to an API only take effect after you deploy to a stage. A stage is a named snapshot of your API (e.g., dev, staging, prod).
1# Deploy to prod stage
2aws apigateway create-deployment \
3 --rest-api-id abc123 \
4 --stage-name prod \
5 --description "v2.1 — add /orders endpoint"Stage Variables
Stage variables are key-value pairs attached to a stage — like environment variables for API Gateway. They let a single API definition point to different backends per stage.
1# Set a stage variable
2aws apigateway update-stage \
3 --rest-api-id abc123 \
4 --stage-name prod \
5 --patch-operations op=replace,path=/variables/lambdaAlias,value=prodReference stage variables in integrations:
- Lambda ARN:
arn:aws:lambda:us-east-1:123:function:MyFunc:${stageVariables.lambdaAlias} - HTTP endpoint:
https://${stageVariables.apiHost}/v1/orders
Canary Deployments
Route a percentage of traffic to a new deployment before full rollout — built into API Gateway stages.
1aws apigateway update-stage \
2 --rest-api-id abc123 \
3 --stage-name prod \
4 --patch-operations \
5 op=replace,path=/canarySettings/percentTraffic,value=10Throttling
API Gateway enforces two levels of throttling to protect backends:
| Level | Default limit | Scope |
|---|---|---|
| Account-level burst | 10,000 req/sec | All APIs in the region |
| Account-level steady state | 5,000 req/sec | All APIs in the region |
| Per-method throttling | Configurable | Individual routes (REST API only) |
| Usage plan throttling | Configurable | Per API key |
When throttled, the client receives HTTP 429 Too Many Requests.
Usage Plans & API Keys
Control who can access your API and at what rate.
1# Create an API key
2aws apigateway create-api-key --name "mobile-app-key" --enabled
3
4# Create a usage plan with throttling and quota
5aws apigateway create-usage-plan \
6 --name "mobile-plan" \
7 --throttle burstLimit=500,rateLimit=100 \
8 --quota limit=10000,period=DAY
9
10# Associate key with plan
11aws apigateway create-usage-plan-key \
12 --usage-plan-id xyz \
13 --key-id abc \
14 --key-type API_KEYClients send the API key in the x-api-key header.
Authorization
IAM Authorization
Requests are signed with AWS Signature Version 4 (SigV4). Best for service-to-service communication within AWS. The caller must have an IAM policy that allows execute-api:Invoke.
1{
2 "Effect": "Allow",
3 "Action": "execute-api:Invoke",
4 "Resource": "arn:aws:execute-api:us-east-1:123:abc123/prod/GET/orders"
5}Cognito Authorizer
API Gateway validates JWT tokens issued by a Cognito User Pool. No custom code needed.
Lambda Authorizer
A Lambda function receives the request and returns an IAM policy. Supports two modes:
| Mode | Input to Lambda | Use case |
|---|---|---|
| Token-based | Authorization header value | Bearer tokens, JWT, OAuth |
| Request-based | Full request context (headers, query, stage vars) | Custom header combinations |
1// Token-based Lambda authorizer
2exports.handler = async (event) => {
3 const token = event.authorizationToken; // e.g. "Bearer eyJhbGci..."
4
5 try {
6 const decoded = verifyToken(token); // your verification logic
7
8 return {
9 principalId: decoded.sub,
10 policyDocument: {
11 Version: '2012-10-17',
12 Statement: [{
13 Action: 'execute-api:Invoke',
14 Effect: 'Allow',
15 Resource: event.methodArn,
16 }],
17 },
18 context: {
19 userId: decoded.sub,
20 tier: decoded.tier,
21 // These become event.requestContext.authorizer.userId in Lambda
22 },
23 };
24 } catch {
25 throw new Error('Unauthorized'); // Returns 401
26 }
27};Authorizer cache: Responses are cached by the token value. TTL configurable from 0–3,600s (default 300s). Set TTL to 0 to disable caching.
Response Caching
REST API only. Cache API responses to reduce backend load and latency.
| Setting | Value |
|---|---|
| Scope | Per stage |
| TTL range | 0 – 3,600 seconds |
| Default TTL | 300 seconds (5 minutes) |
| Cache size | 0.5 GB – 237 GB |
| Cache invalidation | Cache-Control: max-age=0 header (caller must have IAM permission) |
| Per-method override | Individual methods can override stage cache settings |
1aws apigateway update-stage \
2 --rest-api-id abc123 \
3 --stage-name prod \
4 --patch-operations \
5 op=replace,path=/cacheClusterEnabled,value=true \
6 op=replace,path=/cacheClusterSize,value=0.5 \
7 op=replace,path=/*/*/caching/ttlInSeconds,value=300CORS Configuration
For browser-based clients, CORS preflight requests (OPTIONS) must return the right headers.
1// Lambda proxy must include CORS headers in EVERY response
2return {
3 statusCode: 200,
4 headers: {
5 'Access-Control-Allow-Origin': 'https://app.example.com',
6 'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
7 'Access-Control-Allow-Headers': 'Content-Type,Authorization,x-api-key',
8 },
9 body: JSON.stringify(data),
10};With REST API, you can enable CORS in the console — it automatically creates the OPTIONS method with a Mock integration returning the correct headers.
WebSocket APIs
WebSocket APIs maintain persistent, bidirectional connections between client and server. Ideal for real-time apps: chat, live dashboards, multiplayer games.
Built-in Routes
| Route | Trigger |
|---|---|
$connect | Client establishes connection |
$disconnect | Client or server closes connection |
$default | No matching custom route |
Custom (e.g. sendMessage) | Matched by routeSelectionExpression |
Pushing Messages Back to Clients
Lambda uses the Management API to push data to a connected client:
1import { ApiGatewayManagementApiClient, PostToConnectionCommand } from '@aws-sdk/client-apigatewaymanagementapi';
2
3const client = new ApiGatewayManagementApiClient({
4 endpoint: `https://${event.requestContext.domainName}/${event.requestContext.stage}`,
5});
6
7await client.send(new PostToConnectionCommand({
8 ConnectionId: connectionId,
9 Data: JSON.stringify({ type: 'update', payload: data }),
10}));Request Validation
REST API can validate incoming requests before they reach your backend — saving Lambda invocations on bad input.
1# Create a request validator
2aws apigateway create-request-validator \
3 --rest-api-id abc123 \
4 --name "validate-body-params" \
5 --validate-request-body \
6 --validate-request-parameters
7
8# Define a JSON Schema model for the request body
9aws apigateway create-model \
10 --rest-api-id abc123 \
11 --name CreateOrderRequest \
12 --content-type application/json \
13 --schema '{
14 "$schema": "http://json-schema.org/draft-04/schema#",
15 "type": "object",
16 "required": ["customerId", "amount"],
17 "properties": {
18 "customerId": { "type": "string" },
19 "amount": { "type": "number", "minimum": 0.01 }
20 }
21 }'When validation fails, API Gateway returns HTTP 400 Bad Request immediately — no backend invocation.
DVA-C02 Quick Reference
| Topic | Key Fact |
|---|---|
| Default burst limit | 10,000 req/sec per region |
| Default steady-state limit | 5,000 req/sec per region |
| Throttle response code | HTTP 429 |
| Cache TTL range | 0 – 3,600 seconds (default 300s) |
| Cache invalidation header | Cache-Control: max-age=0 |
| Cheapest API type | HTTP API (~71% cheaper than REST) |
| Supports usage plans & API keys | REST API only |
| Supports VTL mapping templates | REST API only |
| Supports AWS service integrations | REST API only |
| Supports response caching | REST API only |
| Native JWT / OIDC auth | HTTP API (REST API needs Lambda authorizer) |
| Service-to-service auth | IAM + SigV4 |
| Lambda authorizer cache | Per token value, TTL 0–3,600s |
| Must do after API change | Deploy to a stage |
| Stage variables used for | Pointing same API to different Lambda aliases per stage |
| WebSocket push to client | POST to Management API callback URL |
| WebSocket built-in routes | $connect, $disconnect, $default |
| Validation failure response | HTTP 400 (before backend is called) |
Practice Questions7
Q1. A developer needs to expose a Lambda function via API Gateway with the lowest possible latency and cost. The API does not need API keys, usage plans, or per-method throttling. Which API type should the developer choose?
Select one answer before revealing.
Q2. An API Gateway REST API is experiencing occasional 429 Too Many Requests errors under burst traffic. The developer wants to protect the backend Lambda function while still serving as many requests as possible. Which API Gateway feature should the developer configure?
Select one answer before revealing.
Q3. A developer configures an API Gateway Lambda proxy integration. The Lambda function returns the following object: `{ "statusCode": 200, "body": "Hello" }`. After deployment, all API calls return a 502 Bad Gateway error. What is the most likely cause?
Select one answer before revealing.
Q4. A developer needs to validate incoming API requests before they reach the Lambda backend. The validation should check that required query string parameters and headers are present. Which API Gateway feature accomplishes this with no Lambda code changes?
Select one answer before revealing.
Q5. A mobile app calls API Gateway with valid JWT tokens issued by Amazon Cognito User Pools. The developer wants API Gateway to verify these tokens automatically without writing a custom Lambda authorizer. Which authorizer type should be configured?
Select one answer before revealing.
Q6. An API Gateway stage has caching enabled with a 5-minute TTL. A developer needs certain requests (those with a specific header) to always bypass the cache. What should the developer configure?
Select one answer before revealing.
Q7. A developer needs API Gateway to transform an incoming XML request body into JSON before forwarding it to a Lambda function. The Lambda function only understands JSON. Which API Gateway feature should be used?
Select one answer before revealing.