149 types
Amazon API Gateway is an AWS service for creating, publishing, maintaining, monitoring, and securing REST, HTTP, and WebSocket APIs at any scale. API developers can create APIs that access AWS or other web services, as well as data stored in the AWS Cloud. As an API Gateway API developer, you can create APIs for use in your own client applications. Read the Amazon API Gateway Developer Guide.
This module supports features under API Gateway v2
that lets users set up Websocket and HTTP APIs.
REST APIs can be created using the aws-cdk-lib/aws-apigateway module.
HTTP and Websocket APIs use the same CloudFormation resources under the hood. However, this module separates them into two separate constructs for a more efficient abstraction since there are a number of CloudFormation properties that specifically apply only to each type of API.
HTTP APIs enable creation of RESTful APIs that integrate with AWS Lambda functions, known as Lambda proxy integration, or to any routable HTTP endpoint, known as HTTP proxy integration.
HTTP APIs have two fundamental concepts - Routes and Integrations.
Routes direct incoming API requests to backend resources. Routes consist of two parts: an HTTP method and a resource
path, such as, GET /books. Learn more at Working with
routes. Use the ANY method
to match any methods for a route that are not explicitly defined.
Integrations define how the HTTP API responds when a client reaches a specific Route. HTTP APIs support Lambda proxy integration, HTTP proxy integration and, AWS service integrations, also known as private integrations. Learn more at Configuring integrations.
Integrations are available at the aws-apigatewayv2-integrations module and more information is available in that module.
As an early example, we have a website for a bookstore where the following code snippet configures a route GET /books with an HTTP proxy integration. All other HTTP method calls to /books route to a default lambda proxy for the bookstore.
require 'aws-cdk-lib'
book_store_default_fn = nil # AWSCDK::Lambda::Function
get_books_integration = AWSCDK::APIGatewayv2Integrations::HttpURLIntegration.new("GetBooksIntegration", "https://get-books-proxy.example.com")
book_store_default_integration = AWSCDK::APIGatewayv2Integrations::HttpLambdaIntegration.new("BooksIntegration", book_store_default_fn)
http_api = AWSCDK::APIGatewayv2::HttpAPI.new(self, "HttpApi")
http_api.add_routes({
path: "/books",
methods: [AWSCDK::APIGatewayv2::HttpMethod::GET],
integration: get_books_integration,
})
http_api.add_routes({
path: "/books",
methods: [AWSCDK::APIGatewayv2::HttpMethod::ANY],
integration: book_store_default_integration,
})
The URL to the endpoint can be retrieved via the api_endpoint attribute. By default this URL is enabled for clients. Use disable_execute_api_endpoint to disable it.
http_api = AWSCDK::APIGatewayv2::HttpAPI.new(self, "HttpApi", {
disable_execute_api_endpoint: true,
})
The default_integration option while defining HTTP APIs lets you create a default catch-all integration that is
matched when a client reaches a route that is not explicitly defined.
require 'aws-cdk-lib'
AWSCDK::APIGatewayv2::HttpAPI.new(self, "HttpProxyApi", {
default_integration: AWSCDK::APIGatewayv2Integrations::HttpURLIntegration.new("DefaultIntegration", "https://example.com"),
})
The route_selection_expression option allows configuring the HTTP API to accept only ${request.method} ${request.path}. Setting it to true automatically applies this value.
AWSCDK::APIGatewayv2::HttpAPI.new(self, "HttpProxyApi", {
route_selection_expression: true,
})
You can configure IP address type for the API endpoint using ip_address_type property.
Valid values are IPV4 (default) and DUAL_STACK.
AWSCDK::APIGatewayv2::HttpAPI.new(self, "HttpApi", {
ip_address_type: AWSCDK::APIGatewayv2::IPAddressType::DUAL_STACK,
})
Cross-origin resource sharing (CORS) is a browser security feature that restricts HTTP requests that are initiated from scripts running in the browser. Enabling CORS will allow requests to your API from a web application hosted in a domain different from your API domain.
When configured CORS for an HTTP API, API Gateway automatically sends a response to preflight OPTIONS requests, even
if there isn't an OPTIONS route configured. Note that, when this option is used, API Gateway will ignore CORS headers
returned from your backend integration. Learn more about Configuring CORS for an HTTP
API.
The cors_preflight option lets you specify a CORS configuration for an API.
AWSCDK::APIGatewayv2::HttpAPI.new(self, "HttpProxyApi", {
cors_preflight: {
allow_headers: ["Authorization"],
allow_methods: [
AWSCDK::APIGatewayv2::CorsHttpMethod::GET,
AWSCDK::APIGatewayv2::CorsHttpMethod::HEAD,
AWSCDK::APIGatewayv2::CorsHttpMethod::OPTIONS,
AWSCDK::APIGatewayv2::CorsHttpMethod::POST,
],
allow_origins: ["*"],
max_age: AWSCDK::Duration.days(10),
},
})
A Stage is a logical reference to a lifecycle state of your API (for example, dev, prod, beta, or v2). API
stages are identified by their stage name. Each stage is a named reference to a deployment of the API made available for
client applications to call.
Use HttpStage to create a Stage resource for HTTP APIs. The following code sets up a Stage, whose URL is available at
https://{api_id}.execute-api.{region}.amazonaws.com/beta.
api = nil # AWSCDK::APIGatewayv2::HttpAPI
AWSCDK::APIGatewayv2::HttpStage.new(self, "Stage", {
http_api: api,
stage_name: "beta",
description: "My Stage",
})
If you omit the stage_name will create a $default stage. A $default stage is one that is served from the base of
the API's URL - https://{api_id}.execute-api.{region}.amazonaws.com/.
Note that, HttpApi will always creates a $default stage, unless the create_default_stage property is unset.
Custom domain names are simpler and more intuitive URLs that you can provide to your API users. Custom domain name are associated to API stages.
The code snippet below creates a custom domain and configures a default domain mapping for your API that maps the
custom domain to the $default stage of the API.
require 'aws-cdk-lib'
handler = nil # AWSCDK::Lambda::Function
cert_arn = "arn:aws:acm:us-east-1:111111111111:certificate"
domain_name = "example.com"
dn = AWSCDK::APIGatewayv2::DomainName.new(self, "DN", {
domain_name: domain_name,
certificate: AWSCDK::CertificateManager::Certificate.from_certificate_arn(self, "cert", cert_arn),
})
api = AWSCDK::APIGatewayv2::HttpAPI.new(self, "HttpProxyProdApi", {
default_integration: AWSCDK::APIGatewayv2Integrations::HttpLambdaIntegration.new("DefaultIntegration", handler),
# https://${dn.domainName}/foo goes to prodApi $default stage
default_domain_mapping: {
domain_name: dn,
mapping_key: "foo",
},
})
The IP address type for the domain name can be configured by using the ip_address_type
property. Valid values are IPV4 (default) and DUAL_STACK.
require 'aws-cdk-lib'
certificate = nil # AWSCDK::CertificateManager::ICertificate
domain_name = nil
dn = AWSCDK::APIGatewayv2::DomainName.new(self, "DN", {
domain_name: domain_name,
certificate: certificate,
ip_address_type: AWSCDK::APIGatewayv2::IPAddressType::DUAL_STACK,
})
To migrate a domain endpoint from one type to another, you can add a new endpoint configuration via add_endpoint()
and then configure DNS records to route traffic to the new endpoint. After that, you can remove the previous endpoint configuration.
Learn more at Migrating a custom domain name
To associate a specific Stage to a custom domain mapping -
api = nil # AWSCDK::APIGatewayv2::HttpAPI
dn = nil # AWSCDK::APIGatewayv2::DomainName
api.add_stage("beta", {
stage_name: "beta",
auto_deploy: true,
# https://${dn.domainName}/bar goes to the beta stage
domain_mapping: {
domain_name: dn,
mapping_key: "bar",
},
})
The same domain name can be associated with stages across different HttpApi as so -
require 'aws-cdk-lib'
handler = nil # AWSCDK::Lambda::Function
dn = nil # AWSCDK::APIGatewayv2::DomainName
api_demo = AWSCDK::APIGatewayv2::HttpAPI.new(self, "DemoApi", {
default_integration: AWSCDK::APIGatewayv2Integrations::HttpLambdaIntegration.new("DefaultIntegration", handler),
# https://${dn.domainName}/demo goes to apiDemo $default stage
default_domain_mapping: {
domain_name: dn,
mapping_key: "demo",
},
})
The mapping_key determines the base path of the URL with the custom domain. Each custom domain is only allowed
to have one API mapping with undefined mapping_key. If more than one API mappings are specified, mapping_key will be required for all of them. In the sample above, the custom domain is associated
with 3 API mapping resources across different APIs and Stages.
| API | Stage | URL |
|---|---|---|
| api | $default | https://${domainName}/foo |
| api | beta | https://${domainName}/bar |
| apiDemo | $default | https://${domainName}/demo |
You can retrieve the full domain URL with mapping key using the domain_url property as so -
api_demo = nil # AWSCDK::APIGatewayv2::HttpAPI
demo_domain_url = api_demo.default_stage&.domain_url
Mutual TLS can be configured to limit access to your API based by using client certificates instead of (or as an extension of) using authorization headers.
require 'aws-cdk-lib'
bucket = nil # AWSCDK::S3::Bucket
cert_arn = "arn:aws:acm:us-east-1:111111111111:certificate"
domain_name = "example.com"
AWSCDK::APIGatewayv2::DomainName.new(self, "DomainName", {
domain_name: domain_name,
certificate: AWSCDK::CertificateManager::Certificate.from_certificate_arn(self, "cert", cert_arn),
mtls: {
bucket: bucket,
key: "someca.pem",
version: "version",
},
})
Instructions for configuring your trust store can be found here
API Gateway supports multiple mechanisms for controlling and managing access to your HTTP API through authorizers.
These authorizers can be found in the APIGatewayV2-Authorizers constructs library.
The API Gateway v2 service sends metrics around the performance of HTTP APIs to Amazon CloudWatch.
These metrics can be referred to using the metric APIs available on the HttpApi construct.
The APIs with the metric prefix can be used to get reference to specific metrics for this API. For example,
the method below refers to the client side errors metric for this API.
api = AWSCDK::APIGatewayv2::HttpAPI.new(self, "my-api")
client_error_metric = api.metric_client_error
Please note that this will return a metric for all the stages defined in the api. It is also possible to refer to metrics for a specific Stage using
the metric methods from the Stage construct.
api = AWSCDK::APIGatewayv2::HttpAPI.new(self, "my-api")
stage = AWSCDK::APIGatewayv2::HttpStage.new(self, "Stage", {
http_api: api,
})
client_error_metric = stage.metric_client_error
Private integrations let HTTP APIs connect with AWS resources that are placed behind a VPC. These are usually Application
Load Balancers, Network Load Balancers or a Cloud Map service. The VpcLink construct enables this integration.
The following code creates a VpcLink to a private VPC.
require 'aws-cdk-lib'
vpc = AWSCDK::EC2::VPC.new(self, "VPC")
alb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(self, "AppLoadBalancer", {vpc: vpc})
vpc_link = AWSCDK::APIGatewayv2::VPCLink.new(self, "VpcLink", {vpc: vpc})
# Creating an HTTP ALB Integration:
alb_integration = AWSCDK::APIGatewayv2Integrations::HttpALBIntegration.new("ALBIntegration", alb.listeners[0], {})
Any existing VpcLink resource can be imported into the CDK app via the VpcLink.fromVpcLinkAttributes().
require 'aws-cdk-lib'
vpc = nil # AWSCDK::EC2::VPC
awesome_link = AWSCDK::APIGatewayv2::VPCLink.from_vpc_link_attributes(self, "awesome-vpc-link", {
vpc_link_id: "us-east-1_oiuR12Abd",
vpc: vpc,
})
Private integrations enable integrating an HTTP API route with private resources in a VPC, such as Application Load Balancers or Amazon ECS container-based applications. Using private integrations, resources in a VPC can be exposed for access by clients outside of the VPC.
These integrations can be found in the aws-apigatewayv2-integrations constructs library.
The arnForExecuteApi function in AWS CDK is designed to generate Amazon Resource Names (ARNs) for Execute API operations. This is particularly useful when you need to create ARNs dynamically based on different parameters like HTTP method, API path, and stage.
api = AWSCDK::APIGatewayv2::HttpAPI.new(self, "my-api")
arn = api.arn_for_execute_api("GET", "/myApiPath", "dev")
A WebSocket API in API Gateway is a collection of WebSocket routes that are integrated with backend HTTP endpoints, Lambda functions, or other AWS services. You can use API Gateway features to help you with all aspects of the API lifecycle, from creation through monitoring your production APIs. Read more
WebSocket APIs have two fundamental concepts - Routes and Integrations.
WebSocket APIs direct JSON messages to backend integrations based on configured routes. (Non-JSON messages are directed
to the configured $default route.)
Integrations define how the WebSocket API behaves when a client reaches a specific Route. Learn more at Configuring integrations.
Integrations are available in the aws-apigatewayv2-integrations module and more information is available in that module.
To add the default WebSocket routes supported by API Gateway ($connect, $disconnect and $default), configure them as part of api props:
require 'aws-cdk-lib'
connect_handler = nil # AWSCDK::Lambda::Function
disconnect_handler = nil # AWSCDK::Lambda::Function
default_handler = nil # AWSCDK::Lambda::Function
web_socket_api = AWSCDK::APIGatewayv2::WebSocketAPI.new(self, "mywsapi", {
connect_route_options: {integration: AWSCDK::APIGatewayv2Integrations::WebSocketLambdaIntegration.new("ConnectIntegration", connect_handler)},
disconnect_route_options: {integration: AWSCDK::APIGatewayv2Integrations::WebSocketLambdaIntegration.new("DisconnectIntegration", disconnect_handler)},
default_route_options: {integration: AWSCDK::APIGatewayv2Integrations::WebSocketLambdaIntegration.new("DefaultIntegration", default_handler)},
})
AWSCDK::APIGatewayv2::WebSocketStage.new(self, "mystage", {
web_socket_api: web_socket_api,
stage_name: "dev",
description: "My Stage",
auto_deploy: true,
})
To retrieve a websocket URL and a callback URL:
web_socket_stage = nil # AWSCDK::APIGatewayv2::WebSocketStage
web_socket_url = web_socket_stage.url
# wss://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}
callback_url = web_socket_stage.callback_url
To add any other route:
require 'aws-cdk-lib'
= nil # AWSCDK::Lambda::Function
web_socket_api = AWSCDK::APIGatewayv2::WebSocketAPI.new(self, "mywsapi")
web_socket_api.add_route("sendmessage", {
integration: AWSCDK::APIGatewayv2Integrations::WebSocketLambdaIntegration.new("SendMessageIntegration", ),
})
To add a route that can return a result:
require 'aws-cdk-lib'
= nil # AWSCDK::Lambda::Function
web_socket_api = AWSCDK::APIGatewayv2::WebSocketAPI.new(self, "mywsapi")
web_socket_api.add_route("sendmessage", {
integration: AWSCDK::APIGatewayv2Integrations::WebSocketLambdaIntegration.new("SendMessageIntegration", ),
return_response: true,
})
To import an existing WebSocketApi:
web_socket_api = AWSCDK::APIGatewayv2::WebSocketAPI.from_web_socket_api_attributes(self, "mywsapi", {web_socket_id: "api-1234"})
To generate an ARN for Execute API:
api = AWSCDK::APIGatewayv2::WebSocketAPI.new(self, "mywsapi")
arn = api.arn_for_execute_api_v2("$connect", "dev")
For a detailed explanation of this function, including usage and examples, please refer to the Generating ARN for Execute API section under HTTP API.
To disable schema validation, set disable_schema_validation to true.
AWSCDK::APIGatewayv2::WebSocketAPI.new(self, "api", {
disable_schema_validation: true,
})
You can configure IP address type for the API endpoint using ip_address_type property.
Valid values are IPV4 (default) and DUAL_STACK.
AWSCDK::APIGatewayv2::WebSocketAPI.new(self, "WebSocketApi", {
ip_address_type: AWSCDK::APIGatewayv2::IPAddressType::DUAL_STACK,
})
Grant permission to use API Gateway Management API of a WebSocket API by calling the grant_manage_connections API.
You can use Management API to send a callback message to a connected client, get connection information, or disconnect the client. Learn more at Use @connections commands in your backend service.
fn = nil # AWSCDK::Lambda::Function
web_socket_api = AWSCDK::APIGatewayv2::WebSocketAPI.new(self, "mywsapi")
stage = AWSCDK::APIGatewayv2::WebSocketStage.new(self, "mystage", {
web_socket_api: web_socket_api,
stage_name: "dev",
})
# per stage permission
stage.grant_management_api_access(fn)
# for all the stages permission
web_socket_api.grant_manage_connections(fn)
API Gateway supports multiple mechanisms for controlling and managing access to a WebSocket API through authorizers.
These authorizers can be found in the APIGatewayV2-Authorizers constructs library.
Websocket APIs also support usage of API Keys. An API Key is a key that is used to grant access to an API. These are useful for controlling and tracking access to an API, when used together with usage plans. These together allow you to configure controls around API access such as quotas and throttling, along with per-API Key metrics on usage.
To require an API Key when accessing the Websocket API:
web_socket_api = AWSCDK::APIGatewayv2::WebSocketAPI.new(self, "mywsapi", {
api_key_selection_expression: AWSCDK::APIGatewayv2::WebSocketAPIKeySelectionExpression.HEADER_X_API_KEY,
})
A usage plan specifies who can access one or more deployed WebSocket API stages, and the rate at which they can be accessed. The plan uses API keys to identify API clients and meters access to the associated API stages for each key. Usage plans also allow configuring throttling limits and quota limits that are enforced on individual client API keys.
The following example shows how to create and associate a usage plan and an API key for WebSocket APIs:
api_key = AWSCDK::APIGatewayv2::APIKey.new(self, "ApiKey")
usage_plan = AWSCDK::APIGatewayv2::UsagePlan.new(self, "UsagePlan", {
usage_plan_name: "WebSocketUsagePlan",
throttle: {
rate_limit: 10,
burst_limit: 2,
},
})
usage_plan.add_api_key(api_key)
To associate a plan to a given WebSocketAPI stage:
api = AWSCDK::APIGatewayv2::WebSocketAPI.new(self, "my-api")
stage = AWSCDK::APIGatewayv2::WebSocketStage.new(self, "my-stage", {
web_socket_api: api,
stage_name: "dev",
})
usage_plan = AWSCDK::APIGatewayv2::UsagePlan.new(self, "my-usage-plan", {
usage_plan_name: "Basic",
})
usage_plan.add_api_stage({
api: api,
stage: stage,
})
Existing usage plans can be imported into a CDK app using its id.
usage_plan = AWSCDK::APIGatewayv2::UsagePlan.from_usage_plan_id(self, "imported-usage-plan", "<usage-plan-id>")
The name and value of the API Key can be specified at creation; if not provided, a name and a value will be automatically generated by API Gateway.
# Auto-generated name and value
auto_key = AWSCDK::APIGatewayv2::APIKey.new(self, "AutoKey")
# Explicit name and value
explicit_key = AWSCDK::APIGatewayv2::APIKey.new(self, "ExplicitKey", {
api_key_name: "MyWebSocketApiKey",
value: "MyApiKeyThatIsAtLeast20Characters",
})
Existing API keys can also be imported into a CDK app using its id.
imported_key = AWSCDK::APIGatewayv2::APIKey.from_api_key_id(self, "imported-key", "<api-key-id>")
The "grant" methods can be used to give prepackaged sets of permissions to other resources. The following code provides read permission to an API key.
require 'aws-cdk-lib'
user = AWSCDK::IAM::User.new(self, "User")
api_key = AWSCDK::APIGatewayv2::APIKey.new(self, "ApiKey", {
customer_id: "test-customer",
})
api_key.grant_read(user)
API Keys for WebSocket APIs are associated through Usage Plans, not directly to stages. When you import a WebSocketApi, you need to create a Usage Plan that references the imported stage and then associate the API key with that Usage Plan.
web_socket_api = nil # AWSCDK::APIGatewayv2::IWebSocketAPI
imported_stage = AWSCDK::APIGatewayv2::WebSocketStage.from_web_socket_stage_attributes(self, "imported-stage", {
stage_name: "myStage",
api: web_socket_api,
})
api_key = AWSCDK::APIGatewayv2::APIKey.new(self, "MyApiKey")
usage_plan = AWSCDK::APIGatewayv2::UsagePlan.new(self, "MyUsagePlan", {
api_stages: [{api: web_socket_api, stage: imported_stage}],
})
usage_plan.add_api_key(api_key)
It is possible to specify multiple API keys for a given Usage Plan, by calling usagePlan.addApiKey().
When using multiple API keys, you may need to ensure that the CloudFormation logical ids of the API keys remain consistent across deployments. You can set the logical id as part of the add_api_key() method
usage_plan = nil # AWSCDK::APIGatewayv2::UsagePlan
api_key = nil # AWSCDK::APIGatewayv2::APIKey
usage_plan.add_api_key(api_key, {
override_logical_id: "MyCustomLogicalId",
})
In scenarios where you need to create a single api key and configure rate limiting for it, you can use RateLimitedApiKey.
This construct lets you specify rate limiting properties which should be applied only to the api key being created.
The API key created has the specified rate limits, such as quota and throttles, applied.
The following example shows how to use a rate limited api key :
api = nil # AWSCDK::APIGatewayv2::WebSocketAPI
stage = nil # AWSCDK::APIGatewayv2::WebSocketStage
key = AWSCDK::APIGatewayv2::RateLimitedAPIKey.new(self, "rate-limited-api-key", {
customer_id: "test-customer",
api_stages: [
{
api: api,
stage: stage,
},
],
quota: {
limit: 10000,
period: AWSCDK::APIGatewayv2::Period::MONTH,
},
throttle: {
rate_limit: 100,
burst_limit: 200,
},
})
Common config for both HTTP API and WebSocket API
Represents a collection of route settings.
api = nil # AWSCDK::APIGatewayv2::HttpAPI
AWSCDK::APIGatewayv2::HttpStage.new(self, "Stage", {
http_api: api,
throttle: {
rate_limit: 1000,
burst_limit: 1000,
},
detailed_metrics_enabled: true,
})
You can turn on logging to write logs to CloudWatch Logs. Read more at Configure logging for HTTP APIs or WebSocket APIs
require 'aws-cdk-lib'
http_api = nil # AWSCDK::APIGatewayv2::HttpAPI
web_socket_api = nil # AWSCDK::APIGatewayv2::WebSocketAPI
log_group = nil # AWSCDK::Logs::LogGroup
AWSCDK::APIGatewayv2::HttpStage.new(self, "HttpStage", {
http_api: http_api,
access_log_settings: {
destination: AWSCDK::APIGatewayv2::LogGroupLogDestination.new(log_group),
},
})
AWSCDK::APIGatewayv2::WebSocketStage.new(self, "WebSocketStage", {
web_socket_api: web_socket_api,
stage_name: "dev",
access_log_settings: {
destination: AWSCDK::APIGatewayv2::LogGroupLogDestination.new(log_group),
},
})
The following code will generate the access log in the CLF format.
require 'aws-cdk-lib'
api = nil # AWSCDK::APIGatewayv2::HttpAPI
log_group = nil # AWSCDK::Logs::LogGroup
stage = AWSCDK::APIGatewayv2::HttpStage.new(self, "Stage", {
http_api: api,
access_log_settings: {
destination: AWSCDK::APIGatewayv2::LogGroupLogDestination.new(log_group),
format: AWSCDK::APIGateway::AccessLogFormat.clf,
},
})
You can also configure your own access log format by using the AccessLogFormat.custom() API.
AccessLogField provides commonly used fields. The following code configures access log to contain.
require 'aws-cdk-lib'
api = nil # AWSCDK::APIGatewayv2::HttpAPI
log_group = nil # AWSCDK::Logs::LogGroup
stage = AWSCDK::APIGatewayv2::HttpStage.new(self, "Stage", {
http_api: api,
access_log_settings: {
destination: AWSCDK::APIGatewayv2::LogGroupLogDestination.new(log_group),
format: AWSCDK::APIGateway::AccessLogFormat.custom("#{AWSCDK::APIGateway::AccessLogField.context_request_id} #{AWSCDK::APIGateway::AccessLogField.} #{AWSCDK::APIGateway::AccessLogField.}
#{AWSCDK::APIGateway::AccessLogField.} #{AWSCDK::APIGateway::AccessLogField.}"),
},
})