Prev Next

Cloud / Amazon API Gateway Interview questions

Last updated

1. What is Amazon API Gateway? 2. What are the types of APIs in Amazon API Gateway? 3. What are the endpoint types for REST APIs? 4. What is a stage in Amazon API Gateway? 5. What are resources and methods in a REST API? 6. What are the integration types supported by API Gateway? 7. What is Lambda proxy integration? 8. What is a mapping template in API Gateway? 9. What are API keys and usage plans? 10. What is a Lambda authorizer in API Gateway? 11. What is a Cognito user pool authorizer? 12. What are stage variables in API Gateway? 13. What is API caching in Amazon API Gateway? 14. What is a custom domain name in API Gateway? 15. What is throttling in Amazon API Gateway? 16. What is a mock integration in API Gateway? 17. What is a WebSocket API in Amazon API Gateway? 18. What is a private API in API Gateway? 19. What is a VPC link in Amazon API Gateway? 20. How do you enable CORS in Amazon API Gateway? 21. How do you monitor Amazon API Gateway? 22. What is request validation in API Gateway? 23. What is a canary release deployment in API Gateway? 24. Why must you redeploy a REST API after changing it? 25. What is the difference between a REST API and an HTTP API in API Gateway? 26. What is the difference between edge-optimized and Regional API endpoints? 27. What is the difference between proxy and non-proxy integration? 28. What is the difference between TOKEN and REQUEST Lambda authorizers? 29. When should you use IAM authorization on API Gateway? 30. Why aren't API keys enough to secure an API? 31. How does throttling work in Amazon API Gateway? 32. How do you invalidate the API Gateway cache? 33. How does a JWT authorizer work in an HTTP API? 34. What happens when a Lambda proxy function returns a malformed response? 35. Why do you get a 504 Gateway Timeout from API Gateway? 36. How do you troubleshoot 403 Forbidden errors in API Gateway? 37. How do you secure a private API with a resource policy? 38. How does AWS WAF integrate with API Gateway? 39. How do you enable mutual TLS on API Gateway? 40. How does route selection work in a WebSocket API? 41. How do you send messages to WebSocket clients from a backend? 42. How do you version an API in Amazon API Gateway? 43. How do you deploy API Gateway with infrastructure as code? 44. How do you handle binary payloads in API Gateway? 45. How do you integrate API Gateway directly with AWS services like SQS? 46. How can you optimize API Gateway cost and performance? 47. How can you build a multi-Region highly available API with API Gateway? 48. Explain the request lifecycle of a REST API call in API Gateway? 49. Why does Lambda authorizer caching sometimes cause 403 errors on other routes? 50. What are the important quotas and limits in Amazon API Gateway?

1. What is Amazon API Gateway?

Amazon API Gateway is a fully managed AWS service for creating, publishing, securing, and monitoring APIs at any scale. It sits in front of your backend (Lambda, EC2, containers, or any HTTP endpoint) and acts as the single entry point for clients.

It handles the plumbing you would otherwise build yourself: request routing, authorization, throttling, caching, request/response transformation, and metrics. There are no servers to manage, and you pay per request.

  • Supports REST, HTTP, and WebSocket APIs
  • Integrates natively with Lambda, IAM, Cognito, CloudWatch, and WAF
  • Scales automatically with traffic
Take quiz
Amazon API Gateway is best described as:
a relational database engine
a container orchestration service
a DNS-only routing service
a managed front door for creating and securing APIs
How is API Gateway billed?
Per EC2 instance hour it runs on
Mainly per API call (plus data transfer)
A flat monthly license fee
Per GB of stored API definitions

2. What are the types of APIs in Amazon API Gateway?

API Gateway offers three API types, and picking the right one early saves rework later.

Type Protocol Typical use
REST API HTTP request/response Full-featured APIs: usage plans, caching, WAF, request validation
HTTP API HTTP request/response Lower-cost, lower-latency proxying to Lambda or HTTP backends
WebSocket API Persistent two-way connection Chat, live dashboards, notifications

There was also the older concept of REST "private" and "regional" endpoints, but those are endpoint types, not API types.

Take quiz
Which API type keeps a persistent two-way connection?
HTTP API
REST API
Private API
WebSocket API
Which type is the cheaper, leaner option for simple Lambda proxying?
HTTP API
WebSocket API
REST API with caching
Edge-optimized REST API

3. What are the endpoint types for REST APIs?

A REST API can be deployed with one of three endpoint types, which decide where traffic enters AWS.

  1. Edge-optimized - requests go through a CloudFront-managed distribution and enter AWS at the nearest edge location. Good for geographically spread clients.
  2. Regional - requests hit the API directly in the Region. Best when clients are in the same Region, or when you want to attach your own CloudFront distribution.
  3. Private - reachable only from inside a VPC through an interface VPC endpoint.

Edge-optimized is the default when creating a REST API in the console, but Regional is often the better choice for modern setups.

Take quiz
Which endpoint type can only be reached from inside a VPC?
Regional
Private
Edge-optimized
Global
Edge-optimized endpoints route traffic through:
a Network Load Balancer
AWS Direct Connect
an S3 website endpoint
a CloudFront-managed distribution

4. What is a stage in Amazon API Gateway?

A stage is a named snapshot of your API that clients can actually call, such as dev, test, or prod. Creating an API alone exposes nothing; you deploy it to a stage.

