{"id":"api-gateway","name":"api-gateway","summary":"REST および HTTP API 管理のための AWS API Gateway です。APIの作成、統合の設定、認可の設定、ステージ管理、レート制限の実装、APIの問題トラブルシューティングの際に活用してください。","body":"# AWS API Gateway\n\nAmazon API Gateway is a fully managed service for creating, publishing, and securing APIs at any scale. Supports REST APIs, HTTP APIs, and WebSocket APIs.\n\n## Table of Contents\n\n- [Core Concepts](#core-concepts)\n- [Common Patterns](#common-patterns)\n- [CLI Reference](#cli-reference)\n- [Best Practices](#best-practices)\n- [Troubleshooting](#troubleshooting)\n- [References](#references)\n\n## Core Concepts\n\n### API Types\n\n| Type | Description | Use Case |\n|------|-------------|----------|\n| **HTTP API** | Low-latency, cost-effective | Simple APIs, Lambda proxy |\n| **REST API** | Full-featured, more control | Complex APIs, transformation |\n| **WebSocket API** | Bidirectional communication | Real-time apps, chat |\n\n### Key Components\n\n- **Resources**: URL paths (/users, /orders/{id})\n- **Methods**: HTTP verbs (GET, POST, PUT, DELETE)\n- **Integrations**: Backend connections (Lambda, HTTP, AWS services)\n- **Stages**: Deployment environments (dev, prod)\n\n### Integration Types\n\n| Type | Description |\n|------|-------------|\n| **Lambda Proxy** | Pass-through to Lambda (recommended) |\n| **Lambda Custom** | Transform request/response |\n| **HTTP Proxy** | Pass-through to HTTP endpoint |\n| **AWS Service** | Direct integration with AWS services |\n| **Mock** | Return static response |\n\n## Common Patterns\n\n### Create HTTP API with Lambda\n\n**AWS CLI:**\n\n```bash\n# Create HTTP API\naws apigatewayv2 create-api \\\n  --name my-api \\\n  --protocol-type HTTP \\\n  --target arn:aws:lambda:us-east-1:123456789012:function:MyFunction\n\n# Get API endpoint\naws apigatewayv2 get-api --api-id abc123 --query 'ApiEndpoint'\n```\n\n**SAM Template:**\n\n```yaml\nAWSTemplateFormatVersion: '2010-09-09'\nTransform: AWS::Serverless-2016-10-31\n\nResources:\n  MyApi:\n    Type: AWS::Serverless::HttpApi\n    Properties:\n      StageName: prod\n\n  MyFunction:\n    Type: AWS::Serverless::Function\n    Properties:\n      Handler: app.handler\n      Runtime: python3.12\n      Events:\n        ApiEvent:\n          Type: HttpApi\n          Properties:\n            ApiId: !Ref MyApi\n            Path: /items\n            Method: GET\n```\n\n### Create REST API with Lambda Proxy\n\n```bash\n# Create REST API\naws apigateway create-rest-api \\\n  --name my-rest-api \\\n  --endpoint-configuration types=REGIONAL\n\nAPI_ID=abc123\n\n# Get root resource ID\nROOT_ID=$(aws apigateway get-resources --rest-api-id $API_ID --query 'items[0].id' --output text)\n\n# Create resource\naws apigateway create-resource \\\n  --rest-api-id $API_ID \\\n  --parent-id $ROOT_ID \\\n  --path-part items\n\nRESOURCE_ID=xyz789\n\n# Create method\naws apigateway put-method \\\n  --rest-api-id $API_ID \\\n  --resource-id $RESOURCE_ID \\\n  --http-method GET \\\n  --authorization-type NONE\n\n# Create Lambda integration\naws apigateway put-integration \\\n  --rest-api-id $API_ID \\\n  --resource-id $RESOURCE_ID \\\n  --http-method GET \\\n  --type AWS_PROXY \\\n  --integration-http-method POST \\\n  --uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:MyFunction/invocations\n\n# Deploy to stage\naws apigateway create-deployment \\\n  --rest-api-id $API_ID \\\n  --stage-name prod\n```\n\n### Lambda Handler for API Gateway\n\n```python\nimport json\n\ndef handler(event, context):\n    # HTTP API event\n    http_method = event.get('requestContext', {}).get('http', {}).get('method')\n    path = event.get('rawPath', '')\n    query_params = event.get('queryStringParameters', {})\n    body = event.get('body', '')\n\n    if body and event.get('isBase64Encoded'):\n        import base64\n        body = base64.b64decode(body).decode('utf-8')\n\n    # Process request\n    response_body = {'message': 'Success', 'path': path}\n\n    return {\n        'statusCode': 200,\n        'headers': {\n            'Content-Type': 'application/json'\n        },\n        'body': json.dumps(response_body)\n    }\n```\n\n### Configure CORS\n\n**HTTP API:**\n\n```bash\naws apigatewayv2 update-api \\\n  --api-id abc123 \\\n  --cors-configuration '{\n    \"AllowOrigins\": [\"https://example.com\"],\n    \"AllowMethods\": [\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n    \"AllowHeaders\": [\"Content-Type\", \"Authorization\"],\n    \"MaxAge\": 86400\n  }'\n```\n\n**REST API:**\n\n```bash\n# Enable CORS on resource\naws apigateway put-method \\\n  --rest-api-id $API_ID \\\n  --resource-id $RESOURCE_ID \\\n  --http-method OPTIONS \\\n  --authorization-type NONE\n\naws apigateway put-integration \\\n  --rest-api-id $API_ID \\\n  --resource-id $RESOURCE_ID \\\n  --http-method OPTIONS \\\n  --type MOCK \\\n  --request-templates '{\"application/json\": \"{\\\"statusCode\\\": 200}\"}'\n\naws apigateway put-method-response \\\n  --rest-api-id $API_ID \\\n  --resource-id $RESOURCE_ID \\\n  --http-method OPTIONS \\\n  --status-code 200 \\\n  --response-parameters '{\n    \"method.response.header.Access-Control-Allow-Headers\": true,\n    \"method.response.header.Access-Control-Allow-Methods\": true,\n    \"method.response.header.Access-Control-Allow-Origin\": true\n  }'\n\naws apigateway put-integration-response \\\n  --rest-api-id $API_ID \\\n  --resource-id $RESOURCE_ID \\\n  --http-method OPTIONS \\\n  --status-code 200 \\\n  --response-parameters '{\n    \"method.response.header.Access-Control-Allow-Headers\": \"'\\''Content-Type,Authorization'\\''\",\n    \"method.response.header.Access-Control-Allow-Methods\": \"'\\''GET,POST,PUT,DELETE,OPTIONS'\\''\",\n    \"method.response.header.Access-Control-Allow-Origin\": \"'\\''*'\\''\"\n  }'\n```\n\n### JWT Authorization (HTTP API)\n\n```bash\naws apigatewayv2 create-authorizer \\\n  --api-id abc123 \\\n  --name jwt-authorizer \\\n  --authorizer-type JWT \\\n  --identity-source '$request.header.Authorization' \\\n  --jwt-configuration '{\n    \"Issuer\": \"https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123\",\n    \"Audience\": [\"client-id\"]\n  }'\n```\n\n## CLI Reference\n\n### HTTP API (apigatewayv2)\n\n| Command | Description |\n|---------|-------------|\n| `aws apigatewayv2 create-api` | Create API |\n| `aws apigatewayv2 get-apis` | List APIs |\n| `aws apigatewayv2 create-route` | Create route |\n| `aws apigatewayv2 create-integration` | Create integration |\n| `aws apigatewayv2 create-stage` | Create stage |\n| `aws apigatewayv2 create-authorizer` | Create authorizer |\n\n### REST API (apigateway)\n\n| Command | Description |\n|---------|-------------|\n| `aws apigateway create-rest-api` | Create API |\n| `aws apigateway get-rest-apis` | List APIs |\n| `aws apigateway create-resource` | Create resource |\n| `aws apigateway put-method` | Create method |\n| `aws apigateway put-integration` | Create integration |\n| `aws apigateway create-deployment` | Deploy API |\n\n## Best Practices\n\n### Performance\n\n- **Use HTTP APIs** for simple use cases (70% cheaper, lower latency)\n- **Enable caching** for REST APIs\n- **Use regional endpoints** unless global distribution needed\n- **Implement pagination** for list endpoints\n\n### Security\n\n- **Use authorization** on all endpoints\n- **Enable WAF** for REST APIs\n- **Use API keys** for rate limiting (not authentication)\n- **Enable access logging**\n- **Use HTTPS only**\n\n### Reliability\n\n- **Set up throttling** to protect backends\n- **Configure timeout** appropriately\n- **Use canary deployments** for updates\n- **Monitor with CloudWatch**\n\n## Troubleshooting\n\n### 403 Forbidden\n\n**Causes:**\n- Missing authorization\n- Invalid API key\n- WAF blocking\n- Resource policy denying\n\n**Debug:**\n\n```bash\n# Check API key\naws apigateway get-api-key --api-key abc123 --include-value\n\n# Check authorizer\naws apigatewayv2 get-authorizer --api-id abc123 --authorizer-id xyz789\n```\n\n### 502 Bad Gateway\n\n**Causes:**\n- Lambda error\n- Integration timeout\n- Invalid response format\n\n**Lambda response format:**\n\n```python\n# Correct format\nreturn {\n    'statusCode': 200,\n    'headers': {'Content-Type': 'application/json'},\n    'body': json.dumps({'message': 'success'})\n}\n\n# Wrong - missing statusCode\nreturn {'message': 'success'}\n```\n\n### 504 Gateway Timeout\n\n**Causes:**\n- Backend timeout (Lambda max 29 seconds for REST API)\n- Integration timeout too short\n\n**Solutions:**\n- Increase Lambda timeout\n- Use async processing for long operations\n- Increase integration timeout (max 29s for REST, 30s for HTTP)\n\n### CORS Errors\n\n**Debug:**\n- Check OPTIONS method exists\n- Verify headers in response\n- Check origin matches allowed origins\n\n## References\n\n- [API Gateway Developer Guide](https://docs.aws.amazon.com/apigateway/latest/developerguide/)\n- [API Gateway REST API Reference](https://docs.aws.amazon.com/apigateway/latest/api/)\n- [API Gateway CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/apigateway/)\n- [boto3 API Gateway](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/apigateway.html)","author":"@itsmostafa","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/api-gateway","license":"MIT","category":null,"lang":"en","tokens":2214,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"integration-patterns.md","size":9246,"sha256":"7cd0d0e09b43b4cd4943a11a34299e7d2765b5ecabaa626e9b3bb1c6a12336bd"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["api.example.com","boto3.amazonaws.com","cognito-idp.us-east-1.amazonaws.com","docs.aws.amazon.com","my-nlb.internal"]}}