AWS API Gateway
Create, publish, maintain, monitor, and secure APIs at any scale
Amazon API Gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs.
API Gateway Types
Choose the right API type based on your use case. HTTP APIs are ~70% cheaper but have fewer features.
API Types
| Type | Use Case | Features |
|---|---|---|
| REST API | Traditional REST APIs | Full feature set, caching, WAF |
| HTTP API | Simple HTTP APIs | Lower cost, faster, simpler |
| WebSocket API | Real-time communication | Two-way communication |
Request Flow Architecture
Key Concepts
Resources and Methods
APIs are organized as resources (paths) with methods (HTTP verbs).
/users GET → List users
/users POST → Create user
/users/{id} GET → Get user
/users/{id} PUT → Update user
/users/{id} DELETE → Delete userStages
Deployment environments for your API:
dev- Developmentstaging- Testingprod- Production
Integrations
Connect API methods to backend services:
| Type | Description |
|---|---|
| Lambda | Invoke Lambda functions |
| HTTP | Proxy to HTTP endpoints |
| AWS Service | Integrate with AWS services |
| Mock | Return static responses |
| VPC Link | Access private resources |
REST API vs HTTP API
| Feature | REST API | HTTP API |
|---|---|---|
| Cost | Higher | ~70% cheaper |
| Latency | Higher | Lower |
| Caching | Yes | No |
| Request validation | Yes | No |
| WAF integration | Yes | No |
| API keys | Yes | Yes |
| Custom domains | Yes | Yes |
- Need API caching
- Require request/response validation
- Need WAF integration
- Complex mapping templates
- Usage plans with quotas
- Simple proxy to Lambda or HTTP
- Cost-sensitive applications
- Need lower latency
- JWT authorization is sufficient
- No need for caching
Lambda Integration
Lambda Proxy Integration
Lambda Proxy Integration is the most common pattern. API Gateway passes the entire request to Lambda and expects a specific response format.
API Gateway passes the entire request to Lambda:
export const handler = async (event) => {
const { httpMethod, path, body, queryStringParameters } = event;
return {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "Hello!" })
};
};Request/Response Mapping
Transform requests and responses with mapping templates (Velocity Template Language):
{
"userId": "$input.path('$.id')",
"userName": "$input.path('$.name')"
}VTL Syntax
Mapping templates use Apache Velocity Template Language (VTL). Common functions: $input.path(), $input.json(), $util.escapeJavaScript().
Authorization
Security First
Always implement proper authorization for production APIs. Never expose APIs without authentication.
Authorization Flow
Use AWS credentials to sign requests with Signature Version 4.
aws apigateway test-invoke-method \
--rest-api-id abc123 \
--resource-id xyz789 \
--http-method GETAuthenticate with Amazon Cognito User Pools. The API validates JWT tokens automatically.
aws apigateway create-authorizer \
--rest-api-id abc123 \
--name MyCognitoAuthorizer \
--type COGNITO_USER_POOLS \
--provider-arns arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_xxxSimple key-based access control:
# Create API key
aws apigateway create-api-key \
--name my-api-key \
--enabled
# Create usage plan
aws apigateway create-usage-plan \
--name my-usage-plan \
--throttle burstLimit=500,rateLimit=1000 \
--quota limit=10000,period=MONTHRequest Validation
Validate requests before reaching backend:
components:
schemas:
CreateUserRequest:
type: object
required:
- name
- email
properties:
name:
type: string
minLength: 1
email:
type: string
format: emailRequest validation is only available for REST APIs. HTTP APIs require validation in your backend.
CORS Configuration
Enable Cross-Origin Resource Sharing:
# For REST API
aws apigateway put-method-response \
--rest-api-id abc123 \
--resource-id xyz789 \
--http-method OPTIONS \
--status-code 200 \
--response-parameters '{
"method.response.header.Access-Control-Allow-Origin": true,
"method.response.header.Access-Control-Allow-Methods": true,
"method.response.header.Access-Control-Allow-Headers": true
}'For HTTP APIs, CORS can be configured directly in the console or via --cors-configuration parameter.
Throttling
Rate limit API requests:
| Level | Description |
|---|---|
| Account | 10,000 RPS default |
| Stage | Custom per stage |
| Method | Custom per method |
| Usage Plan | Per API key |
aws apigateway update-stage \
--rest-api-id abc123 \
--stage-name prod \
--patch-operations '[
{"op": "replace", "path": "/throttling/rateLimit", "value": "1000"},
{"op": "replace", "path": "/throttling/burstLimit", "value": "2000"}
]'Caching (REST API)
Caching is only available for REST APIs. Cache sizes range from 0.5 GB to 237 GB.
Cache responses to reduce backend calls:
aws apigateway update-stage \
--rest-api-id abc123 \
--stage-name prod \
--patch-operations '[
{"op": "replace", "path": "/cacheClusterEnabled", "value": "true"},
{"op": "replace", "path": "/cacheClusterSize", "value": "0.5"}
]'Custom Domain Names
Use your own domain:
aws apigateway create-domain-name \
--domain-name api.example.com \
--certificate-arn arn:aws:acm:us-east-1:123456789012:certificate/abc123For regional endpoints, the certificate must be in the same region. For edge-optimized endpoints, the certificate must be in us-east-1.
Monitoring
CloudWatch Metrics
- Count - Total API requests
- Latency - Request processing time
- 4XXError - Client errors
- 5XXError - Server errors
- CacheHitCount - Cache hits (REST API)
- CacheMissCount - Cache misses (REST API)
Access Logging
aws apigateway update-stage \
--rest-api-id abc123 \
--stage-name prod \
--patch-operations '[
{"op": "replace", "path": "/accessLogSettings/destinationArn", "value": "arn:aws:logs:us-east-1:123456789012:log-group:api-logs"},
{"op": "replace", "path": "/accessLogSettings/format", "value": "$requestId $httpMethod $resourcePath $status"}
]'Best Practices
Security
- Use HTTPS only
- Enable authentication
- Implement request validation
- Use WAF for REST APIs
- Rotate API keys regularly
Performance
- Enable caching for GET requests
- Use HTTP APIs for simple use cases
- Minimize integration latency
- Use regional endpoints
Cost Optimization
- Choose HTTP API when possible
- Right-size cache
- Use usage plans for rate limiting
- Monitor and optimize