Each stage has its own invoke URL, for example:

https://abc123.execute-api.us-east-1.amazonaws.com/prod

Settings like throttling, caching, logging, stage variables, and canary configuration are stored per stage, so you can run dev with debug logging and prod with caching on, using the same API definition.

Take quiz
A stage in API Gateway represents:
a database table for API data
a Lambda alias only
a billing tier
a named, callable deployment of the API
Where is the stage name placed in a default invoke URL?
Inside the Region name
As a query string parameter
As the account ID prefix
At the end of the path, like /prod

5. What are resources and methods in a REST API?

A resource is a path in your API's URL tree, such as /orders or /orders/{orderId}. Curly braces mark a path parameter.

A method is an HTTP verb attached to a resource, for example GET /orders or POST /orders. Each method has its own configuration: authorization, request validation, integration, and responses.

So resources define where a request goes, and methods define what action is allowed there. Special cases exist too, like ANY (all verbs) and greedy path variables such as {proxy+}.

Take quiz
In /orders/{orderId}, what does {orderId} represent?
A stage variable
A path parameter
An API key
A Lambda alias
Which item carries its own authorization and integration settings?
The AWS Region
The stage description
The CloudWatch log group
The method

6. What are the integration types supported by API Gateway?

An integration tells API Gateway how to forward a request to the backend. REST APIs support five types:

Type What it does
AWS_PROXY Lambda proxy; passes the whole request to Lambda
AWS Custom integration with Lambda or another AWS service; you map the request and response
HTTP_PROXY Passes the request straight to an HTTP endpoint
HTTP HTTP backend with your own mapping templates
MOCK API Gateway answers itself; no backend call

Take quiz
Which integration type returns a response without calling any backend?
AWS_PROXY
MOCK
HTTP_PROXY
AWS
Which type gives you full control via mapping templates for a Lambda backend?
AWS_PROXY
HTTP_PROXY
MOCK
AWS (non-proxy)

7. What is Lambda proxy integration?

In Lambda proxy integration, API Gateway passes the entire HTTP request (headers, query string, path parameters, body) to Lambda as a single event object. Your function then decides what to return.

The function must return JSON in a specific shape:

{
  "statusCode": 200,
  "headers": { "Content-Type": "application/json" },
  "body": "{\"ok\": true}",
  "isBase64Encoded": false
}

Note that body must be a string, not a JSON object. It is the simplest way to build a Lambda-backed API because no mapping templates are needed.

Take quiz
In Lambda proxy integration, the 'body' field in the response must be:
a raw JSON object
an XML document only
a string
a Base64 image
Who is responsible for shaping the HTTP response in proxy mode?
The Lambda function
The stage variable
The usage plan
The API key

8. What is a mapping template in API Gateway?

A mapping template transforms a request or response payload between the client's format and the backend's format. It is written in Velocity Template Language (VTL) and applies to non-proxy integrations.

For example, this template turns a query string into a JSON body for a backend:

{
  "userId": "$input.params('userId')",
  "source": "$context.identity.sourceIp"
}

Templates are selected by the request Content-Type. If none matches, the behavior depends on the passthrough setting: pass the body as-is, or reject with 415 Unsupported Media Type.

Take quiz
Mapping templates in API Gateway are written in:
Handlebars
Jinja2
GraphQL SDL
Velocity Template Language (VTL)
When does a mapping template NOT apply?
With MOCK integrations only
With AWS service integrations
With Lambda proxy or HTTP proxy integrations
With custom integrations

9. What are API keys and usage plans?

An API key is an alphanumeric string that identifies a client application. A usage plan defines what that client may do: throttle rate, burst, and a quota per day, week, or month.

You attach API stages to a usage plan, then associate keys with the plan. Requests must carry the key in the x-api-key header, and the method must have "API key required" enabled.

They work on REST APIs only; HTTP APIs do not support usage plans. Use them for metering and partner tiers, not as your main security control.

Take quiz
Which header carries the API key by default?
Authorization
x-amz-security-token
x-usage-plan
x-api-key
Usage plans are supported on:
HTTP APIs
REST APIs
WebSocket APIs only
Private HTTP APIs only

10. What is a Lambda authorizer in API Gateway?

A Lambda authorizer (formerly custom authorizer) is a Lambda function that API Gateway calls before invoking the backend to decide whether a request is allowed. You use it for custom auth logic such as validating a third-party token or checking a database.

The function returns an IAM policy document with Allow or Deny on the requested resource, plus a principalId and an optional context map that is passed to the backend.

Results can be cached for up to one hour, which cuts latency and Lambda invocations for repeat callers.

Take quiz
What does a Lambda authorizer return to API Gateway?
An HTML login form
A signed Cognito token
An IAM policy with Allow or Deny
A CloudFront cookie
Why enable authorizer caching?
To avoid re-running the function for repeat tokens
To encrypt the payload
To increase burst limits
To remove the need for IAM

11. What is a Cognito user pool authorizer?

A Cognito user pool authorizer lets API Gateway validate tokens issued by an Amazon Cognito user pool without any custom code. The client signs in with Cognito, receives a JWT, and sends it in the Authorization header.

API Gateway checks the token's signature and expiry. With an ID token, it can also require that the caller belongs to the pool; with an access token, you can require specific OAuth scopes on the method.

