Amazon API Gateway

Amazon API Gateway is a managed service for creating, publishing, and operating HTTP, REST, and WebSocket APIs at scale. It fronts backend services (Lambda, containers, EC2, public HTTP endpoints) with authentication, request validation, rate limiting, and caching — the standard AWS entry point for serverless and microservice APIs.


API Types:


Key Features:


Common Architectures:


API Gateway vs. Alternatives:


Service Limits & Quotas:


Pricing Model:


Code Example:

Creating an HTTP API with a Lambda integration via boto3:

import boto3

apigw = boto3.client("apigatewayv2", region_name="us-west-2")

# 1) Create the HTTP API
api = apigw.create_api(
    Name="orders-api",
    ProtocolType="HTTP",
    CorsConfiguration={
        "AllowOrigins": ["https://app.example.com"],
        "AllowMethods": ["GET", "POST"],
        "AllowHeaders": ["content-type", "authorization"],
    },
)
api_id = api["ApiId"]

# 2) Lambda integration (proxy)
integ = apigw.create_integration(
    ApiId=api_id,
    IntegrationType="AWS_PROXY",
    IntegrationUri=("arn:aws:lambda:us-west-2:123456789012:"
                    "function:orders-handler"),
    PayloadFormatVersion="2.0",
    IntegrationMethod="POST",
)

# 3) Routes
apigw.create_route(ApiId=api_id, RouteKey="GET /orders",
                   Target=f"integrations/{integ['IntegrationId']}")
apigw.create_route(ApiId=api_id, RouteKey="POST /orders",
                   Target=f"integrations/{integ['IntegrationId']}",
                   AuthorizationType="JWT",
                   AuthorizerId="abc123")

# 4) Auto-deploy stage
apigw.create_stage(ApiId=api_id, StageName="$default", AutoDeploy=True)

print(f"https://{api_id}.execute-api.us-west-2.amazonaws.com")

A simple Lambda authorizer (TOKEN type) for a REST API:

import jwt   # PyJWT

def lambda_handler(event, context):
    token = event["authorizationToken"].removeprefix("Bearer ")
    try:
        claims = jwt.decode(token, key=JWKS, algorithms=["RS256"],
                            audience="orders-api")
    except jwt.PyJWTError:
        raise Exception("Unauthorized")  # API GW maps to 401

    return {
        "principalId": claims["sub"],
        "policyDocument": {
            "Version": "2012-10-17",
            "Statement": [{
                "Action": "execute-api:Invoke",
                "Effect": "Allow",
                "Resource": event["methodArn"],
            }],
        },
        "context": {"tenant": claims.get("tenant_id", "")},
    }


Common Interview Questions:

HTTP API vs. REST API — which would you pick for a new project?

HTTP API by default — ~70% cheaper, lower latency, JWT authorizers built-in, auto-deploy, simpler config. Choose REST API only if you need its specific features: in-gateway response cache, request/response validation models, API keys + usage plans, AWS WAF (now also on HTTP), Edge-Optimized endpoints, or Private API endpoints.

How does API Gateway authentication work?

Four options: IAM (clients sign requests with SigV4 — for service-to-service), Cognito User Pools (token validation against a Cognito pool), JWT authorizers (HTTP APIs only — validate any compliant JWT against a JWKS URI), and Lambda authorizers (arbitrary code returns an IAM policy + context). Lambda authorizer results can be cached up to 1 hour to avoid invoking on every request.

How would you protect an API from abuse and DoS?

Stack: WAF rate-based rules (IP-level rate limiting), API Gateway throttling (per-stage, per-method, per-API-key), usage plans for tiered customers, CloudFront in front for edge absorption + WAF managed rules, Cognito for identity, and 4xx/5xx CloudWatch alarms. For aggressive attacks, AWS Shield Advanced provides DDoS response team and cost protection.

Why is the integration timeout 29 seconds and how do you work around it?

API Gateway is intended for synchronous request/response — 29 seconds is the hard cap on backend integration time. For longer work, switch to async: API Gateway returns 202 + a job ID immediately, the request is queued (SQS, EventBridge) for async Lambda or Step Functions processing, and the client polls a status endpoint or receives a webhook/WebSocket notification when complete.

What's the difference between Edge-Optimized, Regional, and Private endpoints?

Edge-Optimized REST APIs route through CloudFront for global latency reduction (good for geographically dispersed clients). Regional endpoints serve from a single region — better when clients are in that region or you want to put your own CloudFront in front. Private endpoints expose the API only inside your VPC via an interface endpoint — internal services only, no public exposure.

How do you do canary deployments on API Gateway?

REST APIs support canary releases natively: deploy a new version to a stage's canary, set a percentage of traffic (e.g., 10%) to the canary, monitor 4xx/5xx and latency CloudWatch metrics, then promote canary to base or roll back. HTTP APIs don't support canary directly — use stage variables, weighted DNS via Route 53, or shift via Lambda alias weights instead.