# API Gateway

[Mock integration](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-mock-integration.html) | [CloudWatch monitoring](https://docs.aws.amazon.com/apigateway/latest/developerguide/monitoring-cloudwatch.html) | [Integrations](https://docs.aws.amazon.com/apigateway/latest/developerguide/setup-http-integrations.html) |

## Overview

* Fully managed service
* Helps create, publish, maintain, monitor and secure APIs at any scale.

<figure><img src="https://2259236002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fuh9xZDZ53qGqmMCM44PU%2Fuploads%2F3dbuRCePS4Pf1sqMYFFH%2Fimage.png?alt=media&#x26;token=16fa080d-6c4d-4f1c-85e5-3f0e7ef2a70b" alt=""><figcaption><p>request flow inside an API Gateway</p></figcaption></figure>

### Use cases

* Deploy RESTful APIs: act as a <mark style="background-color:blue;">**front-door**</mark> for application to access data, business logic, and functionality from backend services.

<figure><img src="https://2259236002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fuh9xZDZ53qGqmMCM44PU%2Fuploads%2FOk60trucpE9oU2mvMIkD%2Fimage.png?alt=media&#x26;token=aefa8f52-1412-47af-9429-60643a0b1010" alt="" width="563"><figcaption><p>serverless pattern</p></figcaption></figure>

### 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

* *<mark style="color:red;">2 - way communication</mark>* 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)

{% hint style="info" %}
Amazon API Gateway WebSocket APIs provide a callback URL (`$disconnect`) that can be used to programmatically disconnect clients.
{% endhint %}

***

## 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}`

<figure><img src="https://2259236002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fuh9xZDZ53qGqmMCM44PU%2Fuploads%2FIRF1R5Z79yO10uimtp0q%2Fimage.png?alt=media&#x26;token=df48c1a4-7a8c-41c7-8966-1ba8c04b21ff" alt=""><figcaption><p>Stage variable</p></figcaption></figure>

### 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](#mapping-templates).
  * `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](#overview) 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`

{% hint style="info" %}
Mock integrations <mark style="color:red;">aren't</mark> intended to support <mark style="color:red;">large response templates</mark>. If you need them for your use case, you should consider using a Lambda integration instead.
{% endhint %}

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.

{% hint style="danger" %}
Mapping templates only work for non-proxy integrations.
{% endhint %}

### Throttling limit

* Configure this to *<mark style="color:red;">handle burst, spike traffic</mark>*.
* 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

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

### Authorizers

#### Congnito

<figure><img src="https://2259236002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fuh9xZDZ53qGqmMCM44PU%2Fuploads%2FlUuAoT1nYRT98ljW1Deo%2Fimage.png?alt=media&#x26;token=201aa1d7-1b45-4530-9d69-6b824c3e6c5f" alt="" width="563"><figcaption><p>Cognito user pool authorizer</p></figcaption></figure>

#### Lambda

<figure><img src="https://2259236002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fuh9xZDZ53qGqmMCM44PU%2Fuploads%2FKcUApLP8nNYxMUqPdhBs%2Fimage.png?alt=media&#x26;token=68761550-7a5c-4ccb-abee-215e4e10786e" alt="" width="563"><figcaption><p>Lambda authorizer</p></figcaption></figure>

***

## 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 *<mark style="color:red;">snapshot of the API</mark>*. Use a stage to manage and optimize a particular deployment.&#x20;
* ***Stage variable***: environment variable.
* ***Apached Velocity Template Language*** (VTL): engine that API Gateway uses for [mapping templates](#mapping-templates).

## Trivia