It is the quickest option when your users already live in Cognito. For other identity providers, use a Lambda authorizer or a JWT authorizer on an HTTP API.

Take quiz
A Cognito authorizer validates which kind of credential?
A JWT issued by the user pool
A SigV4 signature
An x-api-key header
A client TLS certificate
Method-level OAuth scopes can be enforced when the client sends:
an API key
a CloudFront signed URL
an access token
a stage variable

12. What are stage variables in API Gateway?

Stage variables are name-value pairs attached to a stage that act like environment variables for your API configuration. You reference them as ${stageVariables.name}.

A common use is pointing each stage at a different backend without changing the API definition:

Integration URI: https://${stageVariables.host}/orders
Lambda: arn:aws:lambda:...:function:orders:${stageVariables.alias}

Set host=dev.example.com on dev and host=api.example.com on prod. Do not store secrets in them, since they are not encrypted.

Take quiz
A stage variable is referenced with which syntax?
#{stage.name}
%stage_name%
$env.name
${stageVariables.name}
Which is a good use for stage variables?
Storing database passwords
Pointing dev and prod stages to different Lambda aliases
Encrypting request bodies
Raising account throttle limits

13. What is API caching in Amazon API Gateway?

API Gateway can cache endpoint responses for a stage so repeated identical requests are served from cache instead of hitting your backend. This lowers latency and backend load.

Key facts:

  • Available on REST APIs only, enabled per stage
  • Cache size ranges from 0.5 GB up to 237 GB
  • Default TTL is 300 seconds; the maximum is 3600, and 0 disables caching
  • Cache keys can include query strings, headers, or path parameters

You pay hourly for the cache capacity you provision, so it makes sense mainly for read-heavy, repeatable responses.

Take quiz
What is the default cache TTL for a REST API stage cache?
30 seconds
300 seconds
3600 seconds
24 hours
Built-in response caching is available for:
HTTP APIs
REST APIs
WebSocket APIs
All three API types equally

14. What is a custom domain name in API Gateway?

A custom domain name lets clients call your API at api.example.com instead of the generated execute-api URL. You attach an ACM certificate and create a DNS record (usually a Route 53 alias) pointing to the domain's target.

Then base path mappings (or API mappings for HTTP APIs) connect paths to specific APIs and stages, for example /v1 to the prod stage of one API and /v2 to another.

For an edge-optimized domain, the ACM certificate must be in us-east-1; for Regional domains, it must be in the same Region as the API.

Take quiz
Where must the ACM certificate live for an edge-optimized custom domain?
us-east-1
eu-west-1
The same Region as the Lambda function
Any Region
What maps a custom-domain path to an API stage?
A base path mapping
A stage variable
A usage plan key
A VTL template

15. What is throttling in Amazon API Gateway?

Throttling limits how many requests per second API Gateway will accept, protecting your backend from spikes. When a client exceeds the limit, API Gateway rejects the excess with HTTP 429 Too Many Requests.

Limits are applied at several levels:

  1. Account-level per Region (default 10,000 requests/second steady-state, 5,000 burst)
  2. Per-stage or per-method settings
  3. Per-client limits through usage plans

Clients should handle 429 with retries and exponential backoff.

Take quiz
Which status code does API Gateway return when a request is throttled?
401
429
502
413
How should clients react to throttling?
Retry with exponential backoff
Retry instantly in a tight loop
Switch to HTTP/1.0
Ignore the response

16. What is a mock integration in API Gateway?

A mock integration makes API Gateway generate the response itself, with no backend involved. You define the status code and body in the integration response mapping.

It is useful in three situations:

  • Front-end teams need a working API before the backend exists
  • Answering CORS preflight OPTIONS requests
  • Testing gateway behavior such as auth and throttling in isolation

The request mapping template must return {"statusCode": 200} so API Gateway knows which integration response to use.

Take quiz
Which task is a classic use of MOCK integration in REST APIs?
Streaming video
Running long batch jobs
Encrypting S3 objects
Answering CORS preflight OPTIONS requests
Who builds the response in a mock integration?
A Lambda function
The EC2 backend
API Gateway itself
CloudFront

17. What is a WebSocket API in Amazon API Gateway?

A WebSocket API keeps a persistent, two-way connection between client and server so either side can send messages at any time, without the client polling.

API Gateway manages connections and routes each incoming message to a backend (often Lambda) based on a route selection expression. Three special routes exist: $connect, $disconnect, and $default.

Typical use cases are chat apps, live scoreboards, collaborative editing, and push notifications. Connections idle out after 10 minutes and last at most 2 hours.

Take quiz
Which route is invoked when a client first opens a WebSocket connection?
$default
$open
$connect
$init
A WebSocket API is a good fit for:
one-off file downloads
static website hosting
nightly batch reports
live chat with server push

18. What is a private API in API Gateway?

A private API is a REST API that can only be invoked from within your VPC (or connected networks) through an interface VPC endpoint for execute-api. It has no public internet exposure.

To make it work you need three things: the private endpoint type, an interface VPC endpoint in the calling VPC, and a resource policy that allows traffic from that endpoint or VPC.

Typical use: internal microservice APIs, or backends for internal tools reached over VPN or Direct Connect.

