AWS API Gateway is a fully managed service that makes it easy for developers to publish, maintain, monitor, and secure APIs at any scale
API Gateway handles all of the tasks involved in accepting and processing up to hundreds of thousands of concurrent API calls, including traffic management, authorization and access control, monitoring, and API version management.
APIs defined using the OpenAPI (Swagger) definition
API Gateway has no minimum fees or startup costs and charges only for the API calls received and the amount of data transferred out.
API Gateway acts as a proxy to the configured backend operations.
API Gateway scales automatically to handle the amount of traffic the API receives.
Can integrate endpoints with private VPCs
API Gateway expose HTTPS endpoints only for all the APIs created. It does not support unencrypted (HTTP) endpoints.
APIs built on API Gateway can accept any payloads sent over HTTP with typical data formats include JSON, XML, query string parameters, and request headers.
API Gateway can communicate to multiple backends;
Lambda functions
AWS Step functions state machines
HTTP endpoints exposed through Elastic Beanstalk, ELB or EC2 servers
AWS hosted HTTP based operations accessible via public Internet
API Gateway endpoints are always public to the Internet and does not run within an VPC. Proxy requests to backend operations also need to be publicly accessible on the Internet.
Metering
Automatically meters traffic to the APIs and and lets you extract utilization data for each API key.
Define plans that meter, restrict third-party developer access, configure throttling, and quota limits on a per API key basis
Security
Helps removing authorization concerns from the backend code.
Allows leveraging of AWS administration and security tools, such as IAM and Cognito, to authorize access to APIs.
Can verify signed API calls on your behalf using the same methodology AWS uses for its own APIs.
Supports custom authorizers written as Lambda functions and verify incoming bearer tokens
Automatically protects the backend systems from distributed denial-of-service (DDoS) attacks, whether attacked with counterfeit requests (Layer 7) or SYN floods (Layer 3).
To create, deploy, and manage an API in API Gateway, you must grant the IAM API developer permissions to perform the required actions supported by the API management component of API Gateway.
To call a deployed API or to refresh the API caching, you must grant the IAM API caller permissions to perform required IAM actions supported by the API execution component of API Gateway.
Resiliency
Helps manage traffic with throttling so that backend operations can withstand traffic spikes.
Helps improve the performance of the APIs and the latency end users experience by caching the output of API calls to avoid calling the backend every time.
Operations Monitoring
Integrates with CloudWatch and provides a metrics dashboard to monitor calls to API services.
Integrates with CloudWatch Logs to receive error, access or debug logs.
Provides with backend performance metrics covering API calls, latency data and error rates.
Lifecycle Management
Allows multiple API versions and multiple stages (development, staging, production etc.) for each version simultaneously so that existing applications can continue to call previous versions after new API versions are published.
Saves the history of the deployments, which allows rollback of a stage to a previous deployment at any point, using APIs or console
Designed for Developers
Allows you to specify a mapping template to generate static content to be returned, helping you mock APIs before the backend is ready.
Helps reduce cross-team development effort and time-to-market for applications and allow dependent teams to begin development while backend processes is still built.
Stage variables are name-value pairs that you can define as configuration attributes associated with a deployment stage of a REST API.
Stages
After creating an API, developers can set up a stage.
A stage is a named reference to a deployment, which is a snapshot of the API.
By using stages, you can do the following:
Configure stage settings to enable caching
Customize request throttling
Configure logging
Define stage variables
Attach a canary release for testing
API endpoint
A hostname for an API in API Gateway that is deployed to a specific Region.
The hostname is of the form {api-id}.execute-api.{region}.amazonaws.com.
Following types of API endpoints are supported:
Regional
Regional APIs are deployed in the current AWS Region.
When API requests predominantly originate from an EC2 instance or services within the same Region where the API is deployed.
This is the default selection for Endpoint Type.
Edge-optimized
Edge-optimized APIs are deployed to the Amazon CloudFront network.
Private
Private APIs are accessible only from VPCs using an interface VPC endpoint.
Model
Defines the format (schema or shape) of some data inbound or outbound from the API
Generate SDKs from your API definition.
API Gateway creates classes based on the models you define for your methods.
Resources
A collection of HTTP resources and methods that are integrated with backend HTTP endpoints, Lambda functions, or other AWS services.
You can deploy this collection in one or more stages.
Examples: /notes, /notes/search, and /notes/list.
Methods
Represents a client-facing interface by which the client calls the API to access backend resources.
Methods include GET, POST, HEAD, DELETE, or any other method of choice.
Consists of a request and one or more responses.
You can control method access through authorizations. Default is set to none or set to AWS_IAM.
The following are valid values for Authorization:
NONE – No client authentication is performed, and the method is open for access to any user.
AWS_IAM – Only users in an IAM role with permission to access the method are allowed to call it.
Integrations
Connect a route to backend resources.
Types:
AWS
Integrate the API method request with an AWS service action, including the Lambda function-invoking action.
With the Lambda function-invoking action, this is referred to as the Lambda custom integration.
With any other AWS service action, this is known as AWS integration.
AWS_PROXY
Integrate the API method request with the Lambda function-invoking action with the client request passed through as-is.
Lambda proxy integration.
No options to modify passthrough behaviors
HTTP
Integrate the API method request with an HTTP endpoint, including a private HTTP endpoint within a VPC. This integration is also referred to as the HTTP custom integration.
You can choose passthrough behaviors
HTTP_PROXY
Integrate the API method request with an HTTP endpoint, including a private HTTP endpoint within a VPC, with the client request passed through as-is. This is also referred to as the HTTP proxy integration.
No options to modify passthrough behaviors
MOCK
Integrate the API method request with API Gateway as a "loop-back" endpoint without invoking any backend. Useful for API testing.
Stage
. A stage is a logical reference to a lifecycle state of your API (for example, dev, prod, beta, v2).
When the deployment process is finished, the Stage Editor pane is displayed.
The editor shows the URL to invoke the API's GET/ method request in the Invoke URL field.
Stage Variables
Stage variables, commonly called key-value pairs, are name-value pairs that you can define as configuration attributes.
These attributes are associated with a deployment stage of a REST API.
They act like environment variables and can be used in your API setup and mapping templates.
Example:
$stageVariables.environment
Canary deployment
The purpose of a canary deployment is to reduce the risk of deploying a new version that impacts the workload.
The method will incrementally deploy the new version, making it visible to new users in a slow fashion.
As you gain confidence in the deployment, you will deploy it to replace the current version in its entirety.
Example:
"methodSettings" : {
"String" : {
"metricsEnabled" : "true"
...
}
},
"variables" : {
"Var1" : "Val1"
},
"canarySettings" : {
"percentTraffic" : "10",
"deploymentId" : "A1b2C3",
"useStageCache" : "False"
},
API keys
You can configure usage plans and API keys to allow customers to access selected APIs.
Customers can access these APIs at agreed-upon request rates and quotas that meet their business requirements and budget constraints.
Access control
API Gateway supports multiple mechanisms for controlling and managing access to your API.
Solutions include standard IAM roles and policies, resource policies, cross-origin resource sharing (CORS), and Lambda authorizers.
Data transformations
In API Gateway, an API's method request can take a payload in a different format from the corresponding integration request payload, as required in the backend.
Similarly, the backend may return an integration response payload different from the method response payload, as expected by the frontend.
SDK generation
API Gateway supports generating an SDK for your language-specific application.
Supported languages are Java, JavaScript, Java for Android, Objective-C or Swift for iOS, and Ruby.
Mock integrations
API developers can generate API responses from API Gateway directly, without the need for an integration backend.
Latency
Each service integrated with an application introduces latency.
Using API Gateway, developers with enhanced observability tools can reduce their application’s latency.
Security
AWS (IAM) includes features that are available to use with API Gateway.
With identity-based and resource-based policies, you can specify which API operations are allowed or denied on specified resources. You can also specify conditions under which the operations are allowed or denied.
Using Amazon API Gateway, you can create private REST APIs. These REST APIs can be accessed only from your (VPC) in Amazon VPC by using an interface VPC endpoint.
You can use VPC endpoint policies for private APIs in API Gateway. You can attach to an interface VPC endpoint to control access to the endpoint.
Controls
Tools include throttling to help limit applications from being overwhelmed by too many requests.
With AWS WAF integration as the web application firewall, you can protect the applications from attacks.
Setting up integration requests
Checking the message for any authorizations
Configuring how to pass client-submitted method requests to the backend
Configuring how to transform the request data, if necessary, to the integration request data specifying which Lambda function to call.
Execute the Mapping
Specifying which HTTP server to forward the incoming request to or specifying the AWS service action to invoke
Setting up integration responses
Configuring how to pass the backend-returned result to a method response of a given status code
Configuring how to transform specified integration response parameters to preconfigured method response parameters
Configuring how to map the integration response body to the method response body according to the specified body-mapping templates.
Thus, when an HTTP request comes to API Gateway, it will go through three elements:
Step 0: Protecting your API with Authorization and Usage Plans (Optional)
Authorization with custom authorizers, Cognito, or IAM
Step 1: Validation with Method Requests
Method requests are like the public interface of your API: they define what your endpoint expects, which elements are required, and more.
Your API may require certain headers, such as an Authorization header for authentication and authorization, or an If-Modified-Since header for making conditional requests.
Validating the Request Body using Request Models
Step 2: Transforming the request with the Integration Request
Note that if you’re using the Lambda Proxy or HTTP Proxy, you can skip this step entirely!
However, the time you save here by avoiding integration request configuration can mean additional compute and load in your backing integration.
The integration request step is about transformation.
There are a number of reasons the shape of the request for the client is not the shape of the request needed by your integration:
You’re using API Gateway to provide a more user-friendly interface on top of an older API.
The client may not know information needed for the integration request.
You want to remove request information before forwarding to the backend.
Step 3: Handling your response with Integration Responses
The integration response is a way to internally standardize the response from our integration into something that can be handled next, by our method response.
When configuring integration responses, you first need to provide a regex pattern to identify the response type.
For example, you could use the regex of “.*Unauthorized.*” to capture a 401 Unauthorized status code.
Step 4: Standardizing your responses with Method Responses
Note: This section does not apply if you are using the Lambda proxy or HTTP proxy integration.
Method responses are responsible for two things:
Defining the status codes that will be returned by your API.
Defining the response bodies that are returned by your API.
F
Throttling
Multiple levels including global and by service call and limits can be set for standard rates and bursts.
It tracks the number of requests per second. Any requests over the limit will receive a 429 HTTP response.
Throttling ensures that API traffic is controlled to help the backend services maintain performance and availability.
API Gateway provides two basic types of throttling-related settings:
Server-side throttling limits are applied across all clients.
Per-client throttling limits are applied to clients that use API keys associated with your usage policy as client identifier.
Caching
Provides API result caching specifying its size in gigabytes.
Caching helps improve performance and reduces the traffic sent to the back end.
The request are managed in this way:
If caching is not enabled and throttling limits have not been applied, then all requests pass through to the backend service until the account level throttling limits are reached.
If throttling limits specified, then API Gateway will shed necessary amount of requests and send only the defined limit to the back-end.
If a cache is configured, then API Gateway will return a cached response for duplicate requests for a customizable time, but only if under configured throttling limits.
API Gateway does not arbitrarily limit or throttle invocations to the backend operations and all requests that are not intercepted by throttling and caching settings are sent to your backend operations.
Parameter mapping expressions
A stage variable can be used in a parameter mapping expression for an API method's request or response header parameter, without any partial substitution.
Format
stageVariables.<variable_name>
Mapping templates
A stage variable can be used anywhere in a mapping template, as shown in the following examples.
{ "name" : "$stageVariables.<variable_name>"}
HTTP integration URIs
A stage variable can be used as part of an HTTP integration URL, as shown in the following examples:
A full URI without protocol – http://${stageVariables.<variable_name>}
A full domain – http://${stageVariables.<variable_name>}/resource/operation
A subdomain – http://${stageVariables.<variable_name>}.example.com/resource/operation
A path – http://example.com/${stageVariables.<variable_name>}/bar
A query string – http://example.com/foo?q=${stageVariables.<variable_name>}
For the mapping of exceptions that come from Lambda, Integration Response is the correct place to configure.
However, the corresponding error code (400, 500, so on) on the method response should be created first. Otherwise, API Gateway throws an invalid configuration error response at runtime. Below is an example of mapping BadRequestException to HTTP return code 400:
Attach a resource policy to the API Gateway API, which controls access to the API Gateway resources. Access can be controlled by IAM condition elements, including conditions on AWS account, source VPC, etc.
Standard AWS IAM roles and policies offer flexible and robust access controls that can be applied to an entire API or individual methods.
IAM tags can be used together with IAM policies to control access.
Use IAM permissions to control access to the API Gateway component. For example, in order to call a deployed API, the API caller must be granted permission to perform required IAM actions supported by the API execution component of API Gateway.
Use a Lambda function as the authorizer. When a client calls the API, the API Gateway either supplies the authorization token that is extracted from a specified request header for the token-based authorizer or it passes in the incoming request parameters as the input to the request parameters-based authorizer Lambda function.
Use an Amazon Cognito user pool to control who can access the API in Amazon API Gateway. You need to use the Amazon Cognito console, CLI/SDK, or API to create a user pool. Then, in the API Gateway, create an API Gateway authorizer with the chosen user pool.
Endpoint policies for interface VPC endpoints allow you to attach IAM resource policies to interface VPC endpoints to improve the security of your private APIs.
Cross-origin resource sharing (CORS) lets you control how your REST API responds to cross-domain resource requests.
Client-side SSL certificates can be used to verify that HTTP requests to your backend system are from API Gateway.
AWS WAF can be used to protect your API Gateway API from common web exploits.
A Lambda authorizer is an API Gateway feature that uses a Lambda function to control access to your API.
The following are two types of Lambda authorizers:
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.
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 Lambda authorization workflow
The client calls a method on an API Gateway API method, passing a bearer token or request parameters.
API Gateway checks whether a Lambda authorizer is configured for the method. If it is, API Gateway calls the Lambda function.
The Lambda function authenticates the caller by means such as the following:
Calling out to an OAuth provider to get an OAuth access token.
Calling out to a SAML provider to get a SAML assertion.
Generating an IAM policy based on the request parameter values.
Retrieving credentials from a database.
If the call succeeds, the Lambda function grants access by returning an output object containing at least an IAM policy and a principal identifier.
API Gateway evaluates the policy.
If access is denied, API Gateway returns a suitable HTTP status code, such as 403 ACCESS_DENIED.
If access is allowed, API Gateway runs the method. If caching is enabled in the authorizer settings, API Gateway also caches the policy so that the Lambda authorizer function doesn't need to be invoked again.
When your API's resources receive requests from a domain other than the API's own domain, you must enable cross-origin resource sharing (CORS) for selected methods on the resource.
This amounts to having your API respond to the OPTIONS preflight request with at least the following CORS-required response headers:
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Allow-Origin
While enabling CORS on resources using API Gateway, for all responses apart from 200 responses of the OPTIONS method, we need to manually configure to return Access-Control-Allow-Origin' header with '*' or specific origins to fulfill pre-flight handshakes.
The best way to mantain 2 API versions is to create a separate stage in the API gateway as maybe ‘v2’, and then customers could use both API versions.
Lambda proxy integration
The input to the integrated Lambda function can be expressed as any combination of request headers, path variables, query string parameters, and body.
In addition, the Lambda function can use API configuration settings to influence its execution logic.
For an API developer, setting up a Lambda proxy integration is simple.
Other than choosing a particular Lambda function in a given region, you have little else to do.
API Gateway configures the integration request and integration response for you.
Once set up, the integrated API method can evolve with the backend without modifying the existing settings.
This is possible because the backend Lambda function developer parses the incoming request data and responds with desired results to the client when nothing goes wrong or responds with error messages when anything goes wrong.
Lambda non-proxy integration
You must ensure that input to the Lambda function is supplied as the integration request payload.
This implies that you, as an API developer, must map any input data the client supplied as request parameters into the proper integration request body.
You may also need to translate the client-supplied request body into a format recognized by the Lambda function.