Ace Cloud Interviews
Home/AWS Tutorial/API Gateway
🌐

AWS Networking & CDN

API Gateway

Create, deploy, and manage REST, HTTP, and WebSocket APIs at any scale

Amazon API Gateway is a fully managed service for creating, deploying, and managing REST, HTTP, and WebSocket APIs at any scale. It handles authentication, throttling, caching, request/response transformation, and monitoring - acting as the front door for backend services like Lambda, EC2, ECS, or any HTTP endpoint.

API Types: REST vs HTTP vs WebSocket

API Gateway offers three distinct API types with different feature sets and price points. Choosing the right one significantly impacts cost and capability.

FeatureREST APIHTTP APIWebSocket API
Cost (per million calls)$3.50$1.00$1.00 + $0.25/million connection-minutes
LatencyHigher~60% lowerLow for persistent connections
AWS WAF supportYesNo (use CloudFront + WAF instead)No
Request/response transformationYes (mapping templates)NoNo
Usage plans and API keysYesNoNo
Private integrations (VPC Link)Yes (NLB only)Yes (NLB or ALB)No
CachingYes (dedicated cache)NoNo
JWT authorizersCustom only (Lambda)Native JWT supportNo
Best forComplex APIs needing transformation and rate plansSimple proxy APIs, Lambda backends, cost-sensitiveReal-time bidirectional apps
💡

For new projects integrating with Lambda, HTTP APIs are almost always the better choice - they cost 70% less, have lower latency, and support JWT authorizers natively. Use REST APIs only when you need mapping templates, WAF integration at the API layer, or usage plans.

Integration Types and Request Flow

API Gateway sits between clients and backends. The integration type determines how it forwards requests and handles responses.

Integration TypeDescriptionUse Case
AWS_PROXY (Lambda Proxy)Full request forwarded to Lambda as event object; Lambda must format full HTTP responseStandard Lambda integration - most common
AWS (Lambda Custom)Request/response can be transformed via mapping templatesWhen you need to shape input/output without changing Lambda code
HTTP_PROXYPasses full request to HTTP endpoint unchangedSimple proxy to any HTTP backend
HTTP (Custom)Transform request/response with mapping templates before forwardingTransform for legacy backends
MockReturns a response without calling a backendTesting; returning static responses for health checks
VPC LinkRoute to private VPC resources via NLB/ALBBackend services in private subnets without internet exposure

With Lambda Proxy integration, the entire HTTP request is passed as a structured event object. The Lambda function must return a response in a specific format including statusCode, headers, and body (as a string).

bash
// Lambda Proxy response format
exports.handler = async (event) => {
  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    },
    body: JSON.stringify({ message: 'Hello' })
  }
}

Authentication and Throttling

API Gateway provides multiple authentication mechanisms and built-in rate limiting to protect backends.

Auth MethodHow It WorksBest For
IAM authRequest signed with SigV4; IAM policy controls accessService-to-service; AWS internal calls
Cognito User Pool authorizerValidates Cognito JWT in Authorization headerConsumer apps with Cognito-managed users
Lambda authorizer (token)Lambda validates bearer token and returns IAM policyCustom JWT, OAuth, or API key logic
Lambda authorizer (request)Lambda evaluates headers, query strings, contextComplex auth logic using multiple request attributes
API Keysx-api-key header; combined with usage plansThrottling per customer; not a security mechanism alone

Throttling operates at two levels: account-level defaults (10,000 RPS burst, 5,000 RPS steady) and per-stage/method overrides. Usage plans layer on top to set limits per API key.

⚠️

API Keys are not a security mechanism - they do not encrypt traffic or authenticate identity. Always combine API Keys with at least one of: IAM auth, Cognito, or a Lambda authorizer. API Keys are for rate limiting and metering, not for authentication.

Stages, Deployments, and Canary Releases

REST APIs require explicit deployments to stages (dev, staging, prod). HTTP APIs auto-deploy by default. Stages are independently configurable with variables, throttling, and logging.

FeaturePurposeKey Detail
StageIndependent deployment target with its own URLURL: https://id.execute-api.region.amazonaws.com/{stage}/
Stage VariablesEnvironment-specific config (Lambda alias, backend URL)Reference as ${stageVariables.variableName} in config
Canary ReleaseRoute a percentage of traffic to a new deploymentSet canary % in stage settings; promote or rollback
DeploymentSnapshot of API configuration applied to a stageREST API: must manually deploy after config changes
Custom DomainMap your domain to API Gateway endpointRequires ACM cert; use Base Path Mapping per stage
bash
# Deploy a REST API to prod stage
aws apigateway create-deployment \
  --rest-api-id abc123 \
  --stage-name prod \
  --description "v2.1.0 release"

# Enable canary with 10% of traffic to new deployment
aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations \
  op=replace,path=/canarySettings/percentTraffic,value=10

Pricing and Caching

ComponentREST APIHTTP API
First 333M calls/month$3.50/million$1.00/million
333M - 667M calls/month$2.80/million$1.00/million
Caching (0.5 GB)$0.020/hrNot available
Caching (6.1 GB)$0.200/hrNot available
Data transfer out$0.09/GB (first 10 TB)$0.09/GB (first 10 TB)
Connection minutes (WebSocket)N/AN/A
💡

API Gateway caching reduces calls to your Lambda or backend. Cache TTL is 0-3600 seconds (default 300). Clients can bust the cache by passing Cache-Control: max-age=0 if you allow it. Cache is per stage and adds significant cost - evaluate whether CloudFront caching is more cost-effective for your traffic patterns.

🎯

Interview Focus Points

  • 1What is the difference between REST API and HTTP API in API Gateway? When would you choose each?
  • 2How does Lambda Proxy integration differ from Lambda Custom integration?
  • 3Explain the different authorizer types in API Gateway and when you'd use each.
  • 4How would you implement a canary deployment for an API Gateway-backed service?
  • 5How does throttling work in API Gateway at the account level vs stage level vs usage plan level?
  • 6Why are API Keys not considered a security mechanism? What should you use instead?
  • 7How would you expose a private ALB or ECS service through API Gateway without making it public?
  • 8What is the maximum payload size in API Gateway and how do you handle larger payloads?
  • 9How do you handle CORS in API Gateway? What does the OPTIONS method do?