Take quiz
Private APIs are invoked through:
an internet gateway only
an interface VPC endpoint
a public CloudFront distribution
an S3 gateway endpoint
Which policy controls who can call a private API?
A resource policy
An S3 bucket policy
A stage variable
A CloudTrail trail

A VPC link lets API Gateway reach resources inside a VPC, such as services behind a load balancer, without exposing them publicly.

For REST APIs, a VPC link traditionally targets a Network Load Balancer. For HTTP APIs, VPC links (v2) can target an Application Load Balancer, an NLB, or AWS Cloud Map service instances.

You then create an HTTP or HTTP_PROXY integration whose connection type is VPC_LINK. Traffic stays on the AWS network and your backend can live in private subnets.

20. How do you enable CORS in Amazon API Gateway?

CORS lets a browser on one origin call your API on another. In API Gateway the setup differs by type.

API type How CORS is configured
HTTP API Built-in CORS settings: allowed origins, methods, headers
REST API (non-proxy) Add an OPTIONS method with a mock integration and set Access-Control-* headers in the method and integration responses
REST API (proxy) Same OPTIONS setup, but your Lambda must also return the CORS headers on real responses

Forgetting the headers on error responses is a common bug; the browser then shows a CORS error instead of the real 4xx or 5xx.

Take quiz
With Lambda proxy on a REST API, who must return CORS headers on actual responses?
Only CloudFront
Only Route 53
Nobody, it is automatic
The Lambda function
Where are CORS settings a simple built-in option?
Private REST APIs only
HTTP APIs
Usage plans
Stage variables

21. How do you monitor Amazon API Gateway?

API Gateway reports to CloudWatch in three ways: metrics, access logs, and execution logs. You can also trace REST APIs with AWS X-Ray.

The metrics to watch first:

  • Count - total requests
  • 4XXError and 5XXError - client and server error counts
  • Latency - total time from request received to response sent
  • IntegrationLatency - time spent waiting on the backend
  • CacheHitCount / CacheMissCount - cache effectiveness

Comparing Latency with IntegrationLatency shows quickly whether slowness is in the gateway or your backend.

Take quiz
Which metric measures time spent waiting for the backend?
IntegrationLatency
Count
CacheHitCount
4XXError
Which service traces REST API requests end-to-end?
AWS Glue
Amazon Macie
AWS X-Ray
AWS Config

22. What is request validation in API Gateway?

Request validation lets API Gateway reject malformed requests before they reach your backend, saving Lambda invocations and backend load. It returns a 400 response when validation fails.

Two things can be checked on a REST API method:

  1. Required query strings, headers, and path parameters
  2. The request body against a model defined with JSON Schema
{
  "type": "object",
  "required": ["email"],
  "properties": { "email": { "type": "string" } }
}

It only checks structure and types, so business rules still belong in your code.

Take quiz
What does API Gateway use to describe the expected request body?
A CloudFormation output
A model in JSON Schema
An IAM policy
A Route 53 record
A failed request validation returns:
502 Bad Gateway
429 Too Many Requests
204 No Content
400 Bad Request

23. What is a canary release deployment in API Gateway?

A canary release sends a small percentage of a stage's traffic to a new deployment while the rest continues to hit the current one. It is available for REST APIs.

The flow is straightforward:

  1. Deploy the new version to the stage as a canary with, say, 10% traffic
  2. Watch metrics and logs (canary stats are reported separately)
  3. Promote the canary to 100%, or delete it to roll back

You can also override stage variables just for the canary, which is handy for pointing it at a new Lambda alias.

Take quiz
What happens when you promote a canary release?
It is deleted
It moves to another Region
It switches to an HTTP API
It becomes the stage's full deployment
A canary release primarily reduces the risk of:
exceeding the S3 storage quota
shipping a bad change to all users at once
losing DNS records
expired ACM certificates

24. Why must you redeploy a REST API after changing it?

In a REST API, edits to resources, methods, or integrations are saved to a working copy that is not live. Callers only see what has been captured in a deployment associated with a stage.

So after changing a route or integration, you must create a new deployment for the stage to pick it up. The console has a "Deploy API" action; in CLI it is create-deployment. Infrastructure-as-code tools often need a trigger (like a hash) to force this.

HTTP APIs are different: they support auto-deploy on a stage, so changes go live automatically.

Take quiz
Why doesn't a REST API edit take effect immediately?
API Gateway caches edits for 24 hours
Changes must be captured in a new deployment
Stages are read-only
Lambda must be restarted
Which API type supports auto-deploy on a stage?
REST API only
Private API only
None of them
HTTP API

25. What is the difference between a REST API and an HTTP API in API Gateway?

Both expose HTTP endpoints, but HTTP APIs are the newer, trimmed-down option built for lower cost and latency. REST APIs keep the deeper feature set.

Feature REST API HTTP API
Price Higher Up to ~70% cheaper
Usage plans / API keys Yes No
Response caching Yes No
AWS WAF Yes No
Request validation and mapping templates Yes No (parameter mapping only)
JWT authorizer Via Cognito or Lambda Built-in
CORS Manual setup Built-in setting

Choose HTTP API for straightforward Lambda or HTTP proxying, and REST API when you need caching, WAF, usage plans, or request transformation.

