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/architecture-patterns.md
Architecture Patterns
Topology Patterns
Three topology patterns:
Single AWS account: Simplest. All APIs in one account with routing rules or base path mappings
Separate AWS accounts per domain/application: Better isolation. Each account owns a subdomain (e.g.,
orders.example.com,shipping.example.com) and can contain multiple microservices behind it. No cross-account base path mappings, so subdomain-per-account is the routing mechanismCentral API account: Central account owns the custom domain and routes to backend APIs in other accounts. Centralized governance, throttling, metering, and observability
API Gateway as Single Entry Point
Both single AWS account or central API account scenarios
Map different custom domain subdomains to the same API with routing rules or different base path mappings
Route different paths (
/service1,/service2,/docs) to different backends
Endpoint type selection:
Regional (default): API deployed in a single region. Best when clients are in the same region or when using your own CloudFront distribution for edge caching/WAF control. Supports custom domains with ACM certificates in the same region
Edge-optimized: Routes requests through CloudFront POPs for optimized TCP connections to global clients. Does NOT cache at the edge. For actual edge caching, use a self-managed CloudFront distribution with a Regional API. ACM certificate must be in
us-east-1Private: Accessible only from within a VPC via
execute-apiVPC endpoint. REST API only. See Private API Endpoints section below
Trade-offs with central account:
X-Ray traces can span accounts using CloudWatch cross-account observability (source/monitoring account linking), but require explicit setup
Usage plans cannot track across accounts without aggregation
CloudWatch dashboards require aggregation in central account
Multi-Tenant SaaS Specific Concerns
Tiered usage plans (free/pro/enterprise or bronze/silver/gold)
Lambda authorizer validates JWT from external IdP, extracts tenant ID, retrieves per-tenant API key from DynamoDB, returns it in
usageIdentifierKeyfor transparent per-tenant throttling (seereferences/authentication.mdfor full flow)Set
ApiKeySourceType: AUTHORIZERso API Gateway reads the key from the authorizer response, so tenants never see or manage API keysOnboarding automation: create tenant in IdP + API key in API Gateway + mapping in DynamoDB + associate key with usage plan tier
Forward tenant identification as custom header to backend for tenant-specific logic
Lambda tenant isolation mode: For compute-level tenant isolation beyond throttling, create Lambda functions with
--tenancy-config '{"TenantIsolationMode": "PER_TENANT"}'. Lambda isolates execution environments per tenant: each environment is reused only for invocations from the same tenant, preventing cross-tenant data access via in-memory or/tmpstorage. API Gateway maps the tenant ID to theX-Amz-Tenant-Idheader on the Lambda integration request (e.g., from a Lambda authorizer context value viacontext.authorizer.tenantId, or from a client request header viamethod.request.header.x-tenant-idmapped tointegration.request.header.X-Amz-Tenant-Id). Tenant ID is available in the handler context object (context.tenantIdin Node.js,context.tenant_idin Python). Must be set at function creation time (cannot be changed later). Expect more cold starts since execution environments are not shared across tenants. All tenants share the function's execution role; for fine-grained per-tenant permissions, propagate tenant-scoped credentials from upstream components
Integration Patterns
API Gateway supports five integration types: AWS, AWS_PROXY, HTTP, HTTP_PROXY, and MOCK. See references/service-integrations.md for detailed configuration of each pattern.
Lambda integrations (AWS_PROXY / AWS), the most common integration type. AWS_PROXY (Lambda proxy) is the recommended default: API Gateway passes the full request to Lambda and returns the Lambda response directly, no mapping templates needed. AWS (Lambda non-proxy) allows VTL request/response transformation but requires more setup.
Direct AWS service integrations: integrate directly with AWS services without Lambda. Two implementation approaches:
REST API and WebSocket API use
Type: AWSwith VTL mapping templates for full request/response transformation. Supports most of AWS services' actionsHTTP API uses first-class integrations (
Type: AWS_PROXYwithIntegrationSubtype) with parameter mapping instead of VTL. Supported services: EventBridge (PutEvents), SQS (SendMessage,ReceiveMessage,DeleteMessage,PurgeQueue), Kinesis (PutRecord), Step Functions (StartExecution,StartSyncExecution,StopExecution), and AppConfig (GetConfiguration). DynamoDB, SNS, and S3 are not available as HTTP API first-class integrations; use Lambda proxy instead
Most commonly used service integrations (REST API Type: AWS can integrate with any AWS service that has an HTTP API; the list below covers the most popular patterns; see references/service-integrations.md for details):
EventBridge: event ingestion
SQS: async message buffering
SNS: fan-out pub/sub to multiple subscribers (REST/WebSocket only)
DynamoDB: full CRUD with optional Streams for async processing (REST/WebSocket only)
Kinesis Data Streams: high-throughput ordered data ingestion
Step Functions: workflow orchestration (sync Express or async Standard).
S3: file upload/download proxy with binary media type support (REST/WebSocket only)
HTTP integrations (HTTP / HTTP_PROXY): proxy to any HTTP endpoint (ALB, NLB, ECS, EC2, on-premises, external APIs). Use VPC Link for private backends. Available on REST and HTTP APIs. API Gateway is a valid choice for east-west (service-to-service) traffic when API management capabilities are needed beyond what load balancing provides (throttling, usage plans, request validation, authentication, and centralized observability). For internal calls that do not need these controls, prefer direct invocation (ALB, service mesh, or Lambda-to-Lambda) for lower latency and cost.
Mock integrations (Type: MOCK): responses without any backend (health checks, CORS preflight, prototyping)
Common patterns across all integrations: IAM execution roles, request validation, response mapping, Lambda sync/async invocation, backend bypass prevention (zero trust), and binary media type handling. Security note for direct service integrations: Use VTL mapping templates and API Gateway request validators. Every field that reaches the AWS service must be explicitly constructed in the mapping template. Never pass user input directly into service parameters without validation. Scope the IAM execution role to minimum required actions and specific resource ARNs (e.g., a single SQS queue, a single DynamoDB table). For S3 integrations, hardcode the bucket and validate key patterns to prevent path traversal.
Hybrid / On-Premises Workloads
Connect API Gateway to on-premises or edge applications:
VPC with connectivity to on-prem (VPN/Direct Connect/Transit Gateway)
NLB/ALB with target group using IP addresses to register on-prem server IPs
VPC Link to the NLB/ALB
API Gateway with
VPC_LINKintegration type
AWS Outposts: Workloads running on Outposts (EC2, ECS, ALB) can also serve as integration targets. Outposts extend the VPC into the on-premises environment, so the same VPC Link + NLB/ALB pattern applies. Register Outposts instance IPs in the NLB target group
Connectivity considerations: This pattern assumes stable, low-latency connectivity to the on-premises location. AWS Direct Connect provides the most reliable path. Site-to-Site VPN connections are inherently less stable; tunnel flaps cause NLB/ALB targets to become unreachable. With default NLB/ALB health check settings (30s interval, 3 failures), there is a ~90-second window where API Gateway sends traffic to unreachable targets, resulting in integration timeouts. Tune NLB health check intervals (10s, 2 failures) and set API Gateway integration timeouts to match your SLA. Implement a /health endpoint on the on-premises target that validates downstream dependencies. Monitor NLB/ALB UnHealthyHostCount and alarm on it
Private API Endpoints (not accessible from the public Internet)
REST API only, accessible via VPC interface endpoint for
execute-apiResource policy must allow access from VPC endpoint or VPC
Deploy VPC endpoints across multiple AZs for high availability
disableExecuteApiEndpoint: trueforces traffic through custom domain only
Private API as External API Proxy
Private APIs can proxy external/third-party APIs for workloads in isolated VPCs (no NAT gateway or internet access needed)
API Gateway is a managed service in an AWS-managed VPC; it has internet connectivity even when your VPC does not
Pattern: Private API (VPC endpoint) -> HTTP_PROXY integration -> external API
Adds centralized logging, throttling, and access control to external API calls
Security warning: This pattern effectively grants internet egress to an isolated VPC through API Gateway. Lock down the HTTP_PROXY integration to specific allowed external domains. Do not use parameterized URLs that callers can control. Apply a resource policy restricting which VPC endpoints can invoke the API. Enable full access logging. This egress path does not appear in VPC flow logs or network firewall logs, so security teams must be aware of it as a potential data exfiltration vector
Private API Cross-Account Access
Pattern 1: VPC endpoint in consumer account + resource policy in producer account allowing
aws:SourceVpce. Combine with IAM authorization (SigV4) or Lambda authorizer for defense in depth. The resource policy controls network-level access, but without authentication any workload in the consumer VPC that can reach the VPC endpoint can invoke the APIPattern 2: PrivateLink between accounts with VPC endpoint
Pattern 3: Transit Gateway connecting VPCs across accounts (one of them with VPC endpoint )
Custom Domains for Private APIs
Private custom domain names (
AWS::ApiGateway::DomainNameV2), dualstack onlyShare cross-account via AWS RAM using domain name access associations
Route 53 private hosted zone with alias record pointing to VPC endpoint regional DNS
Enforcing CloudFront as Sole Entry Point
To prevent clients from bypassing CloudFront and hitting API Gateway directly (skipping WAF, caching, geo-restrictions):
Private API approach: Make the API Gateway endpoint private (VPC endpoint only), place CloudFront in front with VPC Origins: CloudFront → VPC Origin (internal ALB) → execute-api VPC endpoint → private API. All traffic stays within AWS private network and the API is unreachable from the public internet without CloudFront
Regional API + restrictions (defense-in-depth, not a security boundary): Keep a regional endpoint but restrict direct access. Use a custom header from CloudFront (via origin custom headers) and validate it in a Lambda authorizer. Combine with disabling the default
execute-apiendpoint to force traffic through the custom domain fronted by CloudFront. Caveat: The header value is a static secret. If leaked through logs, source code, or developer machines, attackers can bypass CloudFront. Rotate the value regularly, store it in AWS Secrets Manager, and treat it as a credential.
On-Premises Access to Private APIs
AWS Direct Connect or Site-to-Site VPN to reach VPC with VPC endpoint
Route 53 Resolver inbound endpoints for on-premises DNS resolution of VPC endpoint DNS names or private custom domain
VPC Links
VPC Links enable API Gateway to reach private integration targets inside a VPC that are not publicly accessible. API Gateway creates a private connection to the VPC without exposing the backend to the internet.
VPC Link v2 (
AWS::ApiGatewayV2::VpcLink): Supported by REST and HTTP APIs, targets ALB, NLB, and Cloud Map (for HTTP APIs) services. One VPC link per VPC can serve multiple backends. Prefer v2 for new integrationsVPC Link v1 (
AWS::ApiGateway::VpcLink): Used by WebSocket API (and legacy REST API integrations), targets NLB onlyNot the same as private endpoints: A private API endpoint restricts who can call the API (only from within a VPC via
execute-apiVPC endpoint). A VPC Link controls where the API forwards requests to (private backends in a VPC). These are independent: a public API can use VPC Links to reach private backends, and a private API can call public HTTP endpoints without VPC Links
Multi-Region
Foundational Setup
API Gateway custom domain names are regional resources. Create the same custom domain name (e.g.,
api.example.com) independently in each regionEach region requires its own ACM certificate for the domain. ACM certificates are also regional. Request or import in every region where the API is deployed
Route 53 alias records point to each region's API Gateway regional domain name (the
d-xxxxxx.execute-api.{region}.amazonaws.comtarget provided when creating the custom domain)Deploy the full stack (API Gateway, Lambda, DynamoDB, etc.) independently per region; there is no cross-region replication of API Gateway configuration
Use IaC (SAM/CDK/Terraform) with parameterized region to ensure consistent deployments across regions
Active-Passive Failover
Route 53 failover routing policy with health checks on the primary region
Health checks monitor a
/healthendpoint or a CloudWatch alarm (e.g., on 5XX error rate or backend availability)On primary failure, Route 53 automatically routes all traffic to the secondary region
Route 53 Application Recovery Controller (ARC) for manual failover switches when automated routing is insufficient (e.g., data corruption in one region)
RPO/RTO trade-off: Health check interval (10s or 30s) + failover propagation (~60-120s DNS TTL) determines theoretical failover speed. In practice, plan for 3-10 minutes, as many clients cache DNS aggressively beyond TTL (Java caches successful lookups indefinitely by default, mobile SDKs and corporate resolvers vary). Set Route 53 record TTL to 60s, but do not size SLAs around sub-minute failover. For faster failover, use Global Accelerator (anycast IP, no DNS propagation delay) or CloudFront with origin failover (seconds, not minutes)
Active-Active
Route 53 latency-based or geo-based routing to nearest region
All regions serve traffic simultaneously; both must be fully provisioned, not just on standby
Data sovereignty: Latency-based routing may route EU users to US regions (or vice versa) if latency is lower, potentially violating GDPR or other data residency requirements. Use geo-based routing (combined with tenant locality verification) when data sovereignty is a concern. Note that DynamoDB Global Tables replicate data to all configured regions regardless of routing, so do not add regions that would violate data residency constraints
Resilient Private APIs (Multi-Region)
Private API in each region + VPC endpoint + Custom Domain Name
Route 53 private hosted zone with latency-based or failover routing
Transit Gateway with inter-Region peering for VPC connectivity
Health checks must be CloudWatch alarm-based: Route 53 health checkers run from the public internet and cannot reach private API endpoints. Create CloudWatch alarms on NLB
UnHealthyHostCount, API Gateway5XXErrorrate, or custom health metrics, then associate them with Route 53 health checks. Monitor Transit Gateway peering status separately; if inter-region peering fails, failover routing becomes critical
Response Streaming
Still a request/response pattern: client sends a request and receives a streamed response. The connection is one-directional (server to client) and closes when the response completes. For bidirectional real-time communication, use WebSocket API (see
references/websocket.md)REST API only; not available for HTTP API or WebSocket API
Set
responseTransferMode: "STREAM"on integrationSupports HTTP_PROXY, Lambda proxy, and private integrations (ALB/NLB/Cloud Map backends via VPC Link)
Lambda integrations: Use
awslambda.streamifyResponse()andHttpResponseStream.from()HTTP integrations: Backend sends a chunked transfer-encoded response (
Transfer-Encoding: chunked); API Gateway streams chunks to the client as they arrive, with no Lambda requiredFirst 10 MB unrestricted; beyond 10 MB bandwidth limited to 2 MB/s
Max streaming session: 15 minutes, removing the 10 MB buffered response limit
Idle timeouts: 5 min (Regional/Private), 30 sec (edge-optimized)
Billing: each 10 MB of response (rounded up) = 1 request
Limitations: No VTL response transformation, no caching, no content encoding with streaming
Key use cases: LLM chatbot implementations that stream sentence-by-sentence for better UX; large payload delivery beyond the 10 MB buffered response limit (up to 15 minutes of streaming); real-time data feeds (logs, metrics, event streams) where partial results are useful before the full response completes; file downloads from backend services where the client can begin processing immediately
Designing APIs for AI Agent Consumption
As AI agents become API consumers, design considerations change:
Rich documentation: API descriptions must be detailed enough for LLMs to understand intent, not just for humans
Descriptive error messages: AI agents need enough context in error responses to retry with corrective information
Minimize round-trips: Consider how many requests are needed to perform one action. Batch operations and intent-based APIs (e.g., "manage user" vs. separate GET/PUT/DELETE) reduce agent complexity
Machine-friendly pagination: Use cursor-based pagination that machine consumers can follow automatically
Resource-based vs intent-based: Consider whether traditional CRUD or intent-based endpoints better serve AI consumers
Non-deterministic cost: AI-backed APIs have variable processing cost per request (LLM token usage varies). Factor this into monetization and usage plan design
Reducing Backend Load
Request validation at the front door: Use API Gateway validators (headers, query strings, JSON schema) to reject bad requests before they reach the backend
WAF rules: Block traffic from regions with no customers
Add pagination and filters: Reduce response data volume
Batch operations: Combine multiple small actions into single requests
Async processing: Acknowledge request immediately, queue for backend processing at its own pace. Better for constrained backend resources
Caching strategy: Use CloudFront caching first (reduces load, latency, AND cost, since the request never reaches API Gateway). Use API Gateway cache as fallback (reduces load and latency but NOT cost, as the request is still counted by API Gateway). See
references/performance-scaling.mdfor cache sizing, TTL configuration, and multi-layer caching details
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