/API Gateway & REST APIs
Concept
Medium

API Gateway & REST APIs

10 min read·API GatewayRESTServerlessDVA-C02

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.

FeatureREST APIHTTP APIWebSocket API
LatencyMediumLowestN/A
PriceStandard~71% cheaperPer message + connection
Lambda integrationProxy + CustomProxy onlyProxy 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:

TypeDescriptionUse case
Edge-OptimizedRouted through CloudFront PoPs globallyPublic APIs with geographically distributed clients
RegionalDeployed in a single AWS regionSame-region clients, custom CloudFront setup
PrivateOnly accessible inside a VPC via interface VPC endpointInternal microservices, private backends

Request / Response Flow

Rendering diagram…

Every request passes through this pipeline:

  1. Method Request — validates incoming request (headers, query params, body schema)
  2. Integration Request — transforms the request before sending to the backend
  3. Backend — Lambda, HTTP endpoint, or AWS service
  4. Integration Response — transforms the backend response
  5. 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.

javascript
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.

json
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).

SettingValue
Integration typeAWS Service
ServiceSQS
ActionSendMessage
Request mapping templateAction=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.

json
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).

bash
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.

bash
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=prod

Reference stage variables in integrations:

  • Lambda ARN: arn:aws:lambda:us-east-1:123:function:MyFunc:${stageVariables.lambdaAlias}
  • HTTP endpoint: https://${stageVariables.apiHost}/v1/orders
Rendering diagram…

Canary Deployments

Route a percentage of traffic to a new deployment before full rollout — built into API Gateway stages.

bash
1aws apigateway update-stage \
2  --rest-api-id abc123 \
3  --stage-name prod \
4  --patch-operations \
5    op=replace,path=/canarySettings/percentTraffic,value=10

Throttling

API Gateway enforces two levels of throttling to protect backends:

LevelDefault limitScope
Account-level burst10,000 req/secAll APIs in the region
Account-level steady state5,000 req/secAll APIs in the region
Per-method throttlingConfigurableIndividual routes (REST API only)
Usage plan throttlingConfigurablePer 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.

bash
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_KEY

Clients 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.

json
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.

Rendering diagram…

Lambda Authorizer

A Lambda function receives the request and returns an IAM policy. Supports two modes:

ModeInput to LambdaUse case
Token-basedAuthorization header valueBearer tokens, JWT, OAuth
Request-basedFull request context (headers, query, stage vars)Custom header combinations
javascript
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.

SettingValue
ScopePer stage
TTL range0 – 3,600 seconds
Default TTL300 seconds (5 minutes)
Cache size0.5 GB – 237 GB
Cache invalidationCache-Control: max-age=0 header (caller must have IAM permission)
Per-method overrideIndividual methods can override stage cache settings
bash
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=300

CORS Configuration

For browser-based clients, CORS preflight requests (OPTIONS) must return the right headers.

javascript
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.

Rendering diagram…

Built-in Routes

RouteTrigger
$connectClient establishes connection
$disconnectClient or server closes connection
$defaultNo 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:

javascript
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.

bash
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

TopicKey Fact
Default burst limit10,000 req/sec per region
Default steady-state limit5,000 req/sec per region
Throttle response codeHTTP 429
Cache TTL range0 – 3,600 seconds (default 300s)
Cache invalidation headerCache-Control: max-age=0
Cheapest API typeHTTP API (~71% cheaper than REST)
Supports usage plans & API keysREST API only
Supports VTL mapping templatesREST API only
Supports AWS service integrationsREST API only
Supports response cachingREST API only
Native JWT / OIDC authHTTP API (REST API needs Lambda authorizer)
Service-to-service authIAM + SigV4
Lambda authorizer cachePer token value, TTL 0–3,600s
Must do after API changeDeploy to a stage
Stage variables used forPointing same API to different Lambda aliases per stage
WebSocket push to clientPOST to Management API callback URL
WebSocket built-in routes$connect, $disconnect, $default
Validation failure responseHTTP 400 (before backend is called)

Practice Questions7

easy

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.

medium

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.

medium

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.

medium

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.

easy

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.

hard

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.

medium

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.