API Gateway
AWS LabsOfficialPublished by AWS Labs
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides comprehensive support for Amazon API Gateway, covering the full lifecycle of API development. It helps users choose between REST, HTTP, and WebSocket APIs based on specific requirements like cost, latency, and management features. The skill includes guidance on architecture patterns, security configurations (including mTLS and Lambda authorizers), performance tuning, and observability. It also provides troubleshooting steps for common errors and supports IaC implementation using SAM, CloudFormation, and CDK.
What it does
- Assists in selecting the appropriate API type (REST, HTTP, or WebSocket) based on enterprise needs.
- Provides architectural patterns for multi-tenant SaaS, private APIs, and cross-account deployments.
- Offers troubleshooting workflows for common 4xx and 5xx errors, including CORS and timeout issues.
- Guides the implementation of security controls like Lambda authorizers, JWT, and mTLS.
- Generates IaC templates for API Gateway resources using SAM, CloudFormation, or CDK.
- Configures performance settings such as throttling, usage plans, and caching strategies.
When to use it
- When designing or deploying APIs on AWS using API Gateway.
- When you need to troubleshoot API Gateway errors like 403, 502, 504, or CORS failures.
- When implementing security, authentication, or authorization for serverless APIs.
- When you need to optimize API performance, scaling, or observability.
- When you require Infrastructure as Code templates for API Gateway resources.
Advantages
- Reduces development time by providing clear decision trees for API types and auth methods.
- Minimizes configuration errors by highlighting common pitfalls and service limits.
- Ensures consistent deployment practices through standardized IaC patterns.
- Simplifies complex tasks like setting up mTLS or cross-account API routing.
- Provides a structured approach to observability and logging for production readiness.
Usage examples
- “I need to build a REST API that requires per-consumer throttling and request validation. Which API type should I use?”
- The agent will recommend the REST API (v1) and explain how to configure usage plans and request validation to meet your requirements.
- “My API is returning a 504 timeout error. How can I fix this?”
- The agent will guide you through checking backend latency, suggest optimizing the integration, or explain how to request a timeout increase for Regional/Private endpoints.
- “Generate a SAM template for a private API Gateway REST API.”
- The agent will provide a complete SAM/CloudFormation YAML template configured for a private endpoint, including necessary VPC link resources.
- “How do I set up mTLS for my API Gateway?”
- The agent will explain the requirements for Regional custom domains, S3 truststore configuration, and the necessary security policies.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/awslabs/api-gateway/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip api-gateway.zip -d .agents/skills
Documentation by AWS Labs
Amazon API Gateway Development
Expert guidance for building, managing, governing, and operating APIs with Amazon API Gateway. Covers REST APIs (v1), HTTP APIs (v2), and WebSocket APIs.
How to Use This Skill
When answering API Gateway questions:
Read the relevant reference file(s) before responding, do not rely solely on this summary
For tasks spanning multiple concerns (e.g., "private API with mTLS and custom domain"), read all relevant references
When the user needs IaC templates, consult
references/sam-cloudformation.mdorreferences/sam-service-integrations.mdand provide complete, working SAM/CloudFormation YAMLAlways mention relevant pitfalls and limits that affect the user's design
Quick Decision: Which API Type?
Choose the right API type first. This decision affects every downstream choice.
REST API is the full-featured API management platform for enterprises. It provides the governance, security, monetization, and operational controls that organizations need to build, publish, and manage APIs at scale, including usage plans with per-consumer throttling and quotas, API keys, request validation, WAF integration, resource policies, caching, canary deployments, and private endpoints.
HTTP API is the lightweight, low-cost proxy optimized for simpler API workloads. It offers ~70% lower cost and lower latency but trades away the API management features. Choose HTTP API when you need a fast, lightweight proxy to Lambda or HTTP backends and don't require the enterprise controls above.
| Factor | REST API (v1) | HTTP API (v2) | WebSocket API |
|---|---|---|---|
| Positioning | Full API management | Low-cost proxy | Real-time bidirectional |
| Cost | Higher | ~70% cheaper | Per-message pricing |
| Latency | Higher | Lower | Persistent connection |
| Max timeout | 50ms-29s (up to 300s Regional/Private) | 30s hard limit | 29s |
| Payload | 10 MB | 10 MB | 128 KB message / 32 KB frame |
| API Management | |||
| Usage plans/API keys | Yes | No | No |
| Request validation | Yes (JSON Schema draft 4) | No | No |
| Caching | Yes (0.5-237 GB) | No | No |
| Custom gateway responses | Yes | No | No |
| VTL mapping templates | Yes | No (parameter mapping only) | Yes |
| Security & Governance | |||
| WAF | Yes | No (use CloudFront + WAF) | No |
| Resource policies | Yes | No | No |
| Private endpoints | Yes | No | No |
| mTLS | Yes (Regional custom domain only) | Yes (Regional custom domain only) | Via CloudFront viewer mTLS |
| Auth | |||
| Lambda authorizer | Yes (TOKEN + REQUEST) | Yes (REQUEST only, simple + IAM policy format) | Yes (REQUEST on $connect only) |
| JWT authorizer | No (use Cognito authorizer) | Yes (native) | No |
| Cognito authorizer | Yes (native) | Use JWT authorizer | No |
| Operations | |||
| Canary deployments | Yes | No | No |
| Response streaming | Yes | No | No |
| X-Ray tracing | Yes | No | No |
| Execution logging | Yes | No | Yes |
| Custom domain sharing | Not with WebSocket | Not with WebSocket | Not with REST/HTTP |
Use REST API when: you are building APIs for external consumers, partners, or multi-tenant platforms; need to enforce per-consumer rate limits and quotas; require request validation, caching, or WAF at the API layer; need private endpoints, resource policies, or canary deployments; or are building an API product with monetization and governance requirements.
Use HTTP API when: you are building lightweight APIs or simple backend proxies; cost and latency are the primary concerns; you don't need per-consumer throttling, request validation, caching, or WAF at the API layer; and native JWT authorization with OIDC/OAuth 2.0 meets your auth needs. Accept the hard 30s timeout and lack of API management features. For WAF, edge caching, or edge compute, place a CloudFront distribution in front of the HTTP API.
Use WebSocket API when you need: persistent bidirectional connections for real-time use cases (chat, notifications, live dashboards).
Instructions
Step 1: Design the API
Before implementation, gather requirements systematically. Consult references/requirements-gathering.md for the full requirements workflow covering endpoints, auth, data models, performance, security, and deployment needs.
Key design decisions:
API type: Use the decision table above
Endpoint type: Edge-optimized (default for global clients; optimizes TCP connections via CloudFront POPs but does not cache at the edge), Regional (same-region clients, or global clients needing their own CloudFront distribution for edge caching, edge compute, granular WAF control, or geo-based routing), Private (VPC-only access, REST API only)
Topology: Centralized (single domain, path-based routing) vs Distributed (subdomains per service)
Authentication: See
references/authentication.mdfor the decision tree
Step 2: Implement the API
Consult these references based on what you're building:
Architecture patterns:
references/architecture-patterns.md: topology, multi-tenant SaaS, hybrid workloads, private APIs, multi-region, streamingWebSocket API:
references/websocket.md: route selection, @connections management, session management, client resilience, SAM templates, limits, multi-regionService integrations:
references/service-integrations.md: direct AWS service integrations (EventBridge, SQS, SNS, DynamoDB, Kinesis, Step Functions, S3), HTTP proxy, mock, VTL mapping templates, binary media types, Lambda sync/async invocationCustom domains and routing:
references/custom-domains-routing.md: base path mappings, routing rules, header-based versioningSecurity:
references/security.md: mTLS (API Gateway native + CloudFront viewer mTLS), TLS policies, resource policies, WAF, HttpOnly cookies, CRL checksSAM/CloudFormation:
references/sam-cloudformation.md: IaC patterns, OpenAPI extensions, VTL reference, binary dataSAM service integration templates:
references/sam-service-integrations.md: EventBridge, SQS, DynamoDB CRUD, Kinesis, Step Functions (REST + WebSocket) templates
Step 3: Configure Performance and Scaling
Throttling: Account-level default is 10,000 rps / 5,000 burst (adjustable; request increases via AWS Support). Configure stage-level and method-level throttling via usage plans. See
references/performance-scaling.mdCaching (REST only): Default TTL 300s, max 3600s. Only GET methods cached by default. Max cached response 1 MB
Edge caching (all API types): For edge caching, place a self-managed CloudFront distribution in front of a Regional API. CloudFront reduces latency, backend load, AND cost (cached responses never reach API Gateway). Also enables edge compute (CloudFront Functions, Lambda@Edge) and granular cache behaviors per path. Use a Regional endpoint, not edge-optimized, when pairing with your own CloudFront distribution
Scaling: API Gateway scales automatically but plan the entire stack (Lambda concurrency, DynamoDB capacity)
Step 4: Set Up Observability
Always configure access logging. For REST and WebSocket APIs, also enable execution logging (ERROR level for production, INFO only for debugging). HTTP API does not support execution logging; use access logs with enhanced observability variables instead.
Consult the observability references based on what you need:
Logging setup, log formats, retention:
references/observability-logging.mdMetrics, alarms, metric filters, X-Ray tracing:
references/observability-metrics-alarms.mdLog analysis and insights, analytics pipeline, cross-account, control plane logs:
references/observability-analytics.md
Step 5: Deploy
Use Infrastructure as Code (SAM, CDK, CloudFormation, Terraform) for production
Canary deployments (REST only): Route a percentage of traffic to test new versions
Blue/green deployments: Use custom domain API mappings to switch between environments with zero downtime
Routing rules (preferred for new domains): Declarative header/path-based routing on custom domains for versioning, A/B testing, gradual rollouts, and cell-based routing
See
references/deployment.mdfor detailed patterns
Step 6: Apply Governance
For organization-wide API standards, see references/governance.md covering:
Preventative controls (SCPs, IAM policies)
Proactive controls (CloudFormation Hooks, Guard rules)
Detective controls (AWS Config rules, EventBridge)
Specific enforcement examples for security, observability, and management
Response Format
When responding to API Gateway questions, structure your answer as:
Recommendation: Lead with the recommended approach and why
Code: Include SAM/CloudFormation YAML or code when the user needs implementation (always read the relevant reference file first)
Pitfalls: Warn about relevant gotchas from the pitfalls below or from
references/pitfalls.mdLimits: Mention any service limits that constrain the design
Troubleshooting Quick Reference
When diagnosing API Gateway errors, consult references/troubleshooting.md for detailed resolution steps. Here are the most common issues:
| Error | Most Common Cause | Quick Fix |
|---|---|---|
| 400 Bad Request | Protocol mismatch (HTTP/HTTPS) with ALB | Match protocol to listener type |
| 401 Unauthorized | Wrong token type (ID vs access) or missing identity sources | Check token type matches scope config; verify all identity sources sent |
| 403 Missing Auth Token | Stage name in URL when using custom domain | Remove stage name from URL path |
| 403 from VPC | Private DNS on VPC endpoint intercepts ALL API calls | Use custom domain names for public APIs |
| 403 Access Denied | Resource policy + auth type mismatch or missing redeployment | Review policy, check auth type, redeploy API |
| 403 mTLS | Certificate issuer not in truststore or weak signature algorithm | Verify CA in truststore, use SHA-256+ |
| 429 Too Many Requests | Account/stage/method throttle limits exceeded | Implement jittered exponential backoff; request limit increase |
| 500 Internal Error | Missing Lambda invoke permission (especially with stage variables) | Add resource-based policy to Lambda function |
| 502 Bad Gateway | Lambda response not in required proxy format | Return {statusCode, headers, body} from Lambda |
| 504 Timeout | Backend exceeds 29s (REST, increasable) or 30s (HTTP, hard). HTTP API body says "Service Unavailable" but status is 504 | Optimize backend, request timeout increase (REST Regional/Private), or switch to async invocation |
| CORS errors | Missing CORS headers on Gateway Responses (4XX/5XX) | Add CORS headers to DEFAULT_4XX and DEFAULT_5XX gateway responses |
| SSL/PKIX errors | Incomplete certificate chain on backend | Provide full cert chain; use insecureSkipVerification only for testing |
Critical Pitfalls
REST API default timeout is 29 seconds (increasable up to 300s for Regional/Private endpoints via quota request). Lambda continues running but client gets 504. Request a timeout increase, or consider async patterns (SQS, EventBridge) for better user experience on long operations
HTTP API hard timeout is 30 seconds. Returns
{"message":"Service Unavailable"}while Lambda continues/pingand/spingare reserved paths. Do not use for API resourcesExecution log events truncated at 1,024 bytes. Use access logs for complete data
413
REQUEST_TOO_LARGEis the only gateway response that cannot be customized. Use DEFAULT_4XX as a catch-all to add CORS headers for all 4xx errors including 413maxItems/minItemsnot validated in REST API request validationRoot-level
securityin OpenAPI is ignored. Must set per-operationJWT authorizer public keys cached 2 hours. Account for this in key rotation
Management API rate limit: 10 rps / 40 burst. Heavy automation can hit this
Always redeploy REST API after configuration changes. Changes don't take effect until deployed
Edge-optimized endpoints do NOT cache at the edge — they only optimize TCP connections via CloudFront POPs. If you need edge caching, edge compute (CloudFront Functions, Lambda@Edge), or granular CloudFront control, use a Regional API with your own CloudFront distribution instead
For additional pitfalls (header handling, URL encoding, caching charges, canary deployments, usage plans), see references/pitfalls.md.
IaC Framework Selection
Default: CDK TypeScript
Override syntax:
"use SAM" → Generate SAM/CloudFormation YAML templates
"use CloudFormation" → Generate CloudFormation YAML templates
"use Terraform" → Generate Terraform HCL
When not specified, ALWAYS use CDK TypeScript.
Error Scenarios
MCP Server Unavailable
Inform user: "AWS Serverless MCP not responding"
Ask: "Proceed without MCP support?"
DO NOT continue without user confirmation
Service Limits Quick Reference
See references/service-limits.md for the complete table. Most numeric quotas below are default values and adjustable; check with your AWS account team and the latest quotas page before using them for architectural decisions. Key limits:
| Resource | REST API | HTTP API | WebSocket |
|---|---|---|---|
| Payload size | 10 MB | 10 MB | 128 KB |
| Integration timeout | 50ms-29s (up to 300s Regional/Private) | 30s hard | 29s |
| APIs per region | 600 Regional/Private; 120 Edge-optimized | 600 | 600 |
| Stages per API | 10 | 10 | 10 |
| Routes/resources per API | 300 | 300 | 300 |
| Custom domains (public) | 120 | 120 | 120 |
| Account throttle | 10,000 rps / 5,000 burst | Same | Same (shared quota) |
| API keys per region | 10,000 | N/A | N/A |
| Usage plans per region | 300 | N/A | N/A |
| Cache sizes | 0.5 GB - 237 GB | N/A | N/A |
Files
- ATTRIBUTION.mdAdded by AutoGineer908 B
- LICENSELicence file added by AutoGineer9.9 KiB
- NOTICELicence file added by AutoGineer89 B
- SKILL.md19.3 KiB
- references/architecture-patterns.md19.0 KiB
- references/authentication.md9.4 KiB
- references/custom-domains-routing.md8.5 KiB
- references/deployment.md14.9 KiB
- references/governance.md9.8 KiB
- references/observability-analytics.md4.2 KiB
- references/observability-logging.md11.2 KiB
- references/observability-metrics-alarms.md5.5 KiB
- references/performance-scaling.md9.0 KiB
- references/pitfalls.md2.0 KiB
- references/requirements-gathering.md14.8 KiB
- references/sam-cloudformation.md7.8 KiB
- references/sam-service-integrations.md22.5 KiB
- references/security.md18.2 KiB
- references/service-integrations.md24.4 KiB
- references/service-limits.md11.5 KiB
- references/troubleshooting.md14.5 KiB
- references/websocket.md7.4 KiB
references/security.md
Security Best Practices
TLS Configuration
TLS Security Policies
TLS 1.2 is the recommended minimum
Two naming conventions: legacy policies use
TLS_prefix (e.g.,TLS_1_0,TLS_1_2), enhanced policies useSecurityPolicy_prefix (e.g.,SecurityPolicy_TLS13_1_3_2025_09) and support TLS 1.3 and post-quantum cryptographyEdge-optimized endpoints: use CloudFront TLS stack with
_EDGEsuffix policies (e.g.,SecurityPolicy_TLS13_2025_EDGE). Supports TLS 1.3Regional/Private endpoints: use API Gateway TLS stack with date-based suffix policies (e.g.,
SecurityPolicy_TLS13_1_2_PQ_2025_09). Supports TLS 1.3 and post-quantumEndpoint access mode:
BASIC(standard) vsSTRICT(validates SNI matches Host header)Migration: Apply enhanced policy with BASIC first, validate with access logs (
$context.tlsVersion,$context.cipherSuite), then switch to STRICTSTRICT mode takes up to 15 minutes to propagate
Disable Default Endpoint
Set
disableExecuteApiEndpoint: trueto force all traffic through custom domainREST APIs return 403 when disabled; HTTP APIs return 404 (observed behavior; not explicitly documented in the developer guide)
Must redeploy after changing this setting
Mutual TLS (mTLS)
Setup
Create CA hierarchy (ACM Private CA or self-managed)
Export root CA public key to PEM truststore file
Upload to versioned S3 bucket (same region as API Gateway)
Configure custom domain with truststore URI (
s3://bucket/truststore.pem)Use public ACM certificate for the API Gateway domain itself
Disable default endpoint
Automation with ACM Private CA
Lambda-backed CloudFormation custom resource concatenates certificate chain and uploads to S3
Certificates issued by root CA or any subordinate CA are automatically trusted
SAM resources:
AWS::ACMPCA::CertificateAuthority,AWS::ACMPCA::Certificate,AWS::CertificateManager::Certificate
Certificate Revocation Lists (CRL)
API Gateway does NOT check CRLs natively
Implement via Lambda authorizer:
Extract client cert serial number
Check against CRL stored in DynamoDB (fast lookups at scale)
Deny access if revoked
S3 PutObject event triggers preprocessing Lambda: validates CRL signature, decodes ASN.1, stores simplified JSON
Use function-level caching with S3 ETag for cache invalidation
Lambda authorizer caching and CRL checks: Disable authorizer caching if near-real-time revocation is required. If some latency is acceptable, use a short TTL (e.g., 60s) matching your revocation freshness requirements
Propagating Client Identity
Lambda authorizer extracts client cert subject:
from cryptography import x509; cert = x509.load_pem_x509_certificate(event['requestContext']['identity']['clientCert']['clientCertPem'].encode())Returns
clientCertSub(fromcert.subject.rfc4514_string()) in authorizercontextAPI Gateway injects via
RequestParameters: 'integration.request.header.X-Client-Cert-Sub': 'context.authorizer.clientCertSub'Backend receives client identity without performing mTLS validation itself
CloudFront Viewer mTLS
CloudFront now supports mTLS authentication between viewers (clients) and CloudFront edge locations. This enables mTLS for any origin, including API Gateway HTTP APIs and WebSocket APIs that don't natively support mTLS.
Architecture: Client <-> mTLS <-> CloudFront <-> API Gateway (any type)
Setup:
Upload root CA and intermediate CA certificates (PEM bundle) to S3
Create CloudFront Trust Store referencing the S3 path
Enable "Viewer mutual authentication (mTLS)" on distribution settings
Associate the trust store with the distribution
Modes:
Required: All clients must present valid certificates
Optional: Accepts both mTLS and non-mTLS clients on the same distribution; still rejects invalid certificates
Certificate headers forwarded to origin (enable in origin request policy):
CloudFront-Viewer-Cert-Serial-Number,CloudFront-Viewer-Cert-Issuer,CloudFront-Viewer-Cert-SubjectCloudFront-Viewer-Cert-Validity,CloudFront-Viewer-Cert-PEM,CloudFront-Viewer-Cert-Present,CloudFront-Viewer-Cert-SHA256Use these headers in Lambda authorizers or backend logic for identity-based access control
Certificate revocation: Use CloudFront Connection Functions + KeyValueStore for real-time CRL checks during TLS handshake:
Store revoked serial numbers in KeyValueStore
Connection function checks
connection.clientCertificate.certificates.leaf.serialNumberagainst KVSCall
connection.deny()for revoked certificates; rejection happens at the edge before any request reaches the origin
Connection functions: Execute custom logic during TLS handshake (before viewer request). Can allow, deny, or log connection details. Use connection.logCustomData() for custom connection log entries.
Monitoring: CloudFront connection logs capture TLS handshake details. Each connection gets a unique connectionId that correlates across connection logs, standard logs, and real-time logs.
Options:
Ignore certificate expiration date: Accept expired certificates (useful for gradual migration)Advertise trust store CA names: Send list of accepted CA distinguished names to clientsCertificate chain depth supported: up to 4 (root + intermediates)
When to use CloudFront viewer mTLS instead of API Gateway mTLS:
HTTP APIs or WebSocket APIs that don't support native mTLS
Need edge-based certificate validation (lower latency for global clients)
Need optional mode (mixed mTLS and non-mTLS on same endpoint)
Need Connection Functions for custom TLS handshake logic
Need real-time CRL checks via KeyValueStore (faster than Lambda authorizer approach)
Private APIs + mTLS
Private APIs do not natively support mTLS
Pattern: ALB with mTLS "Verify with trust store" mode -> VPC endpoint -> private API
ALB supports CRL checks on trust store
Cross-account: client -> PrivateLink -> NLB -> ALB (mTLS) -> VPC endpoint -> private API
Resource Policies (REST API)
IP-Based Access Control
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/*"
},
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/*",
"Condition": { "NotIpAddress": { "aws:SourceIp": ["203.0.113.0/24", "198.51.100.0/24"] } }
}
]
}execute-api:/*is a shorthand accepted only in API Gateway resource policies (API Gateway auto-expands it to the full ARN (arn:aws:execute-api:region:account-id:api-id/*)). Do not use this shorthand in IAM identity-based policiesFor traffic through VPC endpoint: use
aws:VpcSourceIpinstead ofaws:SourceIp
HTTP API IP Control
No resource policies for HTTP APIs
Use Lambda authorizer checking
event.requestContext.http.sourceIpagainst allowlistSupport both exact IPs and CIDR ranges
VPC Endpoint Restriction
{ "Condition": { "StringEquals": { "aws:SourceVpce": "vpce-0123456789abcdef0" } } }AWS WAF (REST API Direct; HTTP API via CloudFront)
REST API: Associate Web ACL directly with API stage (no CloudFront required)
HTTP API: No direct WAF association. Workaround: Place CloudFront distribution in front of HTTP API and attach WAF to CloudFront. This is a common production pattern
Gateway response type
WAF_FILTERED(403) when WAF blocks requestAccess log variables:
$context.waf.error,$context.waf.latency,$context.waf.statusBody inspection limit: Default 16 KB for regional API Gateway (configurable up to 64 KB in web ACL for additional cost)
Header inspection limit: First 8 KB or 200 headers (whichever comes first)
"Distributed Denial of Wallet" protection: Without WAF, DDoS traffic invokes Lambda authorizers for every request. WAF blocks malicious traffic before it reaches the authorizer
Recommended Managed Rule Groups for APIs
Tier 1: Always enable for API protection.
| Rule Group | Name | WCU | Purpose |
|---|---|---|---|
| Core Rule Set | AWSManagedRulesCommonRuleSet | 700 | XSS, LFI, RFI, SSRF, path traversal, size restrictions. Note: SizeRestrictions_BODY rule blocks bodies >8 KB; override to Count if your API accepts larger payloads |
| Known Bad Inputs | AWSManagedRulesKnownBadInputsRuleSet | 200 | Log4j RCE, Java deserialization, PROPFIND, exploitable paths, localhost Host header |
| SQL Database | AWSManagedRulesSQLiRuleSet | 200 | SQL injection in query params, body, cookies, URI path |
| IP Reputation | AWSManagedRulesAmazonIpReputationList | 25 | Blocks IPs from AWS threat intelligence (MadPot): malicious actors, reconnaissance, DDoS sources |
Tier 2: Enable based on use case.
| Rule Group | Name | WCU | When to use |
|---|---|---|---|
| Anonymous IP List | AWSManagedRulesAnonymousIpList | 50 | Block TOR nodes, anonymous proxies, VPN services, hosting provider IPs. Use when API should not be accessed anonymously |
| Bot Control | AWSManagedRulesBotControlRuleSet | 50 | Detect/block scrapers, automated browsers, bad bots. Common ($1/M requests) for basic detection; Targeted ($10/M requests) adds ML-based detection (same WCU, higher per-request cost). Note: CategoryAI rule blocks all AI bot traffic (both verified and unverified) unlike other category rules; override to Count and use labels (bot:category:ai:verified vs unverified) for fine-grained control |
| Admin Protection | AWSManagedRulesAdminProtectionRuleSet | 100 | Block access to admin URI paths. Use if API has admin endpoints |
| Account Takeover Prevention | AWSManagedRulesATPRuleSet | 50 | Credential stuffing protection on login endpoints. Checks against stolen credential databases. Additional fees apply |
Tier 3: Custom rules for API-specific protection.
| Rule Type | Purpose |
|---|---|
| Rate-based rules | Per-IP request rate limiting (complements API Gateway throttling) |
| Geo-match rules | Block traffic from regions where you have no customers |
| IP set rules | Allow/deny specific IP ranges |
| Size constraint rules | Custom payload size limits per endpoint |
| Regex pattern rules | Block specific patterns in headers/body (e.g., malformed JWTs) |
WAF Best Practices for APIs
Start in Count mode: Deploy managed rules in Count mode first, analyze CloudWatch metrics and WAF logs, then switch to Block
Use labels for custom logic: Managed rules add labels to requests. Write custom rules that match on labels for fine-grained control (e.g., allow verified bots but block unverified ones)
Override specific rules: If a managed rule causes false positives, override that single rule to Count rather than disabling the entire rule group
Web ACL capacity: Default allocation is 1,500 WCU per web ACL (hard limit 5,000 via support request). WCU above 1,500 incurs additional cost ($0.20 per million requests per 500 WCU block). Plan rule group selection within this budget. Tier 1 rules alone total 1,125 WCU
Scope down statements: Apply expensive rule groups (Bot Control, ATP) only to specific URI paths to reduce cost and false positives
WAF + API Gateway throttling: WAF rate-based rules operate at the edge; API Gateway throttling operates at the service level. Use both for defense in depth
WAF token domain: When CloudFront fronts a WAF-protected API Gateway, CloudFront rewrites the
Hostheader to the origin domain. WAF challenge/CAPTCHA tokens are tied to the client-facing domain, causing a domain mismatch at the origin. Fix: add the CloudFront distribution domain to the token domain list in the origin's web ACL, and forward theaws-waf-tokencookie to the origin
CORS Configuration
REST API
Configure
OPTIONSmethod with Mock integration returning CORS headersLambda must ALSO return CORS headers in actual response (proxy integration)
Critical: Add CORS headers to
DEFAULT_4XXandDEFAULT_5XXgateway responses; otherwise errors are blocked by browserSAM
Corsproperty helps but does NOT cover gateway responsesOnly one origin allowed in MOCK response; use
*or Lambda integration for dynamic origin. Security warning: dynamically reflecting theOriginheader without validating against an allowlist is functionally equivalent to*but also works with credentials. Always validate against an explicit allowlistAdd
AddDefaultAuthorizerToCorsPreflight: falseto exclude authorizer from OPTIONS
HTTP API
First-class
CorsConfigurationproperty:allowOrigins,allowMethods,allowHeaders,exposeHeaders,maxAge,allowCredentialsAPI Gateway automatically handles OPTIONS preflight; no MOCK integration needed
*for AllowOrigins does not work whenAllowCredentialsis true
Common Gotchas
Forgetting CORS headers on gateway responses means 403/500 errors are blocked by browser
For private APIs: avoid
x-apigw-api-idheader (triggers preflight that fails); use Host header insteadAccess-Control-Allow-Originmust match requesting origin exactly when using credentials
HttpOnly Cookie Authentication
Pattern for preventing XSS token theft:
OAuth2 callback Lambda: Exchanges auth code for access token, returns via
Set-Cookieheader withHttpOnly,Secure,SameSite=LaxLambda authorizer: Extracts cookie from request, validates JWT, allows/denies
Identity source:
$request.header.cookiefor cachingUse
aws-jwt-verifylibrary; create verifier outside handler for JWKS caching across warm starts
API Gateway Architecture
API Gateway is a multi-tenant managed service running in an AWS-managed VPC; nothing is deployed into customer VPCs
This is why VPC Links exist: they bridge the gap between the AWS-managed VPC (where API Gateway runs) and your VPC (where private resources live)
API Gateway has internet connectivity by default, which is why it can reach external endpoints even when your VPC cannot
Security at All Layers
Apply security at every component, not just the data plane (who can call APIs). Also secure the control plane (who can modify/deploy APIs).
Cache Encryption (REST API)
API Gateway cache is not encrypted at rest by default; encryption must be explicitly enabled when provisioning the cache
Cache is not isolated per API key by default: one client can receive cached responses generated for another client if the cache key parameters (path, query strings, configured headers) match. To prevent this, add a client-identifying parameter (e.g., API key header) as a cache key
For APIs handling sensitive data, always enable cache encryption
Cache encryption can only be set at cache creation time; changing it requires re-provisioning
Logging Data Sensitivity
Standard execution logging auto-redacts authorization headers, API key values, and similar sensitive parameters
Data tracing (separate option from execution logging) logs full request/response bodies including PII and credentials. AWS recommends against enabling data tracing in production
Treat CloudWatch log groups containing execution logs as sensitive data: apply appropriate IAM access controls, retention policies, and CloudWatch Logs data protection policies
Binary Data Security
Register binary media types explicitly (e.g.,
image/png,application/octet-stream)Avoid
*/*in binary media types unless intentional, as it treats ALL content as binaryFor file uploads via S3: use presigned URLs for large files instead of proxying through API Gateway (10 MB payload limit)
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs an API key
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- AWS Labs
- Publisher
- AWS Labs (Official)
- Source
- awslabs/agent-plugins · plugins/aws-serverless/skills/api-gateway · commit fbefb37
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- NOTICE (added by AutoGineer from NOTICE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by AWS Labs.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download api-gateway.zip