Take quiz
Which feature is available on REST APIs but NOT on HTTP APIs?
Lambda integration
Built-in response caching
Custom domain names
CloudWatch metrics
Why might a team pick an HTTP API?
Lower cost and latency for simple proxying
It supports usage plans
It integrates with WAF
It offers mapping templates

26. What is the difference between edge-optimized and Regional API endpoints?

The difference is how requests enter AWS before reaching your API.

Aspect Edge-optimized Regional
Entry path Nearest CloudFront edge, then AWS backbone Directly to the API's Region
Best for Globally distributed clients Clients in or near the same Region
CloudFront AWS-managed, hidden from you Optional: bring your own distribution
Custom domain cert ACM in us-east-1 ACM in the API's Region

Edge-optimized can cut connection setup time for far-away users, but Regional gives you more control, such as adding your own CloudFront rules or WAF at the edge.

Take quiz
Which endpoint type lets you attach your own CloudFront distribution?
Edge-optimized
Neither
Only Private
Regional
Which endpoint type suits globally spread clients by default?
Private
Regional with no CDN
Edge-optimized
WebSocket only

27. What is the difference between proxy and non-proxy integration?

With a proxy integration, API Gateway forwards the request as-is and returns whatever the backend sends. With a non-proxy (custom) integration, you configure how requests and responses are transformed.

Aspect Proxy Non-proxy
Mapping templates None VTL request and response mapping
Setup effort Minimal Higher: integration request/response config
Response format Backend must return the expected structure Gateway shapes the response for you
Typical use Most Lambda APIs Legacy backends, direct AWS service calls

Proxy is usually the default recommendation; use non-proxy when the backend cannot be changed.

Take quiz
In a non-proxy integration, who reshapes the payload?
CloudFront
The client browser
API Gateway using mapping templates
AWS Config
Which option needs the least gateway configuration?
Non-proxy with VTL
Proxy integration
Mock with custom responses
Direct SQS mapping

28. What is the difference between TOKEN and REQUEST Lambda authorizers?

Both are Lambda authorizers; they differ in what the function receives and what forms the cache key.

Aspect TOKEN REQUEST
Input A single bearer token from one header Headers, query strings, stage variables, context
Cache key The token value A combination of the identity sources you choose
Good for JWT or OAuth bearer tokens Multiple inputs, e.g. API key plus IP or a custom header

If your auth decision depends on more than one value, pick REQUEST. It is also required for WebSocket $connect authorizers.

Take quiz
Which authorizer type can use query strings and multiple headers as identity sources?
TOKEN
Neither
Cognito only
REQUEST
A TOKEN authorizer caches results by:
the source IP only
the stage name
the token value
the HTTP method

29. When should you use IAM authorization on API Gateway?

Use IAM authorization when callers are AWS identities: other AWS services, EC2 or Lambda roles, or internal applications with AWS credentials. Clients sign requests with Signature Version 4 (SigV4), and API Gateway checks the IAM policy attached to the caller.

The caller needs an identity policy allowing execute-api:Invoke on the API's ARN:

{
  "Effect": "Allow",
  "Action": "execute-api:Invoke",
  "Resource": "arn:aws:execute-api:us-east-1:123456789012:abc123/prod/GET/orders"
}

It fits service-to-service calls well. It is a poor fit for public browser users, who do not hold AWS credentials.

Take quiz
IAM authorization requests are signed with:
OAuth 1.0a
Signature Version 4 (SigV4)
A CloudFront key pair
Basic auth
Which IAM action must be allowed to invoke an API?
apigateway:GET
execute-api:Invoke
lambda:InvokeAsync
cloudfront:CreateInvalidation

30. Why aren't API keys enough to secure an API?

API keys identify a client for metering; they do not authenticate a user. A key is a static string that can be copied from an app, logged, or leaked, and anyone holding it can call the API.

AWS says as much in its guidance: don't rely on keys for authorization. They are meant to work with usage plans for throttling and quotas.

For real security, combine them with an actual authorizer: IAM, Cognito, JWT, or a Lambda authorizer. Then the key handles quota and the authorizer handles identity.

Take quiz
What is the main purpose of an API key in API Gateway?
Encrypting traffic end to end
Replacing IAM roles
Identifying clients for throttling and quotas
Issuing JWT tokens
What should you add for proper user authentication?
A longer API key
An authorizer such as Cognito, IAM, or Lambda
A larger cache
A bigger burst limit

31. How does throttling work in Amazon API Gateway?

API Gateway uses the token bucket algorithm. The bucket holds up to the burst number of tokens and refills at the rate (steady-state requests per second). Each request consumes a token; if the bucket is empty, the request gets a 429.

Limits are checked from most specific to least:

  1. Per-client limits in a usage plan
  2. Per-method limits on a stage
  3. Per-stage/API default limits
  4. The account-level Region limit

A method limit cannot exceed the account limit, so a noisy API in one stage can still starve others if you never set per-stage caps.

Take quiz
What algorithm does API Gateway use for throttling?
Leaky heap
Token bucket
Round robin
Two-phase commit
What happens when the bucket has no tokens left?
The request waits in a queue forever
The stage is deleted
The API key rotates
The request is rejected with 429

32. How do you invalidate the API Gateway cache?

You can flush the entire stage cache from the console, or with the CLI flush-stage-cache command. This immediately empties every cached entry for that stage.

