TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท apis ยท serverless ยท web

Amazon API Gateway

A managed front door for APIs. API Gateway matches each request to a route, checks who is calling, applies throttling, and forwards the request to an integration such as a Lambda function or an HTTP backend.

16 min7 animations

๐Ÿ“š Builds on๐Ÿ“ฎ HTTP๐ŸŽŸ๏ธ JWT๐Ÿฌ Rate limiting

๐Ÿ–จ๏ธ Cheat sheet

The service counter

Picture a huge department store. Shoppers don't wander the back rooms looking for the right person. They all go to the service counter by the front entrance.

Behind the counter hangs a department guide. Each line on it says who handles which kind of request: "new orders: the Toy department", "shoe questions: the Shoe shop next door". Each line is called a route. The counter reads what the shopper wants, finds the matching line, sends the request through, and hands the answer back across the counter.

The departments never deal with shoppers directly. They don't need their own till, queue or store detective: the counter does all of that for them. And if a shopper asks for something that isn't in the guide, the counter says no straight away, without bothering anyone in the back.

A managed front door

Amazon API Gateway is a fully managed service for publishing APIs. Clients call one public endpoint, such as https://abc123.execute-api.eu-west-1.amazonaws.com/prod, and API Gateway forwards each request to a backend. You don't run or scale the servers that terminate TLS, parse requests or enforce limits.

TermMeaning
RouteA method and path, such as POST /orders or GET /users/{id}, that API Gateway matches requests against
IntegrationThe backend a route forwards to: a Lambda function, an HTTP endpoint, another AWS service, or a mock
AuthorizerWhat checks the caller before the integration runs: IAM, a JWT or Cognito authorizer, or a Lambda authorizer
StageA named, callable snapshot of the API, such as dev or prod
DeploymentThe snapshot of routes and settings that a stage serves

There are three API types: REST APIs (the original, with the most features), HTTP APIs (newer, simpler and cheaper) and WebSocket APIs (long-lived two-way connections). Both REST and HTTP APIs support a greedy path such as ANY /{proxy+}; HTTP APIs also have a $default route that catches everything else.

A request that matches no route never reaches a backend. An HTTP API answers 404 Not Found. A REST API answers 403 with the message Missing Authentication Token, which confuses many people the first time they see it.

Routes and integrations5 steps
๐Ÿ™‹Shopper Ana๐Ÿ’Service counter๐ŸงธToy department๐Ÿ‘ŸShoe shop next door
Press play and watch it happen!

Passing the slip through

The simplest way to work is for the counter to pass the shopper's request slip to the department exactly as written, with every detail on it. The department reads it and fills in the whole reply slip itself: how it went, and what to hand back. This is called a proxy setup.

But the counter can't keep a shopper standing there forever. It waits about half a minute for a department to answer. If no answer comes, the counter tells the shopper "sorry, no reply in time", even if the department is still busy. So a big job, like a long alteration at the tailor's, shouldn't keep the shopper waiting: take the order, give them a collection ticket, and let the tailor finish in their own time.

Proxy integrations and the timeout

