DevDocsDev Docs
API Gateway

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

TypeUse CaseFeatures
REST APITraditional REST APIsFull feature set, caching, WAF
HTTP APISimple HTTP APIsLower cost, faster, simpler
WebSocket APIReal-time communicationTwo-way communication

Request Flow Architecture

Key Concepts

Resources and Methods

APIs are organized as resources (paths) with methods (HTTP verbs).

REST API Structure
/users          GET    → List users
/users          POST   → Create user
/users/{id}     GET    → Get user
/users/{id}     PUT    → Update user
/users/{id}     DELETE → Delete user

Stages

Deployment environments for your API:

  • dev - Development
  • staging - Testing
  • prod - Production

Integrations

Connect API methods to backend services:

TypeDescription
LambdaInvoke Lambda functions
HTTPProxy to HTTP endpoints
AWS ServiceIntegrate with AWS services
MockReturn static responses
VPC LinkAccess private resources

REST API vs HTTP API

FeatureREST APIHTTP API
CostHigher~70% cheaper
LatencyHigherLower
CachingYesNo
Request validationYesNo
WAF integrationYesNo
API keysYesYes
Custom domainsYesYes
  • 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:

handler.js
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):

mapping-template.vtl
{
  "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.

Signed Request Example
aws apigateway test-invoke-method \
  --rest-api-id abc123 \
  --resource-id xyz789 \
  --http-method GET

Custom authorization logic:

authorizer.js
export const handler = async (event) => {
  const token = event.authorizationToken;
  
  // Validate token
  if (isValid(token)) {
    return generatePolicy('user', 'Allow', event.methodArn);
  }
  
  return generatePolicy('user', 'Deny', event.methodArn);
};

Authenticate with Amazon Cognito User Pools. The API validates JWT tokens automatically.

Create Cognito Authorizer
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_xxx

Simple key-based access control:

Create API Key
# 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=MONTH

Request Validation

Validate requests before reaching backend:

openapi-schema.yaml
components:
  schemas:
    CreateUserRequest:
      type: object
      required:
        - name
        - email
      properties:
        name:
          type: string
          minLength: 1
        email:
          type: string
          format: email

Request validation is only available for REST APIs. HTTP APIs require validation in your backend.

CORS Configuration

Enable Cross-Origin Resource Sharing:

Enable CORS
# 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:

LevelDescription
Account10,000 RPS default
StageCustom per stage
MethodCustom per method
Usage PlanPer API key
Configure Stage Throttling
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:

Enable API Caching
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:

Create Custom Domain
aws apigateway create-domain-name \
  --domain-name api.example.com \
  --certificate-arn arn:aws:acm:us-east-1:123456789012:certificate/abc123

For 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

Enable 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

  1. Use HTTPS only
  2. Enable authentication
  3. Implement request validation
  4. Use WAF for REST APIs
  5. Rotate API keys regularly

Performance

  1. Enable caching for GET requests
  2. Use HTTP APIs for simple use cases
  3. Minimize integration latency
  4. Use regional endpoints

Cost Optimization

  1. Choose HTTP API when possible
  2. Right-size cache
  3. Use usage plans for rate limiting
  4. Monitor and optimize

Next Steps

On this page