Clients can also request a single fresh response by sending the header Cache-Control: max-age=0. By default this is allowed to anyone, so it is safest to require authorization (an IAM permission called execute-api:InvalidateCache) or turn off the option.

Otherwise, entries simply expire when the TTL runs out.

Take quiz
Which request header lets a client bypass the cache for one call?
X-Cache: skip
Accept: no-cache-please
Cache-Control: max-age=0
Authorization: none
What does flushing the stage cache do?
Deletes the API
Removes all cached entries for that stage
Rotates API keys
Resets account throttling

33. How does a JWT authorizer work in an HTTP API?

A JWT authorizer validates JSON Web Tokens issued by an OpenID Connect or OAuth 2.0 provider, such as Cognito, Auth0, or Okta, with no Lambda function.

You configure an issuer URL and one or more audiences. For each request, API Gateway does the following:

  1. Reads the token from the identity source (usually the Authorization header)
  2. Verifies the signature against the issuer's public keys
  3. Checks exp, iss, and aud or client_id
  4. Optionally enforces route-level scopes

Valid claims are passed to the backend in the request context.

Take quiz
A JWT authorizer needs which settings at minimum?
A Lambda ARN and a VPC ID
An S3 bucket and a KMS key
A stage variable and an API key
Issuer URL and audience
Which claim indicates when a token stops being valid?
iss
exp
aud
sub

34. What happens when a Lambda proxy function returns a malformed response?

API Gateway responds with 502 Bad Gateway and a message like "Malformed Lambda proxy response". The function ran, but its output did not match the structure API Gateway expects.

Frequent causes:

  • body returned as an object instead of a string
  • statusCode missing or not an integer
  • Returning plain text or nothing at all
  • An unhandled exception, which produces a different 502 message

Check the function's CloudWatch logs first, and use the console Test feature to see the exact response API Gateway received.

Take quiz
What status code signals a malformed Lambda proxy response?
404
301
502
204
Which body value is invalid in a proxy response?
A raw JSON object instead of a string
A JSON string
An empty string
A Base64 string with isBase64Encoded true

35. Why do you get a 504 Gateway Timeout from API Gateway?

A 504 means the backend did not respond before the integration timeout. For REST APIs the default (and historical maximum) is 29 seconds; HTTP APIs allow up to 30 seconds. Regional REST APIs can request a higher timeout through a quota increase, but that may lower your account throttle limit.

Common reasons:

  • Slow database queries or downstream calls
  • Lambda cold starts plus long processing
  • A backend unreachable through a VPC link

Look at IntegrationLatency in CloudWatch. For long-running work, return 202 and process asynchronously, for example through SQS or Step Functions.

Take quiz
What does a 504 from API Gateway indicate?
The API key is invalid
The integration did not respond in time
The certificate expired
The payload was too small
What is a good pattern for work that takes minutes?
Raise the account burst limit
Disable authorizers
Accept the request and process it asynchronously
Enable caching

36. How do you troubleshoot 403 Forbidden errors in API Gateway?

A 403 has several possible sources, so narrow it down by the error message in the response body.

Message / symptom Likely cause
Missing Authentication Token Wrong URL or path/method not defined; also missing SigV4 signature
User is not authorized to access this resource Authorizer or IAM policy returned Deny
Forbidden (API key) Missing or wrong key, or key not linked to a usage plan
Blocked by WAF or resource policy Rule or policy denies the source IP or VPC

Turn on execution logging for the stage; it shows whether the authorizer, policy, or key check failed.

Take quiz
'Missing Authentication Token' often really means:
The requested path or method does not exist
The Lambda timed out
The cache is full
The ACM certificate is unattached
Which log type best shows which check rejected the call?
S3 access logs
VPC flow logs only
CloudFront real-time logs only
Execution logs

37. How do you secure a private API with a resource policy?

A resource policy is a JSON policy attached to the API itself that says who may invoke it. For a private API it is mandatory in practice, because it decides which VPC endpoints or VPCs can get through.

{
  "Effect": "Deny",
  "Principal": "*",
  "Action": "execute-api:Invoke",
  "Resource": "execute-api:/*",
  "Condition": { "StringNotEquals": { "aws:SourceVpce": "vpce-0abc123" } }
}

Pair the Deny with an Allow, and every call not arriving via vpce-0abc123 is blocked. Resource policies can also allow other AWS accounts, or restrict by source IP on Regional APIs. They are supported on REST APIs.

Take quiz
Which condition key limits calls to a specific VPC endpoint?
aws:SourceVpce
aws:MultiFactorAuthAge
aws:CurrentTime
aws:PrincipalOrgID only
A resource policy is attached to:
the Lambda execution role
the ACM certificate
the Route 53 zone
the API itself

38. How does AWS WAF integrate with API Gateway?

You associate an AWS WAF web ACL with a REST API stage. WAF then inspects every request before API Gateway processes it and can block, allow, or count based on your rules.

Typical rules include managed rule groups for SQL injection and XSS, IP allow/deny lists, geo restrictions, and rate-based rules that block one IP sending too many requests.

HTTP APIs and WebSocket APIs do not support direct WAF association. For those, put CloudFront with WAF in front of the API.

Take quiz
A web ACL is associated with which API Gateway level?
A single Lambda alias
A REST API stage
An API key
A usage plan
Which rule type blocks an IP that sends too many requests?
Rate-based rule
Regex pattern set on body only
Label match
Byte-size constraint

