Skip to content
intermediate Phase 9 · Serverless Architecture

API Gateway

Create REST and HTTP APIs with API Gateway, configure authorizers, request/response mappings, throttling, and custom domains.

1h
0 problems
Topic Progress 0%

REST APIs vs HTTP APIs

API Gateway offers two API types: REST APIs and HTTP APIs. Understanding when to use each saves cost and complexity.

HTTP APIs are the modern, lightweight option—up to 70% cheaper than REST APIs. They support JWT authorizers (Cognito, custom), OAuth 2.0, simple CORS configuration, and automatic deployment. Use HTTP APIs for most new projects.

# HTTP API with JWT authorizer
openapi: "3.0.1"
info:
  title: "my-api"
paths:
  /users:
    get:
      x-amazon-apigateway-integration:
        type: aws_proxy
        uri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/get-users/invocations
        httpMethod: POST

REST APIs provide the full feature set: request/response transformations, API key usage plans, WAF integration, private endpoints, and complex authorizer logic. Use REST APIs when you need fine-grained control over the request/response pipeline.

Deploy APIs using stages. A stage is a snapshot of your API (like dev, staging, prod) with its own configuration:

aws apigateway create-deployment \
  --rest-api-id abc123 \
  --stage-name prod \
  --stage-description "Production"

Stage variables route to different backend implementations. A dev stage variable might point to a Lambda function alias $LATEST while prod points to PROD. This enables environment-specific routing without separate API definitions.

API Gateway Authorizers

Authorizers control who can access your API. API Gateway supports multiple authorizer types.

Cognito User Pools: Fully managed authentication. Users sign in via hosted UI or SDK, receive a JWT token, and pass it in the Authorization header. API Gateway validates the token automatically:

x-amazon-apigateway-authorizer:
  type: COGNITO_USER_POOLS
  providerARNs:
    - arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_abc123

Lambda Authorizers: Custom logic for authentication/authorization. A Lambda function receives the request, validates tokens (JWT, API key, custom), and returns an IAM policy. Use this for custom auth flows, multi-tenant authorization, or integrating with external identity providers.

exports.handler = async (event) => {
  const token = event.authorizationToken;
  const decoded = jwt.verify(token, process.env.JWT_SECRET);
  
  return {
    principalId: decoded.sub,
    policyDocument: {
      Version: '2012-10-17',
      Statement: [{
        Action: 'execute-api:Invoke',
        Effect: 'Allow',
        Resource: event.methodArn
      }]
    },
    context: {
      userId: decoded.sub,
      role: decoded.role
    }
  };
};

IAM Authorization: Uses AWS Signature Version 4. The client signs requests with IAM credentials. Useful for service-to-service communication within AWS.

API Keys: Simple key-based access. Generate keys, create usage plans with throttling limits, and associate keys with stages. Clients pass the key in the x-api-key header.

Request/Response Transformations and Throttling

API Gateway can transform requests and responses before they reach your backend, decoupling your API contract from backend implementation.

Request transformation: Add headers, modify query parameters, or reshape the body:

{
  "requestParameters": {
    "integration.request.header.Content-Type": "'application/json'",
    "integration.request.querystring.userId": "method.request.path.id"
  },
  "requestTemplates": {
    "application/json": "{'user_id': '$input.path('$.userId')', 'action': 'getProfile'}"
  }
}

Response mapping: Reshape backend responses for the client:

{
  "responseTemplates": {
    "application/json": "{'data': $input.json('$'), 'status': 'success'}"
  },
  "responseParameters": {
    "method.response.header.Cache-Control": "'max-age=300'"
  }
}

Throttling prevents abuse and protects backends. Configure at multiple levels:

  • Account level: Default throttle for all APIs (default: 10,000 requests/second)
  • Stage level: Per-stage limits
  • Method level: Per-endpoint limits
  • Usage plans: Per-client limits with API keys
