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/service-integrations.md
AWS Service Integrations
API Gateway integrates 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 any AWS service action. Both synchronous (wait for response) and asynchronous (fire-and-forget) patternsHTTP API: Uses first-class integrations (
Type: AWS_PROXYwithIntegrationSubtype) and parameter mapping instead of VTL. Supported subtypes:EventBridge-PutEvents,SQS-SendMessage,SQS-ReceiveMessage,SQS-DeleteMessage,SQS-PurgeQueue,Kinesis-PutRecord,StepFunctions-StartExecution,StepFunctions-StartSyncExecution,StepFunctions-StopExecution,AppConfig-GetConfiguration. For services not in this list (DynamoDB, SNS, S3), use Lambda proxy instead. See Integration subtype reference
The patterns below cover the most commonly used service integrations. REST API Type: AWS can integrate with any AWS service that exposes an HTTP API; the same approach (URI, IAM role, VTL mapping) applies to services not listed here. For HTTP API first-class integrations, the same services apply but use parameter mapping ($request.body, $request.header, $request.path, $context) instead of VTL.
EventBridge Integration
Integrates directly with EventBridge PutEvents API (see aws-samples/serverless-patterns/apigw-rest-api-eventbridge-sam). For a complete SAM template, see SAM Service Integration Templates — EventBridge.
Use
Type: AWSintegration with URIarn:aws:apigateway:{region}:events:action/PutEventsSet required headers via
RequestParameters(e.g.,integration.request.header.X-Amz-Target: "'AWSEvents.PutEvents'",integration.request.header.Content-Type: "'application/x-amz-json-1.1'"). Alternative: set via VTL$context.requestOverride.headerin the mapping template, but avoid applying the same header in both places (double-application causes 5XX)VTL mapping template transforms HTTP requests into EventBridge events. Use
#foreachto batch multiple events from a single API callInput escaping: Use
$util.escapeJavaScript($elem.Detail).replaceAll("\\'","'"), sinceescapeJavaScriptover-escapes single quotes which breaks JSON; thereplaceAllcorrects thisSupports custom event buses (not just default); pass bus name via
!Subin the mapping templateLambda authorizer can return
custom:clientIdto enrich events with caller identityRequest validation via API Gateway models
Use
PassthroughBehavior: NEVERorWHEN_NO_TEMPLATESto reject unmatched content types. Avoid the defaultWHEN_NO_MATCHwhich passes malformed payloads through to the backend serviceEventBridge rules route events to Kinesis Data Firehose, Lambda, or API destinations
Gotcha: EventBridge does not add newlines between records when forwarding to Firehose; use
\nin InputTemplateGotcha:
PutEventscan succeed (200) withFailedEntryCount > 0(partial failures are silent). Check$input.path('$.FailedEntryCount')in the response template and return an error status if non-zero
SQS Integration (Async Buffer)
Integrates directly with SQS SendMessage API to decouple producers from consumers (see aws-samples/serverless-patterns/apigw-sqs-lambda-iot). For a complete SAM template, see SAM Service Integration Templates — SQS.
Use
Type: AWSintegration with URIarn:aws:apigateway:{region}:sqs:path/{account-id}/{queue-name}Two protocol options:
AWS query protocol: Set
Content-Type: 'application/x-www-form-urlencoded'header in integration request. Mapping template:Action=SendMessage&MessageBody=$util.urlEncode($input.body)AWS JSON protocol: Set
Content-Type: 'application/x-amz-json-1.0'andX-Amz-Target: 'AmazonSQS.SendMessage'headers. Pass JSON body withQueueUrlandMessageBody
Set
PassthroughBehavior: NEVERto reject requests that don't match any mapping template (returns 415 Unsupported Media Type)Always use
$util.urlEncode()with the query protocol; special characters in the message body causeAccessDeniederrors without encodingFIFO queues: Append
MessageGroupIdto the mapping template:Action=SendMessage&MessageGroupId=$context.extendedRequestId&MessageBody=$util.urlEncode($input.body). Enable content-based deduplication on the queue, or addMessageDeduplicationIdexplicitlyKMS-encrypted queues: IAM execution role needs
kms:GenerateDataKeyandkms:Decrypton the queue's KMS key, otherwiseKMS.AccessDeniedExceptionLambda consumer processes messages from SQS at its own pace, with built-in retry and DLQ support
SNS Integration (Fan-Out / Pub-Sub)
Integrates directly with SNS Publish API for fan-out to multiple subscribers (see aws-samples/serverless-patterns/apigw-websocket-api-sns):
Use
Type: AWSintegration with URIarn:aws:apigateway:{region}:sns:action/PublishUses AWS query protocol: Set
Content-Type: 'application/x-www-form-urlencoded'header in integration requestVTL mapping template:
Action=Publish&TopicArn=$util.urlEncode("${TopicArn}")&Message=$util.urlEncode(...); always URL-encode both the TopicArn and MessageEnrich messages with API Gateway context:
$context.connectionId(WebSocket),$context.requestTimeEpoch,$context.identity.sourceIpRequest validation: Use API Gateway models to validate the message body before publishing, ensuring only well-formed messages reach SNS
Subscribers receive messages independently: Lambda, SQS, HTTP/S endpoints, email, SMS. One API call fans out to all
KMS-encrypted topics: IAM execution role needs
kms:GenerateDataKeyandkms:Decrypton the topic's KMS keyMessage attributes: Use indexed query parameters for subscription filter policies:
MessageAttributes.entry.1.Name=eventType&MessageAttributes.entry.1.Value.DataType=String&MessageAttributes.entry.1.Value.StringValue=.... Required for SNS subscription filtering in fan-out architecturesFIFO topics: Append
MessageGroupId(required) and optionallyMessageDeduplicationIdto the mapping template, same pattern as SQS FIFO queuesIAM execution role needs
sns:Publishscoped to the specific topic ARN
DynamoDB Integration (Write-Through with Streams)
Integrates directly with DynamoDB APIs for full CRUD without Lambda. For complete SAM templates (OpenAPI-based and inline), see SAM Service Integration Templates — DynamoDB Full CRUD.
Use
Type: AWSintegration with URIarn:aws:apigateway:{region}:dynamodb:action/{action}(supportsGetItem,PutItem,UpdateItem,DeleteItem,Query, andScan)VTL mapping template transforms HTTP request into DynamoDB JSON format:
Request template: Maps request body/parameters to DynamoDB item attributes with type descriptors (
S,N,M,L, etc.)Response template: Extracts DynamoDB response attributes into clean JSON for the client using
$input.path('$.Item.attribute.S')
Full CRUD pattern (see aws-samples/serverless-patterns/apigw-dynamodb-lambda-scheduler-ses-auto-deletion-sam):
Create: Use
UpdateItem(notPutItem) with$context.requestIdas auto-generated ID, eliminating client-side ID generation. SetReturnValues: ALL_NEWto return the created item in the responseRead:
GetItemwith key from path parameter$input.params().path.idUpdate:
UpdateItemwithUpdateExpressionandExpressionAttributeValuesmapped from request body. UseReturnValues: ALL_NEWto return the updated itemDelete:
DeleteItemwithReturnValues: ALL_OLDto return the deleted item for confirmationList:
Scanwith#foreachloop in response template to build JSON array from$inputRoot.Items. Always include aLimitparameter in the Scan template (e.g.,"Limit": 25) to cap items per request; without it, a single API call can scan the entire table, consuming all provisioned capacity. Support pagination viaExclusiveStartKeymapped from a query parameter
Request validation: Use
x-amazon-apigateway-request-validatorwith OpenAPI schemas to validate request bodies at the gateway before reaching DynamoDBOpenAPI-based definition: Define the full API in a separate OpenAPI file and include via
AWS::Includetransform in the SAM template, keeping the API definition clean and separates API spec from infrastructureFor async event processing, enable DynamoDB Streams on the table:
Stream triggers Lambda function on every insert/update/delete
Lambda processes changes asynchronously (enrichment, notifications, scheduling, cross-service sync)
Example chain: API Gateway → DynamoDB (Streams) → Lambda → EventBridge Scheduler → SES for scheduled email reminders
Stream view type options:
KEYS_ONLY,NEW_IMAGE,OLD_IMAGE,NEW_AND_OLD_IMAGES; choose based on what the processor needs
Gotcha: DynamoDB reserved keywords (
datetime,email,status,name,type,data, etc.) requireExpressionAttributeNameswith#placeholdersyntax. This applies in VTL templates too, not just SDK callsSecurity: Never interpolate request input into DynamoDB expression strings (
UpdateExpression,FilterExpression,ProjectionExpression). Hardcode expression structures in VTL and only map user input intoExpressionAttributeValues(:placeholdervalues). Interpolating into expressions allows callers to inject additional clauses that expose unintended attributes or modify other itemsCanary deployments for DynamoDB service integrations are managed at the API Gateway stage level (no Lambda alias to canary)
Kinesis Data Streams Integration (High-Throughput Ingestion)
Integrates directly with Kinesis Data Streams PutRecord/PutRecords APIs for high-volume data ingestion (see aws-samples/serverless-patterns/apigw-kinesis-lambda). For a complete SAM template, see SAM Service Integration Templates — Kinesis Data Streams.
Use
Type: AWSintegration with URIarn:aws:apigateway:{region}:kinesis:action/{action}(e.g.,action/PutRecord,action/PutRecords)Use
PassthroughBehavior: WHEN_NO_TEMPLATESto ensure requests are only accepted when a matching mapping template existsVTL mapping template constructs the Kinesis payload:
StreamName: Target stream; can be hardcoded via!Subor dynamic via path parameter ($input.params('stream-name'))Data: Base64-encoded record data. Use$util.base64Encode()in VTL. Encode the full body ($input.body) or a specific JSON field ($input.json('$.Data'))PartitionKey: Determines shard placement. Use a high-cardinality value from the request body (e.g., client ID) for even distribution across shards, or$context.requestIdas a simple default for uniform distribution
PutRecords for batching: VTL
#foreachloop transforms an array of items in the request body into multiple Kinesis records in a single API call, reducing round-tripsKMS-encrypted streams: IAM execution role needs
kms:GenerateDataKeyandkms:Decrypton the stream's KMS keyDownstream consumers: Lambda (event source mapping), Kinesis Data Firehose (delivery to S3/Redshift/OpenSearch), Kinesis Data Analytics, or custom KCL applications
Shard limits: Each shard supports 1,000 records/s or 1 MB/s for writes and 2 MB/s for reads. Plan shard count based on expected ingestion rate. Use on-demand capacity mode to auto-scale shards
Gotcha:
PutRecordresponse includesShardIdandSequenceNumber; map these in the response template for client-side tracking if neededGotcha:
PutRecordscan succeed (200) withFailedRecordCount > 0. Map$input.path('$.FailedRecordCount')in the response template so clients know to retry failed records
Step Functions Integration (Workflow Orchestration)
Integrates directly with Step Functions to orchestrate multi-step workflows without Lambda glue code. For complete SAM templates (REST and WebSocket), see SAM Service Integration Templates — Step Functions.
REST API → Step Functions (see aws-samples/serverless-patterns/apigw-rest-stepfunction):
Two execution modes available:
Asynchronous (Standard workflow):
action/StartExecution, which returns execution ARN immediately. Client does not wait for workflow completion. IAM role needsstates:StartExecutionSynchronous (Express workflow):
action/StartSyncExecution, which waits for workflow to complete and returns the result in the response. IAM role needsstates:StartSyncExecution. Must complete within the API Gateway integration timeout (29s default, up to 300s for Regional/Private)
VTL mapping template passes the request body as workflow input and the state machine ARN:
#set($data = $util.escapeJavaScript($input.json('$')).replaceAll("\\'","'")) { "input": "$data", "stateMachineArn": "${StateMachineArn}" }
WebSocket API → Step Functions (see aws-samples/serverless-samples/apigw-ws-integrations):
Two execution modes via custom routes matched by
routeSelectionExpression:Synchronous (Express workflow):
action/StartSyncExecution, which waits for workflow to complete and returns the result directly to the WebSocket client. Constrained by the 29-second WebSocket API integration timeout, not the 5-minute Express workflow maximum. Workflows exceeding 29 seconds will time out at the API Gateway level. Use for short-lived workflows where the client needs the result immediatelyAsynchronous (Standard workflow):
action/StartExecution, which returns the execution ARN immediately. Workflow pushes results back to the WebSocket client via the@connectionsManagement API (POST https://{api-id}.execute-api.{region}.amazonaws.com/{stage}/@connections/{connectionId}) using an HTTP task state or Lambda task. Pass$context.connectionIdin the input so the workflow knows which client to notify
VTL escaping for WebSocket:
$util.escapeJavaScript($input.json("$.data")).replaceAll("\\'","'")(thereplaceAllhandles single quotes thatescapeJavaScriptover-escapes)WebSocket
$connect/$disconnectroutes can use direct DynamoDB integration (PutItem/DeleteItem) for connection tracking without LambdaIAM roles:
states:StartSyncExecutionfor Express,states:StartExecutionfor Standard. Async workflow role also needsexecute-api:ManageConnectionsto call back the WebSocket client
Express vs Standard workflows:
Express (sync): Max 5 minutes, at-least-once execution, lower cost for high-volume short tasks. Good for synchronous REST/WebSocket responses within the API Gateway timeout
Standard (async): Max 1 year, exactly-once execution, full execution history. Good for long-running orchestrations that push results via callback, webhook, or polling
Lambda durable functions as alternative: Durable functions are invoked as regular Lambda integrations (proxy or custom) — no Type: AWS service integration or VTL needed. See the aws-lambda-durable-functions skill for details.
S3 Integration (File Storage Proxy)
Acts as an S3 proxy for file upload, download, and listing without Lambda (see Developer Guide tutorial):
Use
Type: AWSintegration withAction type: Use path override. API Gateway forwards requests to S3 REST API path-style (s3-host-name/{bucket}/{key})Resource structure:
/{folder}maps to S3 bucket,/{folder}/{item}maps to S3 object. Map path parameters in integration request:method.request.path.folder→{bucket},method.request.path.item→{object}Operations: GET on
/lists buckets, GET on/{folder}lists objects in a bucket, GET on/{folder}/{item}downloads an object, PUT on/{folder}/{item}uploads an objectBinary files (images, PDFs, etc.): Register media types in
binaryMediaTypes(e.g.,image/png), addAccept(download) andContent-Type(upload) headers to the method request, leavecontentHandlingunset (passthrough behavior); no mapping template for binary content typesPayload limit: 10 MB max through API Gateway. For larger files, generate S3 presigned URLs via Lambda and have the client upload/download directly to S3 (presigned URLs cannot be generated from a direct service integration; Lambda is required)
Response header mapping: Map
integration.response.header.Content-Type,integration.response.header.Content-Length, andintegration.response.header.Dateto method response headers for proper content deliveryS3 objects with
/or special characters in the key must be URL-encoded in the request path (e.g.,test/test.txt→test%2Ftest.txt)IAM execution role needs S3 permissions (
s3:GetObject,s3:PutObject,s3:ListBucket) scoped to the specific bucket(s)
HTTP Integration (Proxy to HTTP Endpoints)
Forwards requests to any HTTP-accessible endpoint: ALB, NLB, ECS, EC2, on-premises servers, or external third-party APIs:
Two modes:
HTTP_PROXY: Passes request through to the backend as-is and returns the backend response directly to the client. Minimal configuration, no VTL templates. Available on both REST and HTTP APIsHTTP(non-proxy): Allows VTL mapping templates to transform request and response. REST API only
VPC Link for private backends: Use
connectionType: VPC_LINKto reach ALB, NLB, or Cloud Map services inside a VPC without exposing them to the internet. VPC Link v2 supports REST and HTTP APIs (targets ALB and NLB); WebSocket API uses VPC Link v1 (NLB only)Path and parameter passthrough: Map URL path parameters, query strings, and headers from the method request to the integration request. Use
{proxy+}greedy path parameter for catch-all routingTLS to backend: API Gateway validates the backend's TLS certificate by default. If the backend uses a self-signed or private CA certificate, set
insecureSkipVerification: trueon the integration (testing/development only; not recommended for production). Provide the full certificate chain on the backend for proper validationTimeouts: Configure
timeoutInMillison the integration (50ms–29s for REST, 30s hard limit for HTTP API). For backends that may exceed this, consider async patternsConnection reuse: API Gateway reuses connections to HTTP backends by default for lower latency on subsequent requests
No automatic retries: API Gateway does not retry failed HTTP integration requests. If the backend returns 5xx or the connection times out, the error is returned directly to the client. Implement retry logic on the client side or use SQS as a buffer
Mock Integration (No Backend)
Returns responses directly from API Gateway without calling any backend:
Use
Type: MOCK(no integration URI, no IAM role, no backend needed)Health check endpoints: Return 200 on
/healthfor load balancer or monitoring checksCORS preflight: Handle
OPTIONSrequests with appropriate CORS headers without invoking LambdaAPI prototyping: Define request/response contracts before backends are built. Consumers can develop against the mock
Static responses: Return fixed JSON/XML based on request parameters using VTL mapping templates
VTL request template must return
{"statusCode": 200}(or appropriate code) to set the integration response statusMap different status codes using
IntegrationResponseswith selection patterns
Common Patterns
IAM execution role: Every direct service integration requires an IAM role with the specific action permission (e.g.,
sqs:SendMessage,dynamodb:PutItem,events:PutEvents,kinesis:PutRecord,states:StartExecution). Pass the role ARN in the integrationCredentialsfieldRequest validation at the gateway: Use API Gateway request validators (models) to reject invalid requests before they reach the backend service, reducing cost and protects downstream services
Response mapping: Transform raw AWS service responses into clean API responses using VTL response templates. Map HTTP status codes for error cases in
IntegrationResponsesLambda invocations support sync and async: API Gateway Lambda integrations default to synchronous invocation (wait for response). For asynchronous invocation (fire-and-forget, returns 200 immediately while Lambda processes in background), set
X-Amz-Invocation-Type: 'Event'in the integration request HTTP headers (see re:Post guide). Async invocation supports Lambda's built-in retry (up to 2 retries) and dead-letter queues. REST API supports this natively via non-proxy integration; HTTP API only supports proxy integrations for Lambda soX-Amz-Invocation-Typecannot be set — use a proxy Lambda that invokes the target Lambda asynchronously via the SDKPrevent backend bypass (zero trust): Ensure backends can only be reached through API Gateway, not invoked or accessed directly. Apply defense in depth per integration type:
Lambda: Restrict Lambda resource policies to allow invocations only from the API Gateway source ARN
VPC Link targets (ALB/NLB): Use security groups on the load balancer to accept traffic only from the VPC Link's ENIs, not from arbitrary sources
HTTP integrations: Use mutual TLS, API keys, or signed requests between API Gateway and the backend to authenticate the caller
Direct service integrations (SQS, DynamoDB, etc.): The IAM execution role scopes access — ensure the role is only assumable by API Gateway (
apigateway.amazonaws.comprincipal) and follows least-privilege for the specific resources
Parameter overriding (REST API): Override request/response parameters and status codes at method level:
RequestParametersin Integration: Map method request values to integration request valuesResponseParametersin IntegrationResponses: Map integration response values to method response valuesOverride response status:
#set($context.responseOverride.status = 400)in VTLOverride request headers:
$context.requestOverride.header.<name>Gotcha: Applying override to same parameter twice causes 5XX. Build in a variable first, apply at end
Binary media types: API Gateway request and response payloads can be text or binary (JPEG, GZip, XML, PDF, etc.). Configure
binaryMediaTypeson the API, specifying content types treated as binary (e.g.,image/png,application/octet-stream). Avoid*/*wildcard: it treats ALL responses as binary, breaking Lambda proxy integrations that return JSON:Lambda proxy integrations: Lambda must return the response body as base64-encoded and set
isBase64Encoded: true. The API must have matchingbinaryMediaTypesconfigured. Client sendsAcceptheader matching a binary media typeNon-proxy integrations: Set
binaryMediaTypeson the API, or usecontentHandlingon theIntegrationandIntegrationResponseresources:CONVERT_TO_BINARY(base64-decode text to binary),CONVERT_TO_TEXT(base64-encode binary to text), or undefined (passthrough)
Local testing limitation:
sam local start-apidoes not supportType: AWSservice integrations; it only supports Lambda proxy/non-proxy integrations. Test direct service integrations by deploying to a dev stage and using the API Gateway test console (AWS Console → method → Test) to validate VTL mapping templates against sample requests without a full deployment cycle
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