39. How do you enable mutual TLS on API Gateway?

With mutual TLS (mTLS), the client also presents a certificate, so both sides authenticate. It is configured on the custom domain, not the API.

  1. Upload a truststore (a PEM file of trusted CA certificates) to S3
  2. Enable mTLS on the custom domain and point it at the truststore
  3. Clients connect with a certificate chained to a CA in that truststore

It needs a Regional custom domain and the default execute-api endpoint should be disabled, otherwise clients can bypass mTLS. It is common for B2B and IoT scenarios.

Take quiz
Where is mutual TLS configured in API Gateway?
On a usage plan
On a stage variable
On the Lambda function
On the custom domain name
Which file lists the CAs API Gateway will trust?
An IAM trust policy
A truststore stored in S3
A CloudFormation template
A WAF rule group

40. How does route selection work in a WebSocket API?

When a message arrives, API Gateway evaluates the API's route selection expression against it to pick a route. The most common expression is $request.body.action.

For example, with that expression, this message goes to the sendMessage route:

{ "action": "sendMessage", "text": "hello" }

If no route matches, the message goes to $default (if defined). Connection lifecycle uses the reserved $connect and $disconnect routes. Each route has its own integration, so different actions can hit different Lambdas.

Take quiz
With $request.body.action, which field decides the route?
The 'action' property in the JSON body
The HTTP method
The source IP
The stage name
Where do unmatched messages go?
$connect
$disconnect
They are silently queued forever
$default, if defined

41. How do you send messages to WebSocket clients from a backend?

Every connected client gets a connection ID, which you receive in the $connect event. Store it, for example in DynamoDB, then use the @connections management API to push data to it.

POST https://{api-id}.execute-api.{region}.amazonaws.com/{stage}/@connections/{connectionId}

In code you would normally use the SDK's PostToConnection call, signed with IAM. Other operations exist too: GetConnection and DeleteConnection. A 410 Gone response means the client disconnected, so remove the stale ID from your table.

Take quiz
What does a 410 Gone from PostToConnection indicate?
The API key expired
The stage was deleted
The payload exceeded 10 MB
The connection no longer exists
Where do you get the connection ID from?
The stage variables
The usage plan
The $connect route event
The ACM certificate

42. How do you version an API in Amazon API Gateway?

API Gateway has no single built-in versioning feature, so teams pick a strategy that fits.

Approach How it works Trade-off
Path versioning /v1/orders, /v2/orders as separate resources or via base path mappings Clear and cache-friendly; URLs change
Stage per version A v1 stage and a v2 stage Simple; clients must update the base URL
Separate APIs One API per major version, mapped on a custom domain Strong isolation; more to manage
Header versioning Route by a custom header in your backend Clean URLs; harder to test and cache

Whichever you choose, keep older versions running until clients migrate, and use canary releases for minor changes.

Take quiz
Which option maps /v1 and /v2 on one domain to different APIs?
Stage variables only
Usage plan quotas
Cognito scopes
Base path mappings on a custom domain
A downside of header-based versioning is:
It is harder to test and cache
It requires a VPC link
It only works with WebSocket
It needs a truststore

43. How do you deploy API Gateway with infrastructure as code?

You can define an API in OpenAPI 3 (with x-amazon-apigateway-* extensions) or model it directly, then deploy through CloudFormation, AWS SAM, CDK, or Terraform.

In SAM, a Lambda-backed HTTP API can be just a few lines:

Events:
  GetOrders:
    Type: HttpApi
    Properties:
      Path: /orders
      Method: get

Watch out for REST APIs in raw CloudFormation: an AWS::ApiGateway::Deployment won't redeploy when methods change unless something in it changes, so add a hash or use SAM/CDK, which handle it for you.

Take quiz
Which extension family adds API Gateway settings to OpenAPI files?
x-aws-lambda-*
x-cloudfront-*
x-iam-*
x-amazon-apigateway-*
Which tool provides a short 'HttpApi' event syntax for Lambda?
AWS Snowball
AWS SAM
AWS DMS
Amazon Macie

44. How do you handle binary payloads in API Gateway?

API Gateway treats payloads as text by default, so binary content such as images or PDFs needs explicit setup.

  1. Add the content type (for example image/png or application/pdf) to the API's binary media types list
  2. With Lambda proxy, return the body Base64-encoded and set isBase64Encoded: true
  3. Ensure the client's Accept header matches a configured binary type when returning binary

The payload size limit is 10 MB for REST and HTTP APIs, so large uploads should go directly to S3 using pre-signed URLs instead.

Take quiz
What must a Lambda proxy return for binary output?
A Base64 body with isBase64Encoded set to true
A raw byte array in JSON
A gzip header only
An S3 ARN in statusCode
What is the better path for very large uploads?
Increase the API cache size
Use a mock integration
Add a second stage
Pre-signed S3 URLs

45. How do you integrate API Gateway directly with AWS services like SQS?

You can skip Lambda and let API Gateway call an AWS service directly, using an AWS service integration with an IAM role that allows the action.

For SQS, a REST API method can use a POST to SendMessage with a request mapping template:

Action=SendMessage&MessageBody=$util.urlEncode($input.body)

