API Gateway

create, publish, maintain, monitor, and secure APIs at any scale.

Mock integration | CloudWatch monitoring | Integrations |

Overview

  • Fully managed service

  • Helps create, publish, maintain, monitor and secure APIs at any scale.

Use cases

  • Deploy RESTful APIs: act as a front-door for application to access data, business logic, and functionality from backend services.

API Type

REST

  • Request-response patterns

  • Supports resource-based policy

  • Does not support OIDC and OAuth 2.0 natively

HTTP

  • Request-response patterns

  • Supports OIDC and OAuth 2.0

  • Does not support resource-based policies

  • Cheaper than REST APIs

WebSocket

  • 2 - way communication between the client and the server

  • Connection is persistent and stateful

  • Used in real-time chat application, collaboration platforms, multiplayer games and financial trading platforms.

  • The backend can be anything (AWS services or any HTTP endpoint)

Amazon API Gateway WebSocket APIs provide a callback URL ($disconnect) that can be used to programmatically disconnect clients.


Features

Stage variables

  • Key-value pairs that you use to pass configuration settings (environment variables) or env-specific data to your API during deployment.

  • Stage variables are passed to context object in lambda functions

  • Format to access stage variables in API gateway - ${stageVariables.variableName}

Integration type

  • Proxy: client’s request is transmitted as is to the backend, including any headers or query parameters. No modification is done to the request data.

    • AWS_PROXY: Lambda proxy integration

    • HTTP_PROXY (HTTP proxy integration): no configuration for request/response is necessary. You only need to set the HTTP method and the HTTP endpoint URI.

  • Non-proxy: API Gateway has control over how client data is formatted before it’s passed down to your integration backend or before it’s returned to the client using mapping template.

    • AWS: directly integrate with other services

    • HTTP (HTTP custom endpoint): expose HTTP endpoints in the backend. Similar to AWS integration, it requires configuration for both the integration request and response and data mappings between the method and integration requests/responses.

  • Mock

Generate API responses from API Gateway directly, without the need for an integration backend. Type value is MOCK

Mock integrations aren't intended to support large response templates. If you need them for your use case, you should consider using a Lambda integration instead.

You could use a scope query parameter on the incoming request to determine whether to return a successful response or an error response:

{
  #if( $input.params('scope') == "internal" )
    "statusCode": 200
  #else
    "statusCode": 500
  #end
}

Mapping Templates

Modify any request data before it is forwarded to your integration backend. Conversely, it can be used for transforming the response data before it is returned to the client.

Mapping templates only work for non-proxy integrations.

Throttling limit

  • Configure this to handle burst, spike traffic.

  • Limit the request number can be sent to API in a certain amount of time. eg: requests/sec

  • If the number of requests goes over this limit, API Gateway will temporarily block or slow down the extra requests -> as part of DDoS protection trategy.

CloudWatch monitoring

  • IntegrationLatency: monitor responsiveness of backend

  • Latency: the total time taken between API Gateway receiving a request from the client and returning a response. Includes the IntegrationLatency value.

  • CacheHitCount and CacheMissCount: to optimize cache capacities to achieve a desired performance.

Usage Plan

Usage plan determines which API stages and methods the API key can access. If the API key is not associated with a usage plan, it will not have permission to access any of the resources, which will result in a 403 Forbidden error.

-> CreateUsagePlanKey to associate API key with Usage Plan.

CORS

Disabled by default. CORS is configured at the resource method level when using non-proxy integrations

API Caching

API caching in API Gateway improves performance by reducing the number of requests that are sent to your endpoint service.

Invalidating Cache

When content is cached, API Gateway does not update the cache entries until the Time-To-Live (TTL) expires -> By sending an invalidation request to your API endpoint -> will prompt API Gateway to refresh its cache instead of waiting for the TTL to expire.

Invalidation request

Simply include the Cache-Control header in a request with a max-age of 0

fetch('https://aaaa4vb5wf.execute-api.us-east-1.amazonaws.com/v1', {
            method: 'GET',
            headers: {
                'Cache-Control': 'max-age=0'
} });

Authorizers

Congnito

Lambda


Troubleshooting

HTTP 504: gateway timeout

  • INTEGRATION_FAILURE - The gateway response for an integration failed error. If the response type is unspecified, this response defaults to the DEFAULT_5XX type.

    INTEGRATION_TIMEOUT - The gateway response for an integration timed out error. If the response type is unspecified, this response defaults to the DEFAULT_5XX type.

  • Lambda execution time > 15 minutes

  • API Gateway has a maximum integration timeout of 29 seconds for connections to backend services, including Lambda. If your backend takes longer than this to respond, API Gateway will close the connection and return a 504 error.

  • The incoming requests exceed the concurrency limit of your Lambda function

HTTP 502: Bad Gateway

Lambda returned wrong format.

Concepts

  • Stage: a named reference to a deployment, which is a snapshot of the API. Use a stage to manage and optimize a particular deployment.

  • Stage variable: environment variable.

  • Apached Velocity Template Language (VTL): engine that API Gateway uses for mapping templates.

Trivia

Last updated