API Gateway

  • API is an Application Programming Interface
  • Waiters in a restaurant are an API
    • Take order, pass it to the kitchen, then bring it back to customer

Types of APIs

  • Rest APIs
    • REpresentational State Transfer
    • Uses JSON
  • SOAP APIs
    • Simple Object Access Protocol
    • Uses XML

What is API gateway?

  • Fully managed service that makes it easy for developers to publish, maintain, monitor, and secure APIs at any scale
  • With a few clicks in the AWS management console, you can create an API that acts as a “front door” for applications to access data, business logic, or functionality from your back-end services, such as applications running on Amazon Elastic Compute Cloud (Amazon EC2), code running on AWS Lambda, or any web application

What can API Gateway Do?

  • Expose HTTPS Endpoints to define a RESTful API
  • Serverless-ly connect to services like lambda & DynamoDB
  • Send each API endpoint to a different target
  • Run efficiently with low cost
  • Scale effortlessly
  • Track and control usage by API key
  • Throttle requests to prevent attacks
  • Connect to CloudWatch to log all requests for monitoring
  • Maintain multiple versions of the API

How do i configure API gateway?

  • Define an API (container)
  • Define REsources and nested resources (url paths)
  • For each resource:
    • Select supported HTTP methods (verbs)
    • Set Security
    • Choose target (such as EC2, Lambda, DynamoDB, etc)
    • Set request and response transformations
  • Deploy API to a Stage
    • Uses API gateway domain, by default
    • Can use custom domain
    • Now supports AWS certificate Manager: Free SSL/TLS certs

What is API Caching?

  • You can enable API caching in Amazon API Gateway to cache your endpoint’s reponse
  • With caching, you can reduce the number of calls made to your endpoint and also improve the latency of the requests to your API
  • When you enable caching for a stage, API gateway caches responses from your endpoint for a specified time-to-live (TTL) period, in seconds
  • API Gateway then responds to the request by looking up the endpoint response from the cache instead of making a request to your endpoint
    • Mcdonalds already had burgers and big macs already made, so they just grab an already made burger
    • Uncommon orders are not cached, the kitchen actually has to make it

Same origin policy

  • In computing, the same-origin policy is an important concept in the web application security model
  • Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin
  • This is done to prevent cross-site scripting (XSS) attacks
  • Enforced by web browsers
  • Ignored by tools like PostMan and Curl

Cross-Origin Resource Sharing (CORS)

  • Cross-Origin Resource Sharing is one way the server at the other end (not the client code in the browser) can relax the same-origin policy
    • A way for API gateway to talk to S3
  • CORS is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served
  • Browser makes an HTTP OPTIONS call for a URL
    • OPTIONS is an HTTP method like GET, PUT, and POST
  • Server returns a response that says:
    • “These other domains are approved to GET this URL”
  • Error - “Origin policy cannot be read at the remote resource?”
    • You need to enable CORS on API Gateway

Exam Tips

  • What API gateway is at a high level
  • API gateway has caching capabilities to increase performance
  • API gateway is low cost and scales automatically
  • You can Throttle API gateway to prevent attacks
  • You can log results to CloudWatch
  • If you are using JavaScript/AJAX that uses multiple domains with aPI gateway, ensure that you have enabled CORS on API Gateway
  • CORS is enforced by the client

API Gateway Lambda Authorizer

A LAmbda authorizer is an API gateway feature that uses a Lambda function to controll acess to your API. When a client makes a requiest to one of your API's methods, API Gateway calls your Lambda authorizer, which takes the caller's identity as input and returns an IAM policy as output.

There are two types of Lambda Authorizers:

  • A token-based Lambda Authorizer (also called a TOKEN authorizer) receives the caller's identity in a bearer token, such as a JWT or an OAuth token
    • You must specify a custom header as the TokenSource when you configure the authorizer for your API
    • The API client must pass the required authorization token in that header in the incoming request.
    • Upon receiving the incoming method request, API gateway extracts the token from the custom header
    • It then passes the token as the authorizationToken property of the event object of the Lambda function, in addition to the method ARN as the methodARN property
  • A request parameter-based Lambda authorizer (also called a REQUEST authorizer) receives the caller's identity in a combination of headers, query string parameters, stageVariables, and $context variables.
    • API Gateway passes the required request parameters to the authorizer Lambda function as part of the event object.
    • The affected request parameters include headers, path parameters, query string parameters, stage variables, and some request context variables.
    • The API caller can set the path parameters, headers, and query string parameters
    • The API developer must set the stage variables during the API deployment and API Gateway provides the request context at run time.

It is possible to use an AWS Lambda function from an AWS account that is different from the one in whichj you created your Lambda authorizer function by using a Cross-Account Lambda Authorizer.

Use API Gateway Lambda Authorizers

Input to an Amazon API Gateway Lambda Authorizer

Configure a Cross-Account Lambda Authorizer

Integration Types

