AWS API Gateway
medium 28 minAmazon API Gateway is a managed front door for HTTP and WebSocket APIs.
Video lesson · Chapter 1 of 5
A product lookup through a REST API
AWS API Gateway in 90 seconds
1:30Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Amazon API Gateway is a service in which you describe an API, its paths, methods, checks and backends, and AWS runs the gateway that answers. You get a web address; there are no machines to size or patch.
It comes in three kinds. A REST API has the most features. An HTTP API has fewer and is cheaper. A WebSocket API keeps connections open and turns messages into calls to your backend.
The gateway is the front of your system, not its logic. What sits behind it is called an integration: a Lambda function, an HTTP server, a private service in your network, or another AWS service called directly.
Why it exists
Every public API needs the same things: TLS, checking who calls, limits per customer, logs, versions and a way to route a path to a program. Writing them into every service is repeated work, and the result is uneven.
Running a gateway yourself means capacity planning and patching. A managed one charges for requests instead, which is comfortable for small or uneven traffic. In return you accept its limits on size, time and control.
A short history
July 2015
Amazon API Gateway launches, with REST APIs.
December 2018
WebSocket APIs are added.
December 2019
HTTP APIs appear as a preview, announced as up to 71% cheaper than REST APIs.
June 2024
The integration timeout of Regional and private REST APIs can be raised above 29 seconds on request.
Words to know
- Resource and method
- A URL path and an HTTP verb on it, in a REST API. HTTP APIs call the pair a route.
- Integration
- What the gateway calls for a method.
- Deployment
- A fixed snapshot of a REST API's configuration.
- Stage
- A name such as prod that points to a deployment and has its own settings.
- Authorizer
- The check that decides who may call.
- Usage plan
- A rate, a burst and a quota for the API keys that belong to it.
- VPC link
- A private connection from the gateway into your network.
- Mapping template
- A script in the Velocity Template Language (VTL) that rewrites a request or response.
- Token bucket
- A limit where tokens refill at a rate and a full bucket allows a burst.
How it works
Step through the idea, or press Play.
Arrive. TLS ends, the stage and route are found
Understand it
Start here
The garden toll booth
Imagine a botanical garden with three glasshouses and one booth at the gate. Nobody reaches a plant without passing the booth.
The booth grows no plants. It checks, counts and points the way.
The idea
What it does for a system
One door, three kinds of backend
Managed
Capacity, zones and patches are AWS's work. The service agreement names 99.95% monthly uptime per region.
Caller checks
IAM signatures, JWT, Cognito, Lambda authorizers, mutual TLS, WAF in front of REST APIs.
API management
Stages, canary releases, API keys, usage plans, custom domains, developer portals.
Less backend work
Bad requests are refused early and GET answers can be cached.
Pay per request
No minimum fee. Good for small and uneven traffic; compare at steady high traffic.
AWS inside
Lambda, DynamoDB, SQS, SNS, S3 and Step Functions without a server between.
The general pattern, aggregation and a gateway per client type belong to API gateway. Signed tokens are in API authentication. Here we look at the product.
Types
REST, HTTP or WebSocket API
What each type has
| REST API | HTTP API | WebSocket API | |
|---|---|---|---|
| Endpoints | Edge-optimized, Regional, private | Regional | Regional |
| Callers | IAM, Cognito, JWT, Lambda, resource policy | IAM, JWT (also Cognito), Lambda | IAM or Lambda on connect |
| API keys and usage plans | Yes | No | Yes |
| AWS WAF | Yes | No (put CloudFront in front) | No |
| Response cache | Yes | No | No |
| Validation, body mapping | Yes | Parameters only | Mapping, validation |
| Canary, response streaming | Yes | No | No |
| Deployments | By hand | Automatic if you want | By hand or automatic |
Which type?
Model
Resources, methods, integrations
One small API
| Path | Method | Integration |
|---|---|---|
/users | GET | Lambda, proxy |
/orders | POST | SQS, directly |
/orders/{id} | GET | Private service through a VPC link |
/health | GET | Mock: a fixed answer |
Integration kinds
| Kind | What happens | Notes |
|---|---|---|
| Lambda proxy | The whole request becomes an event; the function returns status, headers and body | The usual choice |
| Lambda or HTTP, custom | You map request and response with templates | REST APIs |
| HTTP proxy | Passed to a URL as it is | Public servers or through a VPC link |
| AWS service | The gateway calls the service with a role | No function to run or pay for |
| Mock | Answer made in the gateway | REST APIs: tests, CORS |
Asynchronous work. For a slow task, let the gateway write to a queue or start a workflow and answer 202 at once. The client asks later, or gets a webhook. See queues.
Request
The life of one request
A GET with an authorizer and a cache miss
- 1
Arrive
HTTPS to a Regional endpoint, or through AWS's own CloudFront distribution for an edge-optimized one.
- 2
Route
TLS ends. Path and method choose the configuration; stage variables hold values such as a function alias.
- 3
Check the caller
Signature, JWT or authorizer. A failure is 401 or 403.
- 4
Count
Usage plan, method and account throttles. Too many is 429.
- 5
Validate and transform
Required parameters and a JSON schema (REST). A bad request is 400. Templates may rewrite the body.
- 6
Cache
REST APIs can answer GET requests from the stage's cache.
- 7
Integrate
One backend call with a timeout. Too slow is 504.
- 8
Answer
Response mapping, access log, metrics, reply.
Reading the errors
| Code | Usual cause | Look at |
|---|---|---|
| 400 | Validation failed | Model, required parameters |
| 401, 403 | Caller refused, key missing, WAF, resource policy | Authorizer logs, policy |
| 403 "Missing Authentication Token" | Often a path or method that is not deployed (REST) | URL, stage, deployment |
| 404 | No such route (HTTP API) | Route key |
| 413 | Payload too large | Upload to storage instead |
| 429 | Throttle or quota | Usage plan, account limit |
| 502 | The integration's answer could not be used | Lambda errors, response shape |
| 504 | The integration took too long | Backend time; make it asynchronous |
Callers
Authorizers
| Kind | Best for | Watch |
|---|---|---|
| IAM (Signature Version 4) | Other AWS workloads | Callers need AWS credentials |
| JWT or Cognito | Users of an identity provider | Signing keys are cached up to two hours, so plan key rotation |
| Lambda authorizer | Own rules: opaque tokens, a database look-up | Extra call and cold starts; cache the result |
| API key | Counting a customer's calls | Not a login. Never the only check |
A Lambda authorizer with its cache
Limits
Throttling and quotas
Four layers, checked from narrow to wide
A token bucket with the default account values
AWS calls throttles and quotas best effort: targets, not guaranteed ceilings. Its advice is not to use them to control costs or block access. Use WAF to block, budgets to watch money, and concurrency limits at the backend to protect it. Methods are compared in rate limiter algorithms.
# A plan for one partner: 50 a second, bursts of 100, 10,000 a monthaws apigateway create-usage-plan --name BasicPlan \ --throttle burstLimit=100,rateLimit=50 \ --quota limit=10000,period=MONTH \ --api-stages apiId=abc123,stage=prodaws apigateway create-api-key --name ClientA --enabledaws apigateway create-usage-plan-key \ --usage-plan-id plan123 --key-id key456 --key-type API_KEYShape
Validation, transformation and cache
Validation (REST): required parameters plus a JSON schema model. A malformed order is refused before a function runs. Transformation: templates in VTL reshape bodies and headers. They are powerful and easy to get wrong, so keep them short and test them; a template that fails gives a 5xx or an odd body.
#set($inputRoot = $input.path('$')){ "userId": "$util.escapeJavaScript($input.params('id'))", "requestId": "$context.requestId", "sourceIp": "$context.identity.sourceIp", "contentType": "$util.escapeJavaScript($input.params().header.get('Content-Type'))", "body": $input.json('$')}The stage cache (REST only)
| Fact | Value |
|---|---|
| Lifetime | 300 s by default, 0 to 3,600 s |
| Methods | GET by default; others only if you override them |
| Largest item | 1,048,576 bytes |
| Key | Path, plus the parameters and headers you mark as cache keys |
| Cost | By the size you reserve, used or not |
| Promise | Best effort: hits are not guaranteed |
Release
Stages, deployments and canaries
Editing a REST API changes a draft. A deployment is a snapshot, and a stage points to one. Forgetting to deploy is the classic "my change does nothing". HTTP APIs can deploy automatically.
A canary release on one stage
aws apigateway create-deployment --rest-api-id abc123 \ --stage-name prod --description "add GET /users"curl -i "https://abc123.execute-api.us-east-1.amazonaws.com/prod/users" \ -H "Authorization: Bearer $TOKEN"Custom domains replace the generated address. Certificates come from ACM: in us-east-1 for edge-optimized endpoints, in the API's own region for Regional ones. Path mappings send /v1 and /v2 to different APIs or stages; see API versioning.
Network
Endpoints, VPC links and regions
Endpoint types
| Type | Path | Use |
|---|---|---|
| Regional | Straight to the region | Default; clients nearby, or your own CloudFront in front |
| Edge-optimized (REST) | Through AWS-managed CloudFront locations | Clients far apart. It shortens connections; it is not a cache |
| Private (REST) | Interface endpoint in your VPC | Internal APIs |
A VPC link lets the gateway call services that have no public address. HTTP APIs can target an ALB, an NLB or Cloud Map. REST APIs now support ALB and NLB through VPC links V2; older REST links reach an NLB only. A V2 link with no traffic for 60 days becomes inactive, and waking it takes minutes.
Two regions behind one name
Use Regional endpoints with the same custom domain name in both regions, a health check that tests the whole path, and one API definition in code so that they stay alike. With DynamoDB global tables, plan for conflicting writes.
Numbers
Limits that shape a design
Default quotas, November 2026
| Limit | REST API | HTTP API | WebSocket API |
|---|---|---|---|
| Payload | 10 MB | 10 MB | 128 KB message, 32 KB frame |
| Integration timeout | 29 s; raise on request if Regional or private | 30 s, fixed | 29 s |
| Rate per account and region | 10,000 a second, bucket 5,000 | Shared with the others | Shared with the others |
| Connections | - | - | 2 hours at most, 10 minutes idle |
| Routes or resources | 300 | 300 | 300 |
| Stages | 10 | 10 | 10 |
Streaming. A REST API with a proxy integration can stream a response for up to 15 minutes, beyond 10 MB, with the part above 10 MB limited to 2 MB a second. Caching and VTL then do not work. Uploads go to storage with a presigned URL; see Amazon S3 and file upload APIs.
Steady traffic in requests a month
Run it
Operations
Metrics
Count, 4XXError, 5XXError, Latency and IntegrationLatency. The difference of the last two is the gateway's own share.
Access logs
Switch them on per stage with request ID, route, status and integration error.
Tracing
X-Ray for REST APIs. Pass the request ID on to your services.
Configuration as code
OpenAPI, SAM, CDK or Terraform, and a deployment per release.
Retries. A 504 does not mean that nothing happened: the function may still finish. Clients should retry with backoff and an idempotency key.
Decide
When to choose it, and when not
Choose it when
- You need auth, throttling and analytics without servers
- Backends are Lambda functions
- Each customer needs a rate and a quota
- You must reshape requests without touching the backend
- A mobile or web app needs its own backend (BFF)
- AWS services should be reachable as an API
- You need WebSockets without managing connections
Look elsewhere when
- Every millisecond counts between internal services: gRPC or an ALB
- Payloads are above 10 MB
- Calls run longer than the timeout: queue, Step Functions
- You only need to spread load: ALB or NLB
- Traffic is very high and steady, and cost decides
- The protocol is not HTTP or WebSocket
- You need your own plugins in the proxy: Kong, Envoy
Neighbours
| Product | Alike | Different | Choose it for |
|---|---|---|---|
| Application Load Balancer | HTTP, path routing, WebSocket, Lambda targets | Hourly and capacity price, gRPC, no usage plans; signs users in through Cognito or OIDC | High steady traffic |
| Kong Gateway | Auth, limits, several backends | Self-hosted or their cloud, own plugins, any cloud | Control, several clouds |
| Apigee | Managed API platform | Monetization and deep analytics, Google Cloud | API programmes of large companies |
| AWS AppSync | Managed, serverless | GraphQL and subscriptions | GraphQL, live data |
Strengths
- Nothing to run
- Many API features in one place
- Direct use of Lambda and AWS services
- IAM, JWT, WAF, mutual TLS
- Logs, metrics and traces
Costs
- Fixed size and time limits
- An extra hop on every call: measure it
- Price per call at high traffic
- No code of your own inside the proxy
- Cold starts of an authorizer add to the first call
Summary
The whole topic in one minute.
API Gateway gives an API its front door: addresses, TLS, caller checks, throttling, validation, transformation, caching and logs, then one call to the integration. REST APIs have the full set; HTTP APIs the smaller, cheaper one; WebSocket APIs keep connections.
Design around its numbers: 10 MB, about 30 seconds, 10,000 requests a second per account and region by default. Send big files straight to storage, turn long work into jobs, treat throttles as targets rather than guarantees, and redeploy after a change.
- REST for features, HTTP for simple and cheap, WebSocket for push.
- Route, check, count, validate, cache, integrate, answer.
- 10 MB, about 30 seconds, 10,000 a second per account and region by default.
- Throttles are best effort; API keys are not authentication.
- REST changes need a deployment; cached policies must cover all methods.