With a Lambda proxy integration, API Gateway passes the whole HTTP request (method, path, path and query parameters, headers, body, plus request context such as the authorizer's claims) to the function as a JSON event. In a REST API, the function must return statusCode, headers and body, and a malformed return value gives the client 502 Bad Gateway. With HTTP API payload format 2.0, API Gateway is more lenient: valid JSON without a statusCode is sent as a 200 with that JSON as the body, so always set statusCode on errors. An HTTP proxy integration does the same with any HTTP endpoint. REST APIs also offer non-proxy integrations, where mapping templates reshape the request and response.

The flow of one request is: match a route, run the authorizer, check throttling, call the integration, return the response. API Gateway accepts payloads up to 10 MB for REST and HTTP APIs, but a synchronous Lambda call caps the request and the response at 6 MB each, so 6 MB is the real limit for a Lambda integration.

Integration timeout. API Gateway waits at most 30 seconds for an HTTP API integration, a hard limit, and 29 seconds by default for REST and WebSocket APIs. For Regional and private REST APIs you can request a higher maximum, possibly at the cost of a lower account throttle quota. When the limit passes, the client gets 504 Gateway Timeout, but the Lambda function keeps running until it finishes or hits its own timeout. For long jobs, return 202 Accepted quickly and do the work asynchronously (a queue, Step Functions), letting the client poll or receive a callback.

In Java, a handler for a REST API proxy integration uses the event types from aws-lambda-java-events:

1import java.util.Map;2 3public class CreateOrderHandler4        implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {5 6    private final OrderService orders = new OrderService();7 8    @Override9    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) {10        // Format 1.0 keeps the client's header casing, so "X-Customer-Id" would not match this lookup11        String customer = request.getHeaders().get("x-customer-id");12        String body = request.getBody();             // the raw JSON the client sent13        String orderId = orders.create(customer, body);14 15        return new APIGatewayProxyResponseEvent()16                .withStatusCode(201)17                .withHeaders(Map.of("Content-Type", "application/json"))18                .withBody("{\"orderId\":\"" + orderId + "\"}");19    }20}

HTTP APIs usually use payload format 2.0 (the console default; with CloudFormation, the CLI or an SDK you must set payloadFormatVersion), which uses APIGatewayV2HTTPEvent and APIGatewayV2HTTPResponse. To run a whole Spring Boot app behind one ANY /{proxy+} route, aws-serverless-java-container translates the event into a servlet request, so ordinary @RestController methods handle it:

1public class StreamLambdaHandler implements RequestStreamHandler {2    private static final SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;3 4    static {5        try {6            handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class);7        } catch (ContainerInitializationException e) {8            throw new RuntimeException("Could not start Spring Boot", e);9        }10    }11 12    @Override13    public void handleRequest(InputStream in, OutputStream out, Context context) throws IOException {14        handler.proxyStream(in, out, context);15    }16}

This handler is for REST APIs (payload format 1.0). For an HTTP API on format 2.0, use SpringBootLambdaContainerHandler.getHttpApiV2ProxyHandler(Application.class) with HttpApiV2ProxyRequest.

Proxy integration and the timeout5 steps
๐Ÿ™‹Shopper Ana๐Ÿ’Service counter๐ŸงธToy department๐ŸงตTailor
Press play and watch it happen!

Checking cards

Not everyone may ask for everything, so the counter checks cards before passing anything through. There are three ways it can do that.

Store staff carry a staff card, and the counter checks it against the store's own list of who may do what. Shoppers can get a stamped loyalty card from a trusted card desk. The counter can check the stamp by itself, right there, without phoning anyone. And for the trickiest cases, the counter phones the store manager, who knows the house rules and says "go ahead" or "turn them away".

Phoning the manager every time would be slow, so the counter remembers the manager's answer for a few minutes. But if the manager changes their mind, the counter won't know until its note runs out.

Authorization

API Gateway can reject a request before the integration ever runs:

  • IAM authorization: the caller signs the request with AWS Signature Version 4, and API Gateway checks the caller's IAM policies for execute-api:Invoke on that route. Best for service-to-service calls inside AWS.
  • JWT authorizers (HTTP APIs): API Gateway validates a JWT from any OpenID Connect or OAuth 2.0 issuer, such as a Cognito user pool, checking its signature, issuer, audience and expiry, and optionally its scopes. A missing or invalid token gets 401; a valid token without the required scopes gets 403. REST APIs offer a Cognito user pool authorizer for the same job.
  • Lambda authorizers: API Gateway calls your function with the token or request details. In REST APIs it returns an IAM policy that allows or denies; HTTP APIs can also use a simple isAuthorized response. Use it for custom rules, such as a token from a legacy system or a lookup in your own database.

Lambda authorizer results can be cached by token or identity source for a configurable TTL (5 minutes by default for REST APIs, up to an hour). Caching saves latency and invocations, but a revoked user keeps access until the cached result expires, and a policy cached for one route can be reused for others, so cache with care.

Authorizers5 steps
๐Ÿ™‹Shopper Ana๐ŸคทStranger Ben๐Ÿ’ณCard desk๐Ÿ’Service counter๐Ÿง‘โ€๐Ÿ’ผStore manager๐ŸงธToy department
Press play and watch it happen!

The rope line and the trade card

If a crowd rushes the counter at once, the floor would jam and the departments would drown in slips. So there's a rope line in front of the counter: it lets through a steady number of people each second, and a short rush now and then. Anyone over the limit is told "too busy, try again in a moment".

Shops that buy from the store often get a trade card with their own allowance: so many requests a second, and so many a day. If one shop uses up its allowance, it's turned away, but other shops still get served. Only the store-wide rope line is shared by everyone. The trade card only says who is asking, though. It's plain card and easy to copy, so it's for counting requests, not for keeping anyone out.

Throttling, usage plans and API keys

API Gateway throttles with a token bucket: a steady rate plus a burst. Requests over the limit get 429 Too Many Requests, and well-behaved clients retry with backoff. Limits apply at several levels, and the tightest one wins:

  • Account level: by default 10,000 requests per second per Region with a burst of 5,000, shared by all of the account's APIs in that Region. The rate can be raised on request.
  • Stage and route (or method) level: limits you set to protect a fragile backend.
  • Per client (REST APIs only): a usage plan sets a rate, a burst and a quota (requests per day, week or month) for each API key associated with it. The client sends the key in the x-api-key header.

One noisy client hitting its usage plan limit doesn't affect other keys, but everyone shares the account limit. AWS warns not to use API keys for authentication or authorization: they are shared secrets that are easy to leak and can't express permissions. Pair them with a real authorizer. Throttling is also best-effort, so it protects capacity but isn't an exact billing meter.

Throttling and usage plans5 steps
๐ŸชSam's shop๐ŸฌLee's shop๐Ÿ’Counter and rope line๐Ÿท๏ธPrices department
Press play and watch it happen!

Counters and printed guides

The store has more than one counter. There's a quiet trial counter in the staff training room, where staff try things out, and the busy main counter on the shop floor that real shoppers use.

Changing the department guide takes care. Scribbling on the planner's draft changes nothing at the counters; shoppers only see a new guide once a copy is printed and hung up. Staff write the new version and print it. Each printed copy is called a deployment, and every copy is kept on file, numbered. Hang a copy at the trial counter first, and if it works there, hang the same copy at the main counter. If a new guide turns out to be wrong, just hang the previous copy back up.

Stages and deployments

A deployment is an immutable snapshot of the API's routes, integrations and settings. A stage is a named reference to one deployment with its own URL path (/dev, /prod), throttling, logging and stage variables (for example, which Lambda alias or backend URL to call).

In a REST API, editing a resource or method changes nothing for callers until you create a deployment and point a stage at it. That makes promotion and rollback cheap: deploy to dev, test, point prod at the same deployment, and to roll back, point prod at the previous one. HTTP APIs can auto-deploy a stage on every change, which suits development but takes that control away in production. An HTTP API's $default stage is served from the root of the API's URL, with no stage name in the path.

Many teams use separate stacks or accounts per environment instead of stages in one API, so that a mistake in dev can't touch prod; stages still matter there for versioned snapshots. A custom domain name with API mappings (base path mappings in REST APIs) hides the generated execute-api URL from clients.

Stages point at deployments5 steps
Printed guides on file0123๐Ÿ‘ฉโ€๐Ÿ’ผStore planner๐ŸงชTrial counter๐Ÿ’Main counter
Press play and watch it happen!

The chaperone's question

Some requests come from a web page belonging to another shop, and they don't come alone. They come with a chaperone, the shopper's own web browser. Before it lets the page ask for anything risky, the chaperone asks the counter, "do you serve requests sent by this shop's page?". Only if the counter says yes does the real request go through. And when the answer comes back, the chaperone checks it carries a "welcome" note before letting the page read it.

The chaperone does this to protect the shopper: a page from another shop shouldn't be able to act at this store, or read its answers, unless the store agrees.

The counter can answer the chaperone's question itself, and the simple counter (more on it below) adds the "welcome" note to every reply for you. But at a full-service counter that just passes slips straight through, the department has to remember to add the note to every reply, or the chaperone throws the answer away.

CORS

When a web page on https://shop.example calls the API on another origin, the browser enforces CORS. Many requests (a JSON body, an Authorization header, DELETE) trigger an OPTIONS preflight, and every response must carry Access-Control-Allow-Origin that matches the page.

  • HTTP APIs have a CORS configuration (allowed origins, methods, headers, max age). API Gateway then answers preflight requests itself, even without an OPTIONS route, and adds the headers to responses, ignoring CORS headers returned by the backend. If the $default route has an authorizer, preflights fail (browsers send them without credentials), so add an unauthorized OPTIONS /{proxy+} route.
  • REST APIs: enabling CORS in the console adds an OPTIONS method with a mock integration. With a proxy integration, though, API Gateway doesn't touch the response, so your Lambda function or backend must return the Access-Control-Allow-* headers itself, including on errors.

A forgotten header is the classic symptom: the request succeeds on the server, the logs look fine, and the browser still reports a CORS error. In REST APIs, configure gateway responses (such as 4XX and 5XX) with the headers too, so the browser can read error messages produced by API Gateway itself.

CORS at the gateway4 steps
๐Ÿ›๏ธOther shop's web page๐Ÿง‘โ€๐ŸซChaperone๐Ÿ’Service counter๐Ÿ›’Basket department
Press play and watch it happen!

Three kinds of counter, and the phone line

A store can have one of three kinds of counter. The full-service counter does everything: trade cards with allowances, a shelf of ready answers for common questions, and checks that each slip is filled in properly. The simple counter has fewer extras, but it's quicker and cheaper. Both can check staff cards and loyalty cards, and both can phone the manager. The simple counter also adds the chaperone's "welcome" note for you.

The third kind is a phone line counter. Instead of one slip and one reply, the shopper keeps a phone line open. Each line gets a number, and the counter tells the department which line each message came from. Later, the department can speak to any line through the counter, without being asked first. A line that stays silent too long is hung up, and no call lasts more than two hours. The counter holds the lines, so departments don't have to keep phones of their own.

REST, HTTP and WebSocket APIs

REST APIHTTP API
AuthorizersIAM, Cognito user pools, LambdaIAM, JWT (any OIDC issuer, including Cognito), Lambda
API keys and usage plansYesNo
Response cachingYesNo
Request validation, mapping templatesYesNo (parameter mapping only)
AWS WAF attached directlyYesNo
Endpoint typesEdge-optimized, Regional, privateRegional
CORSConfigured per method, or by your backend for proxy integrationsBuilt in
Auto-deployNoYes
Price and latencyHigherLower

HTTP APIs were designed with fewer features so they could cost less. A common rule: start with an HTTP API, and choose a REST API when you need one of the features only it has.

WebSocket APIs keep a connection open so either side can send at any time. API Gateway holds the connection, and your backend stays stateless. Messages are routed by a route selection expression, usually $request.body.action, plus three special routes: $connect, $disconnect and $default. Each connection has a connectionId; the backend stores it (for example, in DynamoDB) and pushes messages by calling the @connections management API (POST to the connection's callback URL). Connections close after 10 minutes idle or 2 hours in total, so clients send heartbeats and reconnect.

WebSocket APIs5 steps
๐Ÿ™‹Shopper Ana๐Ÿ™‹โ€โ™‚๏ธShopper Benโ˜Ž๏ธPhone line counter๐ŸŽGift list department
Press play and watch it happen!

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • โšกServerless APIThe smallest useful backend: API Gateway, Lambda and DynamoDB.guided design

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about Amazon API Gateway, told the same way as the story.
  1. The tailor takes two minutes to finish an alteration. What does Ana hear at the counter?
  2. Sam's shop keeps its trade card secret. Is that enough to keep strangers out?
  3. Copy 3 of the department guide sends slips at the main counter to the wrong departments. What's the quickest fix?
  4. At the full-service counter, which passes slips straight through, the Basket department's reply comes back without a welcome note. What does the chaperone do?
Answer every question to check.Passing marks Amazon API Gateway as done.
Got the hang of Amazon API Gateway? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โ˜๏ธ AWS from zeroStep 11 of 12

โ† Previous on the path๐Ÿ—ž๏ธ Amazon CloudFrontNext on the path โ†’๐Ÿ“ AWS CloudFormation and CDK