[AWS] API Gateway

API Gateway is a fully managed API endpoint service that creates, manages, publishes, monitors, secures, and scales APIs. API Gateway can use other AWS services (Lambda, DynamoDB) for compute and store.


  • API (Application Programming Interface): Applications use APIs to communicate with other applications.
  • API Gateway is often used as the front door to a serverless application.

API Gateway Features

  • API Gateway is a service that provides a single endpoint for traffic from all clients interacting with the backend applications running on Lamba or EC2 and services like DynamoDB or Kinesis.
    • API Gateway can act as a front door for existing API and can be scaled to meet the demand.
    • It supports the serverless, microservice, and even monolithic architecture.
  • API Gateway allows you to publish, maintain, secure, and monitor APIs at any scale.
    • Supports multiple versions of your APIs
  • Pricing is based on the number of API calls, the amount of data transferred, and any caching.
  • API Gateway can access some AWS services directly using proxy mode.
  • You can use AWS X-Ray to trace and analyze user requests as they travel through your Amazon API Gateway APIs to the underlying services.
  • DDoS (Distributed Denial of Service) protection via CloudFront
  • Request/Response data transformation (JSON -> XML)
  • Can be used with AWS Certificate Manager: free SSL/TLS certificates
  • The same-origin-policy is important to secure your API from Cross-Site Scripting (XSS) attacks. CORS (Cross Origin Resource Sharing) is the way to loosen the policy.

Supported API Types

RESTful (Representational State Transfer) APIs

  • Optimized for stateless and serverless workloads such as web applications
  • Supports JSON (JavaScript Object Notation) with key/value pairs
  • Endpoints
    • Regional endpoint
      • provides lower latency for applications that invoke your API within the same Region
    • Edge-optimized endpoint
      • works with a fully managed CloudFront distribution
    • Private endpoint
      • route requests only within a single VPC

There are 2 types of RESTful services.

Choosing between REST APIs and HTTP APIs – Amazon API Gateway

  • Rest APIs
    • Provides more features
      • API Keys, per-client throttling, request validation, WAF integration
    • There is no $default stage.
    • There is no auto deployment.
    • Designed with minimal features at lower price
    • simple and low-latency solution to integrate with AWS services, such as Lambda, and HTTP endpoints.
    • It creates $default stage for you automatically.
    • You can set up “Auto Deployment”.

Websocket APIs

  • real-time, two-way, long-lived stateful communications
  • use cases
    • chat applications or streaming dashboard
  • WebSocket routes
    • With WebSocket APIs, JSON messages can be routed to invoke a specific backend service based on message content.
    • There are 3 predefined routes:
      • $connect
        • The client application connects to your WebSocket API by sending a WebSocket upgrade request.
        • If the request succeeds, the $connect route is invoked.
        • The upgrade request is pending until the $connection route is completed.
      • $default
        • After the connection is established,the client message can be routed to the backend service.
      • $disconnect
        • The $disconnect route is invoked after the connection is closed.
        • It is the best-effort event. There is no guaranteed delivery.
    • You can add a custom route.
  • Integration
    • You must connect the API with an endpoint such as a lambda function or an HTTP endpoint.
  • WebSocket Selection Expressions
    • API Gateway uses selection expressions as a way to evaluate the request and response context and produce a key.

API Gateway Caching

API Gateway caches the endpoint response to improve the latency for requests.

  • API Gateway Caching is used to cache the endpoint’s response per API or per Stage (a cache key).
  • Caching is used to improve the latency of the requests to APIs.
  • Only GET methods can be cached.
  • API Gateway caches responses for a specified time-to-live (TTL) period in seconds. The default is 300 seconds (5 mins).
  • CloudWatch metrics:
    • CacheHitCount
    • CacheMissCount

API Gateway Components

  • Resource: a logical entity that can be accessed via the resource path (resource URL)
  • Method: a method can be associated with a resource and responds to the request (GET, PUT, …)
  • Deployment: a snapshot of API’s resources and methods; must be associated with a stage
  • Stage: APIs are deployed into stages (different environments: dev, productions);
    • A stage is a snapshot of the API – methods, integration, models, mapping templates, and Lambda authorities. It supports AWS Certificate manager.
    • Each stage has its own unique invoke URL.
    • Stage variables can be used to reference a different backend endpoint such as a different Lambda function.

API Authorization

  • JWT (JSON Web Token)
    • Open ID Connect (OIDC)
      • A simple identity layer on top of the OAuth 2.0
    • Supports federated identities for web and mobile users
    • HTTP APIs: JWT authorizers
    • REST APIs: Amazon Cognito user pools (which use JWT authorizers)
  • AWS IAM Permissions
    • Requires IAM credentials
    • Not good for web/mobile apps with a large number of users
      • Maximum 5,000 users
  • Lambda Authorizers
    • Custom authorization
      • A Lambda authorizer is an API Gateway feature that uses a Lambda function to control access to the API.
    • Types of Lambda Authorizers
      • Token-based: A bearer token (JWT or OAuth token) as a caller’s identity
      • Request-parameter-based: headers, query parameters, stage variables, or $context variables

API Gateway also supports certificate-based authentication via mutual Transport Layer Security (mTLS).

API Throttling

API Gateway manages traffic with throttling so that backend applications can withstand traffic spikes and denial of service attacks.

  • Throttling rules can be used to set the number of requests per second.
  • Limits
    • Default limit: 10,000 requests per second (rps) per region
    • Concurrent limit: 5,000 concurrent requests across all APIs within an account
  • Any request over the limit will receive a 429 HTTP response (Too many requests).

Ex) If there are more than 5K requests per second, 5K requests are handled immediately, and API Gateway throttles the rest within the one-second period.

  • CloudWatch can be used to monitor API Gateway activity, usage, and throttling rules.
    • Throttling limits can be set for standard rates and burst rates. For example, you can set a standard rate limit of 1,000 requests per second for a specific REST method and also configure a burst rate of 2,000 requests per second for a few seconds.

Integration with Lambda

API Gateway works very well with Lambda.

Synchronous Function Call

  • API Gateway invokes Lambda function synchronously and waits for the response.
  • The built-in timeout is 30 seconds.

Import/Export APIs

  • The API Gateway Import feature is used to import an API from the external definition file into API Gateway.
    • Swagger or OpenAPI 3.0

API Gateways Logs

By default, logging is NOT configured for new API. You can set up the “Access logs” or “CloudWatch Logs“.

Access Logs

  • Both for REST and HTTP
  • for every API requests

CloudWatch Logs

  • Only for REST
  • Used for troubleshooting and debugging
  • Error or INFO Level

Mock Endpoints (Integration)

  • Simulate the behaviors and responses of the API
  • Developers can create, test, and debug the client code of the API even before the background of API code is not ready.

API Gateway Usage Plan

API Gateway usage plans make your APIs available as product offerings for your customers.

  • A usage plan specifies who can access deployed APIs (stages and methods) and also how much and how fast they can access them.

API keys are used to identify API clients.

  • An API key has a name and a value.
    • The terms “API key” and “API key value” are often used interchangeably.
    • The value is an alphanumeric string between 20 and 128 characters.
    • The value must be unique.

You can control customers’ API usage by:

  • Throttling limit: the target point at which request throttling should start
  • Quota limit: the target maximum number of requests with a given API key that can be submitted within a specified time interval

Best Practices

  • Do not use API keys for authentication or authorization for your APIs.
  • Use API keys that API Gateway generates.
  • API keys shouldn’t include confidential information.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s