Set the Content-Type to application/x-www-form-urlencoded and give the execution role sqs:SendMessage. This cuts cost and latency. HTTP APIs offer first-class integrations for SQS, EventBridge, Step Functions, and Kinesis, with less mapping work.

Take quiz
What does API Gateway need to call SQS on your behalf?
A public S3 bucket
An API key
An IAM execution role allowing sqs:SendMessage
A Cognito identity pool only
A benefit of direct service integration is:
Unlimited payload size
No Lambda in the middle, so lower cost and latency
Automatic WAF rules
Free data transfer

46. How can you optimize API Gateway cost and performance?

Start by measuring: CloudWatch shows which APIs and routes carry the traffic and where latency comes from.

  • Use HTTP APIs when you don't need REST-only features; the per-request price is much lower
  • Enable caching on read-heavy REST endpoints with sensible TTLs
  • Cache authorizer results to avoid an extra Lambda call per request
  • Validate requests at the gateway so bad calls never invoke the backend
  • Enable compression on REST APIs to shrink large responses
  • Use direct integrations instead of a pass-through Lambda
  • Reduce cold starts with provisioned concurrency for latency-critical functions

Also remove unused stages and caches, since a provisioned cache bills hourly even when idle.

Take quiz
Which change often lowers per-request cost the most?
Adding a larger cache to every API
Enabling detailed logs everywhere
Moving suitable APIs from REST to HTTP API
Using edge-optimized endpoints
Why cache authorizer results?
It encrypts tokens
It removes the need for IAM
It avoids repeated authorizer invocations for the same caller
It raises the payload limit

47. How can you build a multi-Region highly available API with API Gateway?

API Gateway is Regional, so multi-Region resilience means deploying the same API in two Regions and steering traffic between them.

  1. Deploy identical APIs and backends (via IaC) in Region A and Region B
  2. Create a Regional custom domain in each Region with the same name and an ACM certificate per Region
  3. Use Route 53 failover or latency routing with health checks pointing at each Regional domain
  4. Replicate data stores, for example DynamoDB global tables

Test the failover regularly. The gateway layer is easy to duplicate; stateful backends are usually the harder part.

Take quiz
Which service steers traffic between two Regional APIs?
AWS Snowball
Amazon Inspector
Amazon Route 53 with health checks
AWS Artifact
Which custom-domain type is used for each Region's API?
Edge-optimized only
Private domain
S3 website domain
Regional custom domain

48. Explain the request lifecycle of a REST API call in API Gateway?

When a client calls a REST API, the request passes through a fixed pipeline. Knowing the order helps you place logic and debug failures.

flowchart LR
  A["Client request"] --> B["WAF check"]
  B --> C["Authorization: IAM / Cognito / Lambda"]
  C --> D["Throttling and usage plan"]
  D --> E{Cache hit?}
  E -- Yes --> J["Return cached response"]
  E -- No --> F["Request validation and mapping"]
  F --> G["Integration call to backend"]
  G --> H["Integration response mapping"]
  H --> I["Return to client"]

Failures map to stages: 403 usually comes from WAF or auth, 429 from throttling, 400 from validation, and 502/504 from the integration. A cache hit skips the backend entirely, which is why it improves latency so much.

Take quiz
Where does a cache hit end the request path?
After the WAF check only
Only after response mapping
Before the integration call to the backend
It never skips the backend
A 429 in this flow originates from:
request validation
the integration response
throttling and usage plan limits
the cache TTL

49. Why does Lambda authorizer caching sometimes cause 403 errors on other routes?

The authorizer returns an IAM policy, and API Gateway caches that whole policy against the token. If the policy allowed only the specific method ARN of the first call, later calls with the same token to a different route are checked against that cached policy and get denied.

Two common fixes:

  1. Return a wildcard resource, such as arn:aws:execute-api:region:acct:api-id/stage/*/*, when the same token grants access to many routes
  2. Set the cache TTL to 0 if the decision truly differs per route, or use a REQUEST authorizer whose identity sources include the path

Be careful with wildcards: they must match your real permission model, or you will over-grant.

Take quiz
Why can a cached authorizer policy deny a second route?
The token expired instantly
The stage was redeployed
It was generated for only the first method ARN
WAF blocked the token
A safer alternative when decisions differ per route is:
Longer TTL of 3600
Removing the authorizer
A cache TTL of 0 or a REQUEST authorizer keyed on the path
Adding an API key

50. What are the important quotas and limits in Amazon API Gateway?

Limits matter for design decisions, and many can be raised through Service Quotas. These are typical default values; confirm current numbers in the AWS documentation before relying on them.

Limit Typical value
Account throttle per Region 10,000 rps steady, 5,000 burst
Payload size (REST/HTTP) 10 MB
Integration timeout 29 s (REST default), up to 30 s (HTTP)
WebSocket message / frame size 128 KB / 32 KB
WebSocket connection duration / idle timeout 2 hours / 10 minutes
Cache TTL Default 300 s, max 3600 s

The payload and timeout limits are the ones that most often force an architecture change, such as asynchronous processing or S3 pre-signed uploads.

Take quiz
What is the typical payload limit for REST and HTTP APIs?
1 GB
10 MB
128 KB
100 MB
How long can a WebSocket connection last at most?
10 minutes
24 hours
2 hours
Unlimited
«
»

Comments & Discussions