Cloud / Amazon API Gateway Interview questions
Last updated
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
a relational database engine
a container orchestration service
a DNS-only routing service
a managed front door for creating and securing APIs
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
HTTP API
REST API
Private API
WebSocket API
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.
- Edge-optimized - requests go through a CloudFront-managed distribution and enter AWS at the nearest edge location. Good for geographically spread clients.
- 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.
- 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
Regional
Private
Edge-optimized
Global
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 database table for API data
a Lambda alias only
a billing tier
a named, callable deployment of the API
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
A stage variable
A path parameter
An API key
A Lambda alias
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
AWS_PROXY
MOCK
HTTP_PROXY
AWS
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
a raw JSON object
an XML document only
a string
a Base64 image
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
Handlebars
Jinja2
GraphQL SDL
Velocity Template Language (VTL)
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
Authorization
x-amz-security-token
x-usage-plan
x-api-key
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
An HTML login form
A signed Cognito token
An IAM policy with Allow or Deny
A CloudFront cookie
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 JWT issued by the user pool
A SigV4 signature
An x-api-key header
A client TLS certificate
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
#{stage.name}
%stage_name%
$env.name
${stageVariables.name}
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
30 seconds
300 seconds
3600 seconds
24 hours
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
us-east-1
eu-west-1
The same Region as the Lambda function
Any Region
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:
- Account-level per Region (default 10,000 requests/second steady-state, 5,000 burst)
- Per-stage or per-method settings
- Per-client limits through usage plans
Clients should handle 429 with retries and exponential backoff.
Take quiz
401
429
502
413
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
Streaming video
Running long batch jobs
Encrypting S3 objects
Answering CORS preflight OPTIONS requests
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
$default
$open
$connect
$init
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
an internet gateway only
an interface VPC endpoint
a public CloudFront distribution
an S3 gateway endpoint
A resource policy
An S3 bucket policy
A stage variable
A CloudTrail trail
19. What is a VPC link in Amazon API Gateway?
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.
Take quiz
cache responses in CloudFront
reach private resources inside a VPC
replicate APIs to another Region
validate JWT tokens
An S3 bucket
A Route 53 hosted zone
A Network Load Balancer
A DynamoDB table
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
Only CloudFront
Only Route 53
Nobody, it is automatic
The Lambda function
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 requests4XXErrorand5XXError- client and server error countsLatency- total time from request received to response sentIntegrationLatency- time spent waiting on the backendCacheHitCount/CacheMissCount- cache effectiveness
Comparing Latency with IntegrationLatency shows quickly whether slowness is in the gateway or your backend.
Take quiz
IntegrationLatency
Count
CacheHitCount
4XXError
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:
- Required query strings, headers, and path parameters
- 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
A CloudFormation output
A model in JSON Schema
An IAM policy
A Route 53 record
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:
- Deploy the new version to the stage as a canary with, say, 10% traffic
- Watch metrics and logs (canary stats are reported separately)
- 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
It is deleted
It moves to another Region
It switches to an HTTP API
It becomes the stage's full deployment
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
API Gateway caches edits for 24 hours
Changes must be captured in a new deployment
Stages are read-only
Lambda must be restarted
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
Lambda integration
Built-in response caching
Custom domain names
CloudWatch metrics
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
Edge-optimized
Neither
Only Private
Regional
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
CloudFront
The client browser
API Gateway using mapping templates
AWS Config
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
TOKEN
Neither
Cognito only
REQUEST
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
OAuth 1.0a
Signature Version 4 (SigV4)
A CloudFront key pair
Basic auth
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
Encrypting traffic end to end
Replacing IAM roles
Identifying clients for throttling and quotas
Issuing JWT tokens
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:
- Per-client limits in a usage plan
- Per-method limits on a stage
- Per-stage/API default limits
- 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
Leaky heap
Token bucket
Round robin
Two-phase commit
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
X-Cache: skip
Accept: no-cache-please
Cache-Control: max-age=0
Authorization: none
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:
- Reads the token from the identity source (usually the
Authorizationheader) - Verifies the signature against the issuer's public keys
- Checks
exp,iss, andaudorclient_id - Optionally enforces route-level scopes
Valid claims are passed to the backend in the request context.
Take quiz
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
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:
bodyreturned as an object instead of a stringstatusCodemissing 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
404
301
502
204
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
The API key is invalid
The integration did not respond in time
The certificate expired
The payload was too small
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
The requested path or method does not exist
The Lambda timed out
The cache is full
The ACM certificate is unattached
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
aws:SourceVpce
aws:MultiFactorAuthAge
aws:CurrentTime
aws:PrincipalOrgID only
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 single Lambda alias
A REST API stage
An API key
A usage plan
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.
- Upload a truststore (a PEM file of trusted CA certificates) to S3
- Enable mTLS on the custom domain and point it at the truststore
- 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
On a usage plan
On a stage variable
On the Lambda function
On the custom domain name
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
The 'action' property in the JSON body
The HTTP method
The source IP
The stage name
$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
The API key expired
The stage was deleted
The payload exceeded 10 MB
The connection no longer exists
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
Stage variables only
Usage plan quotas
Cognito scopes
Base path mappings on a custom domain
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
x-aws-lambda-*
x-cloudfront-*
x-iam-*
x-amazon-apigateway-*
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.
- Add the content type (for example
image/pngorapplication/pdf) to the API's binary media types list - With Lambda proxy, return the body Base64-encoded and set
isBase64Encoded: true - Ensure the client's
Acceptheader 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
A Base64 body with isBase64Encoded set to true
A raw byte array in JSON
A gzip header only
An S3 ARN in statusCode
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
A public S3 bucket
An API key
An IAM execution role allowing sqs:SendMessage
A Cognito identity pool only
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
Adding a larger cache to every API
Enabling detailed logs everywhere
Moving suitable APIs from REST to HTTP API
Using edge-optimized endpoints
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.
- Deploy identical APIs and backends (via IaC) in Region A and Region B
- Create a Regional custom domain in each Region with the same name and an ACM certificate per Region
- Use Route 53 failover or latency routing with health checks pointing at each Regional domain
- 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
AWS Snowball
Amazon Inspector
Amazon Route 53 with health checks
AWS Artifact
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
After the WAF check only
Only after response mapping
Before the integration call to the backend
It never skips the backend
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:
- Return a wildcard resource, such as
arn:aws:execute-api:region:acct:api-id/stage/*/*, when the same token grants access to many routes - 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
The token expired instantly
The stage was redeployed
It was generated for only the first method ARN
WAF blocked the token
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.