x-amazon-apigateway-stage-settings:
  throttlingRateLimit: 1000
  throttlingBurstLimit: 500

Caching: REST APIs support stage-level caching. Enable caching to store responses and reduce backend calls. Cached responses are served directly from API Gateway with configurable TTL.

aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations \
    op=replace,path=/cacheClusterEnabled,value=true \
    op=replace,path=/cacheClusterSize,value=0.5

Custom Domains and Deployment

Custom domains make your API accessible at api.yourcompany.com instead of the default API Gateway URL.

Set up a custom domain:

# Create the custom domain
aws apigateway create-domain-name \
  --domain-name api.yourcompany.com \
  --regional-certificate-arn arn:aws:acm:us-east-1:123456789012:certificate/abc123 \
  --endpoint-configuration types=REGIONAL

# Map a base path to a stage
aws apigateway create-base-path-mapping \
  --domain-name api.yourcompany.com \
  --rest-api-id abc123 \
  --stage prod \
  --base-path v1

For subdomain routing (api.dev, api.prod), create multiple base path mappings. For multi-region APIs, create domain names in each region and use Route 53 weighted or latency-based routing.

Binary media types enable file uploads. Enable binary support on the API and set Content-Type headers appropriately:

aws apigateway update-rest-api \
  --rest-api-id abc123 \
  --patch-operations \
    op=replace,path=/binaryMediaTypes,value= multipart/form-data

Canary deployments gradually shift traffic to a new version. Configure canary settings on a stage to send a percentage of traffic to a new deployment:

x-amazon-apigateway-canary-settings:
  percentTraffic: 10
  useStageCache: false

Monitor the canary via CloudWatch metrics. If errors increase, route 100% back to the current version. This enables safe rollouts with real production traffic.

Quiz

1. When should you choose HTTP APIs over REST APIs?

Question 1 options

2. What does a Lambda authorizer return to API Gateway?

Question 2 options

3. What is the purpose of API Gateway caching?

Question 3 options

Flashcards

Question

What is the difference between REST APIs and HTTP APIs in API Gateway?

Answer

HTTP APIs are cheaper and simpler, supporting JWT authorizers and OAuth 2.0. REST APIs offer the full feature set: transforms, WAF, private endpoints, and complex authorizers.

Question

What are API Gateway stages?

Answer

Snapshots of your API (e.g., dev, staging, prod) with independent configuration, stage variables, throttling, and caching settings.

Question

What are the throttling levels in API Gateway?

Answer

Account-wide (global default), stage-level, method-level, and per-client via usage plans with API keys.

Question

What is canary deployment in API Gateway?

Answer

Gradually shifting a percentage of traffic to a new deployment version, enabling safe rollouts with real production traffic monitoring.

Revision Notes

Key Takeaways

  • 1. HTTP APIs are the default choice for most new projects—cheaper and simpler than REST APIs
  • 2. REST APIs provide the full feature set: transforms, WAF, private endpoints, complex authorizers
  • 3. Lambda authorizers enable custom auth logic; Cognito authorizers provide managed JWT validation
  • 4. Throttling at account, stage, method, and usage plan levels prevents abuse
  • 5. Custom domains and canary deployments enable professional API rollout strategies

Interview Tips

  • Explain when you'd choose REST APIs over HTTP APIs with specific requirements
  • Describe the flow of a Lambda authorizer including caching and policy generation
  • Explain how you'd set up multi-region API routing with custom domains
  • Discuss API Gateway throttling strategies for a multi-tenant SaaS application

Cheat Sheet

HTTP APIs: cheaper, JWT auth, simple CORS. REST APIs: transforms, WAF, private endpoints, complex auth. Authorizers: Cognito (managed JWT), Lambda (custom logic), IAM (SigV4), API Keys (simple). Throttling: account → stage → method → usage plan. Custom domains: create-domain-name → create-base-path-mapping. Canary: gradual traffic shift with monitoring.