After settingup an API method, you must integrate it with an endpoint in the backend. A backend endpoint is also referred to as an integration endpoint and can be a Lambda function, an HTTP web page, or an AWS service action. As with the API method, the API integration has an integration request and an integration response. An integration request encapsulates an HTTP request received by the backend. It may or may not differ from the method request submitted by the client. An integration response is an HTTP response encapsulating the output returned by the backend.

  • AWS
    • This type of integration lets an API expose AWS service actions
    • In AWS integration, you must configure both the integration request and integration response and set up necessary data mappings from the method request to the integration request, and from the integration response to the method response
  • AWS_PROXY
    • This type of integration lets an API method be integrated with the Lambda function invocation action with a flexible, versatile, and streamlined integration setup.
    • This integration relies on direct interactions between the client and the integrated Lambda function.
    • With this type of integration, also known as the Lambda Proxy integration, you do not set the integration request or the integration response. API Gateway passes the incoming request from the client as the input to the backend Lambda function. The integrated Lambda function takes the input and parses the input from all available sources, including request headers, URL path variables, query string parameters, and applicable body.
    • This is the preferred integration type to call a Lambda function through API Gateway and is not applicable to any other AWS service actions, including Lambda actions other than the function-invoking action.
  • HTTP
    • This type of integration lets an API expose HTTP endpoints in the backend.
    • With this integration, also known as HTTP custom integration, you must configure both the integration request and integration response. You must set up necesssary data mappings from the method request to the integration request, and from the integration response to the method response
  • HTTP_PROXY
    • Allows a client to access the backend HTTP endpoints with a streamlined integration setup on single API method.
    • You do not set the integration request or the integration response
    • API Gateway passes the incoming request from the client to the HTTP endpoint and passes the outgoing response from the HTTP endpoint to the client
  • MOCK
    • This type of integration lets API Gateway return a response without sending the request further to the backend
    • This is useful for API testing because it can be used to test the integration set up without incurring charges for using the backend and to enable collaborative development of an API.
    • In collaborative development, a team can isolate their development effort by setting up simulations of API components owned by other teams using the MOCK integrations. It is also used to return CORS-related headers to ensure that the API method permits CORS access. In fact, the API gateway console integrates the OPTIONS method to support CORS with a mock integration.

Set up Lambda Proxy Integrations in API Gateway

Non-proxy Lambda Integration

In Lambda non-proxy (or custom) integration, you can specify how the incoming request data is mapped to the integration request and how the resulting integration response data is mapped to the method response.

For an AWS service action, you have the AWS integration of the non-proxy type only. API Gateway also supports the mock integration, where API Gateway serves as an Integration endpoint to respond to a method request. The Lambda custom integration is a special case of the AWS integration, where the integration endpoint corresponds to the function-invoking action of the Lambda service.

the Lambda custom integration type (AWS_PROXY) lets an API method be integrated with the Lambda function invocation action iwth a flexible, versatile, and streamlined integration setup. The integration relies on direct interactions between the client and the integrated Lambda function. With this type of integration, also known as the Lambda proxy integration, you do not set the integration request or the integration response. API Gateway passes the incoming request from the client as the input to the backend Lambda function.

Configure the method request to check for required parameters first because the client traffic will hit the method request first before it goes to the integration request down to the underlying Lambda function. Integration requests do not have the capability to enforce a request to include certain query string parameter nor enable API caching.

API Gateway Monitoring

You can monitor API execution using CloudWatch, which collects and processes raw data from API Gateway into readable, near real-time metrics. These statistics are recorded for a period of two weeks, so that you can access historical information and gain a better perspective on how your web application or service is performing. By default, API Gateway metric data is automatically sent to CloudWatch in one-minute periods.

The metrics reported by API Gateway provide information that you can analzyze in different ways. This list below shows some common uses for the metrics. These are suggestions to get you started, not a comprehensive list.

  • IntegrationLatency
    • Measures responsiveness of the backend
  • Latency
    • Overall responsiveness of your API calls
  • CacheHitCount and CacheMissCount
    • Optimize cache capacities to achieve a desired performance.
      • CacheMissCount trakcs the number of requests served from the backend in a given period when API caching is enabled
      • CacheHitCount tracks the number of requests served from the API cache in a given period

API Gateway Metrics and Dimensions

Monitor API Execution with Amazon CloudWatch

API Gateway Integration Errors

A Gateway response is identified by a response type defined by API Gateway. The response consists of an HTTP status code, a set of additional headers that are specified by parameter mappings, and a payload that is generated by a non-VTL (Apache Velocity Template Language) and mapping template.

You can set up a gateway response for a supported response type at the API level. Whenever API Gateway returns a response of the type, the header mappings and payload mapping templates defined in the gateway response are applied to return the mapped results to the API caller.

The following are the Gateway response types which are associated with the HTTP 504 error in API Gateway

  • 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 respoinse type is unspecified, the response defaulst to the DEFAULT_5XX type

For Integration timeout, the range is from 50 milliseconds to 29 seconds for all integration types, including Lambda, Lambda proxy, HTTP, HTTP proxy, and AWS integrations.

If a Lambda function is working but there are instances it throws an error, it could be the Integration_TIMEOUT or INTEGRATION_FAILURE if the Lambda integration does not work at all.

Extras

  • "Usage Plans and API Keys" : You can configure usage plans and API keys to allow customers to access selected APIs at agreed-upon request rates and quotas that meet their business requirements and budget constraints.
  • "Use Mapping Templates" : API Gateway lets you use mapping templates to map the payload from a method request to the corresponding integration request and from an integration response to the corresponding method response.
    • https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
  • Canary Deployment is used for testing for new API Versions.
    • In a canary release deployment, total API traffic is separated at random into a production release and a canary release with a pre-configured ratio. Typically, the canary release receives a small percentage of API traffic and the production release takes up the rest. The updated API features are only visible to API traffic through the canary. You can adjust the canary traffic percentage to optimize test coverage or performance.
    • https://docs.aws.amazon.com/apigateway/latest/developerguide/canary-release.html
  • Stage variables act like environment variables and can be used in your API setup
  • Custom authorizers are used for authentication purposes and must return AWS IAM policies
  • header Cache-Control: max-age=0 can be used to bypass caching in API Gateway
    • use if you have caching set up, but do not want to receive a cached request