TExcelTAD
Home › AWS Cloud › Amazon API Gateway

Amazon API Gateway

Amazon API Gateway is a managed "front door" for APIs. It receives HTTP or WebSocket requests, authenticates and throttles them, and forwards them to a backend: a Lambda function, an HTTP service, or another AWS service. Combined with Lambda and DynamoDB it gives you a complete serverless API with no servers at all.

API types

Type Best for Highlights
HTTP API Most new REST-style APIs Cheaper, faster, JWT authorizers, simple Lambda/HTTP integrations
REST API APIs that need advanced features API keys and usage plans, request validation, caching, WAF, private APIs
WebSocket API Real-time two-way apps (chat, live dashboards) Routes on message content, connection management

The pieces

  • Routes: method + path, like GET /orders/{id}.
  • Integrations: what handles a route (Lambda proxy, HTTP proxy, AWS service).
  • Authorizers: IAM, Amazon Cognito user pools / JWT, or a custom Lambda authorizer.
  • Stages: deployed versions such as dev and prod, each with its own URL and settings.
  • Throttling: a steady rate (requests per second) and a burst limit.
bash
aws apigatewayv2 create-api --name orders-api --protocol-type HTTP \
    --target arn:aws:lambda:eu-west-1:123456789012:function:orders
curl -s https://a1b2c3d4e5.execute-api.eu-west-1.amazonaws.com/orders/42

Sample output:

text
{"id": "42", "status": "shipped", "total": 59.9}

Model: routing to Lambda (proxy integration)

With a Lambda proxy integration, API Gateway passes the whole request to the function as an event and turns the function's return value into the HTTP response. This model matches routes with path parameters and builds such events:

python · try it yourself
import json
import re

ORDERS = {"42": {"id": "42", "status": "shipped", "total": 59.9}}

def get_order(event):
    order = ORDERS.get(event["pathParameters"]["id"])
    if order is None:
        return {"statusCode": 404, "body": json.dumps({"message": "Not Found"})}
    return {"statusCode": 200, "body": json.dumps(order)}

def list_orders(event):
    return {"statusCode": 200, "body": json.dumps(sorted(ORDERS))}

ROUTES = {"GET /orders/{id}": get_order, "GET /orders": list_orders}

def to_regex(path):
    return "^" + re.sub(r"\{(\w+)\}", r"(?P<\1>[^/]+)", path) + "
quot; def gateway(method, path): for route, handler in ROUTES.items(): r_method, r_path = route.split(" ", 1) m = re.match(to_regex(r_path), path) if r_method == method and m: event = {"routeKey": route, "rawPath": path, "pathParameters": m.groupdict()} resp = handler(event) return resp["statusCode"], resp["body"] return 404, json.dumps({"message": "Not Found"}) for method, path in [("GET", "/orders/42"), ("GET", "/orders/7"), ("GET", "/orders"), ("DELETE", "/orders/42")]: print(method, path, "->", *gateway(method, path))
GET /orders/42 -> 200 {"id": "42", "status": "shipped", "total": 59.9}
GET /orders/7 -> 404 {"message": "Not Found"}
GET /orders -> 200 ["42"]
DELETE /orders/42 -> 404 {"message": "Not Found"}

Note the two different 404s: /orders/7 reached the function, which found no order; DELETE /orders/42 matched no route, so API Gateway answered by itself without invoking anything.

Model: throttling with a token bucket

API Gateway's throttling is a token bucket: the bucket holds up to burst tokens and refills at rate tokens per second; each request takes one token, and requests without a token get HTTP 429 Too Many Requests.

python · try it yourself
def simulate(rate, burst, arrivals):
    tokens = float(burst)
    last_t = 0.0
    results = []
    for t in arrivals:
        tokens = min(burst, tokens + (t - last_t) * rate)
        last_t = t
        if tokens >= 1:
            tokens -= 1
            results.append("200")
        else:
            results.append("429")
    return results

# 12 requests in the first 0.55 s, then 3 more a second later
arrivals = [i * 0.05 for i in range(12)] + [1.6, 1.65, 1.7]
res = simulate(rate=5, burst=5, arrivals=arrivals)
print(" ".join(res))
print("accepted:", res.count("200"), " throttled:", res.count("429"))
200 200 200 200 200 200 429 429 200 429 429 429 200 200 200
accepted: 10  throttled: 5

The burst absorbs the first five requests at once; after that requests are accepted only as fast as tokens refill (5 per second). After a quiet second the bucket is full again. Clients should retry 429 responses with exponential backoff.

Model: an HTTP API bill

python · try it yourself
PRICE_PER_MILLION = {"HTTP API": 1.00, "REST API": 3.50}   # example prices, check the AWS pricing pages

for millions in (1, 30, 300):
    row = "  ".join(f"{t}: ${millions * p:8.2f}" for t, p in PRICE_PER_MILLION.items())
    print(f"{millions:>4} million requests/month  {row}")
   1 million requests/month  HTTP API: $    1.00  REST API: $    3.50
  30 million requests/month  HTTP API: $   30.00  REST API: $  105.00
 300 million requests/month  HTTP API: $  300.00  REST API: $ 1050.00

Pick the HTTP API unless you need a REST-API-only feature: for the same traffic it is several times cheaper.

Test yourself

Which API Gateway type is usually the cheapest choice for a simple JSON API backed by Lambda?

  1. REST API
  2. HTTP API
  3. WebSocket API
  4. Private REST API

What does a client receive when it exceeds the throttling limits?

  1. HTTP 500
  2. HTTP 404
  3. HTTP 429 Too Many Requests
  4. HTTP 301

In a Lambda proxy integration, how does the function receive path parameters like {id}?

  1. As environment variables
  2. In the event, under pathParameters
  3. Through stdin
  4. In a DynamoDB table