Skip to main content

Amazon API Gateway

Core concept: API Gateway is the fully managed "front door" for APIs โ€” routes HTTP requests to Lambda, EC2, HTTP backends, or AWS services directly.


API Typesโ€‹

TypeUse CaseFeaturesCost
REST APIFull-featured traditional RESTCaching, WAF, usage plans, request/response transformHigher
HTTP APILow-latency, simple RESTJWT authorizer, auto-deploy, OIDC~70% cheaper
WebSocket APIReal-time bidirectional (chat, dashboards)Connection managementPer message
Exam: REST vs HTTP API
  • Need usage plans / API keys โ†’ REST API
  • Need response caching โ†’ REST API
  • Need resource policies โ†’ REST API
  • Simplest serverless API with Cognito JWT auth โ†’ HTTP API

Integration Typesโ€‹

TypeDescription
Lambda ProxyAPI Gateway passes raw event to Lambda, Lambda returns full response
Lambda Non-ProxyYou map request/response via Velocity templates (VTL)
HTTP ProxyPass through to HTTP backend
AWS ServiceDirectly invoke SQS, DynamoDB, S3, etc. (no Lambda needed!)
MockReturn static response without backend

Direct SQS Integration (No Lambda!)โ€‹

# CloudFormation: API Gateway โ†’ SQS directly
Integration:
Type: AWS
IntegrationHttpMethod: POST
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:sqs:path/${AWS::AccountId}/${Queue.QueueName}"
Credentials: !GetAtt ApiGatewayRole.Arn
RequestParameters:
integration.request.header.Content-Type: "'application/x-www-form-urlencoded'"
RequestTemplates:
application/json: "Action=SendMessage&MessageBody=$input.body"

Authorizersโ€‹

Cognito User Pool Authorizerโ€‹

  • Validates the JWT Access token from Cognito
  • Built-in, no Lambda needed
  • Attach to REST or HTTP APIs

Lambda Authorizer (Custom Authorizer)โ€‹

  • Your Lambda validates the token (JWT, OAuth, API key, etc.)
  • Returns an IAM policy document
  • Token type: receives a header token (Bearer)
  • Request type: receives full request context (headers, query params, etc.)
// Lambda authorizer response
public AuthPolicy handleRequest(TokenAuthorizerContext input, Context context) {
String token = input.getAuthorizationToken();
// Validate token...
return AuthPolicy.builder()
.principalId("user-123")
.policyDocument(PolicyDocument.builder()
.statements(List.of(Statement.builder()
.effect(Effect.ALLOW)
.actions(List.of("execute-api:Invoke"))
.resources(List.of("arn:aws:execute-api:*:*:*"))
.build()))
.build())
.build();
}
Authorizer caching

Lambda Authorizer results are cached (TTL: 0โ€“3600s). Set TTL = 0 to disable caching for dynamic permissions.


Deployment Stagesโ€‹

API โ†’ [dev stage]   โ†’ https://xyz.execute-api.us-east-1.amazonaws.com/dev
โ†’ [prod stage] โ†’ https://xyz.execute-api.us-east-1.amazonaws.com/prod
  • Each stage is a snapshot of the API deployment
  • Stage variables = environment-specific config (like Lambda alias or DB URL)

Canary Deploymentsโ€‹

prod stage โ†’ 95% โ†’ stable Lambda version
โ†’ 5% โ†’ canary Lambda version (testing)

Caching (REST API only)โ€‹

  • Cache API responses for 0.5 โ€“ 3600 seconds
  • Reduces Lambda invocations
  • Cache key = method + path + query params + headers (configurable)
  • Can be invalidated with Cache-Control: max-age=0 header (if allowed)

Throttlingโ€‹

LevelDefault
Account10,000 RPS, burst 5,000
Stage/MethodConfigurable per stage
Usage PlanPer-API key throttle + quota

๐Ÿงช Practice Questionsโ€‹

Q1. A developer builds a serverless API with Lambda. They need to throttle API calls per customer and charge customers differently based on API usage tier. What feature should they use?

A) Stage Variables
B) Lambda Reserved Concurrency
C) API Gateway Usage Plans with API Keys
D) Cognito User Pools

โœ… Answer & Explanation

C โ€” Usage Plans define throttle rates and quotas, assigned to API Keys. Each customer gets their own API key mapped to a usage plan.


Q2. An API needs to return cached responses for most users, but allow admins to bypass the cache. How should this be implemented?

A) Use a Lambda Authorizer to skip the cache
B) Configure different stages (cached vs non-cached)
C) Allow clients to send Cache-Control: max-age=0 to invalidate
D) Disable caching for admin routes

โœ… Answer & Explanation

C โ€” API Gateway supports Cache-Control: max-age=0 header to invalidate the cache per request. Grant execute-api:InvalidateCache permission to authorized users.


Q3. What is the maximum integration timeout for API Gateway calling a Lambda function?

A) 3 seconds
B) 10 seconds
C) 29 seconds
D) 15 minutes

โœ… Answer & Explanation

C โ€” API Gateway has a maximum integration timeout of 29 seconds for all backends. If your Lambda takes longer, API Gateway will return a 504 Gateway Timeout. Lambda itself can run for 15 minutes, but API Gateway won't wait.


๐Ÿ”— Resourcesโ€‹