# AWS::APIGatewayv2 Construct Library
<!--BEGIN STABILITY BANNER-->---
Features | Stability
-------------------------------------------|--------------------------------------------------------
CFN Resources | ![Stable](https://img.shields.io/badge/stable-success.svg?style=for-the-badge)
Higher level constructs for HTTP APIs | ![Experimental](https://img.shields.io/badge/experimental-important.svg?style=for-the-badge)
Higher level constructs for Websocket APIs | ![Experimental](https://img.shields.io/badge/experimental-important.svg?style=for-the-badge)
> **CFN Resources:** All classes with the `Cfn` prefix in this module ([CFN Resources](https://docs.aws.amazon.com/cdk/latest/guide/constructs.html#constructs_lib)) are always
> stable and safe to use.
<!-- -->
> **Experimental:** Higher level constructs in this module that are marked as experimental are
> under active development. They are subject to non-backward compatible changes or removal in any
> future version. These are not subject to the [Semantic Versioning](https://semver.org/) model and
> breaking changes will be announced in the release notes. This means that while you may use them,
> you may need to update your source code when upgrading to a newer version of this package.
---
<!--END STABILITY BANNER-->
## Table of Contents
* [Introduction](#introduction)
* [HTTP API](#http-api)
* [Defining HTTP APIs](#defining-http-apis)
* [Cross Origin Resource Sharing (CORS)](#cross-origin-resource-sharing-cors)
* [Publishing HTTP APIs](#publishing-http-apis)
* [Custom Domain](#custom-domain)
* [Mutual TLS](#mutual-tls-mtls)
* [Managing access to HTTP APIs](#managing-access-to-http-apis)
* [Metrics](#metrics)
* [VPC Link](#vpc-link)
* [Private Integration](#private-integration)
* [WebSocket API](#websocket-api)
* [Manage Connections Permission](#manage-connections-permission)
* [Managing access to WebSocket APIs](#managing-access-to-websocket-apis)
## Introduction
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](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html).
This module supports features under [API Gateway v2](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_ApiGatewayV2.html)
that lets users set up Websocket and HTTP APIs.
REST APIs can be created using the `@aws-cdk/aws-apigateway` module.
## HTTP 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.
### Defining HTTP APIs
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](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html). 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](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations.html).
Integrations are available at the `aws-apigatewayv2-integrations` module and more information is available in that module.
As an early example, the following code snippet configures a route `GET /books` with an HTTP proxy integration all
configures all other HTTP method calls to `/books` to a lambda proxy.
```python
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration, HttpLambdaIntegration
# books_default_fn: lambda.Function
get_books_integration = HttpUrlIntegration("GetBooksIntegration", "https://get-books-proxy.myproxy.internal")
books_default_integration = HttpLambdaIntegration("BooksIntegration", books_default_fn)
http_api = apigwv2.HttpApi(self, "HttpApi")
http_api.add_routes(
path="/books",
methods=[apigwv2.HttpMethod.GET],
integration=get_books_integration
)
http_api.add_routes(
path="/books",
methods=[apigwv2.HttpMethod.ANY],
integration=books_default_integration
)
```
The URL to the endpoint can be retrieved via the `apiEndpoint` attribute. By default this URL is enabled for clients. Use `disableExecuteApiEndpoint` to disable it.
```python
http_api = apigwv2.HttpApi(self, "HttpApi",
disable_execute_api_endpoint=True
)
```
The `defaultIntegration` 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.
```python
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration
apigwv2.HttpApi(self, "HttpProxyApi",
default_integration=HttpUrlIntegration("DefaultIntegration", "https://example.com")
)
```
### Cross Origin Resource Sharing (CORS)
[Cross-origin resource sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/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](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html).
The `corsPreflight` option lets you specify a CORS configuration for an API.
```python
apigwv2.HttpApi(self, "HttpProxyApi",
cors_preflight=apigwv2.CorsPreflightOptions(
allow_headers=["Authorization"],
allow_methods=[apigwv2.CorsHttpMethod.GET, apigwv2.CorsHttpMethod.HEAD, apigwv2.CorsHttpMethod.OPTIONS, apigwv2.CorsHttpMethod.POST
],
allow_origins=["*"],
max_age=Duration.days(10)
)
)
```
### Publishing HTTP APIs
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`.
```python
# api: apigwv2.HttpApi
apigwv2.HttpStage(self, "Stage",
http_api=api,
stage_name="beta"
)
```
If you omit the `stageName` 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 `createDefaultStage` property is unset.
### Custom Domain
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.
```python
import aws_cdk.aws_certificatemanager as acm
from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration
# handler: lambda.Function
cert_arn = "arn:aws:acm:us-east-1:111111111111:certificate"
domain_name = "example.com"
dn = apigwv2.DomainName(self, "DN",
domain_name=domain_name,
certificate=acm.Certificate.from_certificate_arn(self, "cert", cert_arn)
)
api = apigwv2.HttpApi(self, "HttpProxyProdApi",
default_integration=HttpLambdaIntegration("DefaultIntegration", handler),
# https://${dn.domainName}/foo goes to prodApi $default stage
default_domain_mapping=apigwv2.DomainMappingOptions(
domain_name=dn,
mapping_key="foo"
)
)
```
To migrate a domain endpoint from one type to another, you can add a new endpoint configuration via `addEndpoint()`
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](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-migrate.html)
To associate a specific `Stage` to a custom domain mapping -
```python
# api: apigwv2.HttpApi
# dn: apigwv2.DomainName
api.add_stage("beta",
stage_name="beta",
auto_deploy=True,
# https://${dn.domainName}/bar goes to the beta stage
domain_mapping=apigwv2.DomainMappingOptions(
domain_name=dn,
mapping_key="bar"
)
)
```
The same domain name can be associated with stages across different `HttpApi` as so -
```python
from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration
# handler: lambda.Function
# dn: apigwv2.DomainName
api_demo = apigwv2.HttpApi(self, "DemoApi",
default_integration=HttpLambdaIntegration("DefaultIntegration", handler),
# https://${dn.domainName}/demo goes to apiDemo $default stage
default_domain_mapping=apigwv2.DomainMappingOptions(
domain_name=dn,
mapping_key="demo"
)
)
```
The `mappingKey` determines the base path of the URL with the custom domain. Each custom domain is only allowed
to have one API mapping with undefined `mappingKey`. If more than one API mappings are specified, `mappingKey` 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 `domainUrl` property as so -
```python
# api_demo: apigwv2.HttpApi
demo_domain_url = api_demo.default_stage.domain_url
```
### Mutual TLS (mTLS)
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.
```python
import aws_cdk.aws_s3 as s3
import aws_cdk.aws_certificatemanager as acm
# bucket: s3.Bucket
cert_arn = "arn:aws:acm:us-east-1:111111111111:certificate"
domain_name = "example.com"
apigwv2.DomainName(self, "DomainName",
domain_name=domain_name,
certificate=acm.Certificate.from_certificate_arn(self, "cert", cert_arn),
mtls=apigwv2.MTLSConfig(
bucket=bucket,
key="someca.pem",
version="version"
)
)
```
Instructions for configuring your trust store can be found [here](https://aws.amazon.com/blogs/compute/introducing-mutual-tls-authentication-for-amazon-api-gateway/)
### Managing access to HTTP APIs
API Gateway supports multiple mechanisms for [controlling and managing access to your HTTP
API](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-access-control.html) through authorizers.
These authorizers can be found in the [APIGatewayV2-Authorizers](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigatewayv2-authorizers-readme.html) constructs library.
### Metrics
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.
```python
api = apigwv2.HttpApi(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.
```python
api = apigwv2.HttpApi(self, "my-api")
stage = apigwv2.HttpStage(self, "Stage",
http_api=api
)
client_error_metric = stage.metric_client_error()
```
### VPC Link
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.
```python
import aws_cdk.aws_ec2 as ec2
vpc = ec2.Vpc(self, "VPC")
vpc_link = apigwv2.VpcLink(self, "VpcLink", vpc=vpc)
```
Any existing `VpcLink` resource can be imported into the CDK app via the `VpcLink.fromVpcLinkAttributes()`.
```python
import aws_cdk.aws_ec2 as ec2
# vpc: ec2.Vpc
awesome_link = apigwv2.VpcLink.from_vpc_link_attributes(self, "awesome-vpc-link",
vpc_link_id="us-east-1_oiuR12Abd",
vpc=vpc
)
```
### Private Integration
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](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigatewayv2-integrations-readme.html) constructs library.
## WebSocket API
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](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-overview.html)
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](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integration-requests.html).
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:
```python
from aws_cdk.aws_apigatewayv2_integrations import WebSocketLambdaIntegration
# connect_handler: lambda.Function
# disconnect_handler: lambda.Function
# default_handler: lambda.Function
web_socket_api = apigwv2.WebSocketApi(self, "mywsapi",
connect_route_options=apigwv2.WebSocketRouteOptions(integration=WebSocketLambdaIntegration("ConnectIntegration", connect_handler)),
disconnect_route_options=apigwv2.WebSocketRouteOptions(integration=WebSocketLambdaIntegration("DisconnectIntegration", disconnect_handler)),
default_route_options=apigwv2.WebSocketRouteOptions(integration=WebSocketLambdaIntegration("DefaultIntegration", default_handler))
)
apigwv2.WebSocketStage(self, "mystage",
web_socket_api=web_socket_api,
stage_name="dev",
auto_deploy=True
)
```
To retrieve a websocket URL and a callback URL:
```python
# web_socket_stage: apigwv2.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:
```python
from aws_cdk.aws_apigatewayv2_integrations import WebSocketLambdaIntegration
# message_handler: lambda.Function
web_socket_api = apigwv2.WebSocketApi(self, "mywsapi")
web_socket_api.add_route("sendmessage",
integration=WebSocketLambdaIntegration("SendMessageIntegration", message_handler)
)
```
To import an existing WebSocketApi:
```python
web_socket_api = apigwv2.WebSocketApi.from_web_socket_api_attributes(self, "mywsapi", web_socket_id="api-1234")
```
### Manage Connections Permission
Grant permission to use API Gateway Management API of a WebSocket API by calling the `grantManageConnections` 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](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html).
```python
# fn: lambda.Function
web_socket_api = apigwv2.WebSocketApi(self, "mywsapi")
stage = apigwv2.WebSocketStage(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)
```
### Managing access to WebSocket APIs
API Gateway supports multiple mechanisms for [controlling and managing access to a WebSocket API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-control-access.html) through authorizers.
These authorizers can be found in the [APIGatewayV2-Authorizers](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigatewayv2-authorizers-readme.html) constructs library.
### API Keys
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](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html). 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:
```python
web_socket_api = apigwv2.WebSocketApi(self, "mywsapi",
api_key_selection_expression=apigwv2.WebSocketApiKeySelectionExpression.HEADER_X_API_KEY
)
```
Raw data
{
"_id": null,
"home_page": "https://github.com/aws/aws-cdk",
"name": "aws-cdk.aws-apigatewayv2",
"maintainer": "",
"docs_url": null,
"requires_python": "~=3.7",
"maintainer_email": "",
"keywords": "",
"author": "Amazon Web Services",
"author_email": "",
"download_url": "https://files.pythonhosted.org/packages/dd/83/86c7e0790edc1d059fec5be83bc1ccd23f7367f0ac704d15d0f0973a4cd2/aws-cdk.aws-apigatewayv2-1.203.0.tar.gz",
"platform": null,
"description": "# AWS::APIGatewayv2 Construct Library\n\n<!--BEGIN STABILITY BANNER-->---\n\n\nFeatures | Stability\n-------------------------------------------|--------------------------------------------------------\nCFN Resources | ![Stable](https://img.shields.io/badge/stable-success.svg?style=for-the-badge)\nHigher level constructs for HTTP APIs | ![Experimental](https://img.shields.io/badge/experimental-important.svg?style=for-the-badge)\nHigher level constructs for Websocket APIs | ![Experimental](https://img.shields.io/badge/experimental-important.svg?style=for-the-badge)\n\n> **CFN Resources:** All classes with the `Cfn` prefix in this module ([CFN Resources](https://docs.aws.amazon.com/cdk/latest/guide/constructs.html#constructs_lib)) are always\n> stable and safe to use.\n\n<!-- -->\n\n> **Experimental:** Higher level constructs in this module that are marked as experimental are\n> under active development. They are subject to non-backward compatible changes or removal in any\n> future version. These are not subject to the [Semantic Versioning](https://semver.org/) model and\n> breaking changes will be announced in the release notes. This means that while you may use them,\n> you may need to update your source code when upgrading to a newer version of this package.\n\n---\n<!--END STABILITY BANNER-->\n\n## Table of Contents\n\n* [Introduction](#introduction)\n* [HTTP API](#http-api)\n\n * [Defining HTTP APIs](#defining-http-apis)\n * [Cross Origin Resource Sharing (CORS)](#cross-origin-resource-sharing-cors)\n * [Publishing HTTP APIs](#publishing-http-apis)\n * [Custom Domain](#custom-domain)\n * [Mutual TLS](#mutual-tls-mtls)\n * [Managing access to HTTP APIs](#managing-access-to-http-apis)\n * [Metrics](#metrics)\n * [VPC Link](#vpc-link)\n * [Private Integration](#private-integration)\n* [WebSocket API](#websocket-api)\n\n * [Manage Connections Permission](#manage-connections-permission)\n * [Managing access to WebSocket APIs](#managing-access-to-websocket-apis)\n\n## Introduction\n\nAmazon API Gateway is an AWS service for creating, publishing, maintaining, monitoring, and securing REST, HTTP, and WebSocket\nAPIs at any scale. API developers can create APIs that access AWS or other web services, as well as data stored in the AWS Cloud.\nAs an API Gateway API developer, you can create APIs for use in your own client applications. Read the\n[Amazon API Gateway Developer Guide](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html).\n\nThis module supports features under [API Gateway v2](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_ApiGatewayV2.html)\nthat lets users set up Websocket and HTTP APIs.\nREST APIs can be created using the `@aws-cdk/aws-apigateway` module.\n\n## HTTP API\n\nHTTP APIs enable creation of RESTful APIs that integrate with AWS Lambda functions, known as Lambda proxy integration,\nor to any routable HTTP endpoint, known as HTTP proxy integration.\n\n### Defining HTTP APIs\n\nHTTP APIs have two fundamental concepts - Routes and Integrations.\n\nRoutes direct incoming API requests to backend resources. Routes consist of two parts: an HTTP method and a resource\npath, such as, `GET /books`. Learn more at [Working with\nroutes](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html). Use the `ANY` method\nto match any methods for a route that are not explicitly defined.\n\nIntegrations define how the HTTP API responds when a client reaches a specific Route. HTTP APIs support Lambda proxy\nintegration, HTTP proxy integration and, AWS service integrations, also known as private integrations. Learn more at\n[Configuring integrations](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations.html).\n\nIntegrations are available at the `aws-apigatewayv2-integrations` module and more information is available in that module.\nAs an early example, the following code snippet configures a route `GET /books` with an HTTP proxy integration all\nconfigures all other HTTP method calls to `/books` to a lambda proxy.\n\n```python\nfrom aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration, HttpLambdaIntegration\n\n# books_default_fn: lambda.Function\n\n\nget_books_integration = HttpUrlIntegration(\"GetBooksIntegration\", \"https://get-books-proxy.myproxy.internal\")\nbooks_default_integration = HttpLambdaIntegration(\"BooksIntegration\", books_default_fn)\n\nhttp_api = apigwv2.HttpApi(self, \"HttpApi\")\n\nhttp_api.add_routes(\n path=\"/books\",\n methods=[apigwv2.HttpMethod.GET],\n integration=get_books_integration\n)\nhttp_api.add_routes(\n path=\"/books\",\n methods=[apigwv2.HttpMethod.ANY],\n integration=books_default_integration\n)\n```\n\nThe URL to the endpoint can be retrieved via the `apiEndpoint` attribute. By default this URL is enabled for clients. Use `disableExecuteApiEndpoint` to disable it.\n\n```python\nhttp_api = apigwv2.HttpApi(self, \"HttpApi\",\n disable_execute_api_endpoint=True\n)\n```\n\nThe `defaultIntegration` option while defining HTTP APIs lets you create a default catch-all integration that is\nmatched when a client reaches a route that is not explicitly defined.\n\n```python\nfrom aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration\n\n\napigwv2.HttpApi(self, \"HttpProxyApi\",\n default_integration=HttpUrlIntegration(\"DefaultIntegration\", \"https://example.com\")\n)\n```\n\n### Cross Origin Resource Sharing (CORS)\n\n[Cross-origin resource sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) is a browser security\nfeature that restricts HTTP requests that are initiated from scripts running in the browser. Enabling CORS will allow\nrequests to your API from a web application hosted in a domain different from your API domain.\n\nWhen configured CORS for an HTTP API, API Gateway automatically sends a response to preflight `OPTIONS` requests, even\nif there isn't an `OPTIONS` route configured. Note that, when this option is used, API Gateway will ignore CORS headers\nreturned from your backend integration. Learn more about [Configuring CORS for an HTTP\nAPI](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html).\n\nThe `corsPreflight` option lets you specify a CORS configuration for an API.\n\n```python\napigwv2.HttpApi(self, \"HttpProxyApi\",\n cors_preflight=apigwv2.CorsPreflightOptions(\n allow_headers=[\"Authorization\"],\n allow_methods=[apigwv2.CorsHttpMethod.GET, apigwv2.CorsHttpMethod.HEAD, apigwv2.CorsHttpMethod.OPTIONS, apigwv2.CorsHttpMethod.POST\n ],\n allow_origins=[\"*\"],\n max_age=Duration.days(10)\n )\n)\n```\n\n### Publishing HTTP APIs\n\nA Stage is a logical reference to a lifecycle state of your API (for example, `dev`, `prod`, `beta`, or `v2`). API\nstages are identified by their stage name. Each stage is a named reference to a deployment of the API made available for\nclient applications to call.\n\nUse `HttpStage` to create a Stage resource for HTTP APIs. The following code sets up a Stage, whose URL is available at\n`https://{api_id}.execute-api.{region}.amazonaws.com/beta`.\n\n```python\n# api: apigwv2.HttpApi\n\n\napigwv2.HttpStage(self, \"Stage\",\n http_api=api,\n stage_name=\"beta\"\n)\n```\n\nIf you omit the `stageName` will create a `$default` stage. A `$default` stage is one that is served from the base of\nthe API's URL - `https://{api_id}.execute-api.{region}.amazonaws.com/`.\n\nNote that, `HttpApi` will always creates a `$default` stage, unless the `createDefaultStage` property is unset.\n\n### Custom Domain\n\nCustom domain names are simpler and more intuitive URLs that you can provide to your API users. Custom domain name are associated to API stages.\n\nThe code snippet below creates a custom domain and configures a default domain mapping for your API that maps the\ncustom domain to the `$default` stage of the API.\n\n```python\nimport aws_cdk.aws_certificatemanager as acm\nfrom aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration\n\n# handler: lambda.Function\n\n\ncert_arn = \"arn:aws:acm:us-east-1:111111111111:certificate\"\ndomain_name = \"example.com\"\n\ndn = apigwv2.DomainName(self, \"DN\",\n domain_name=domain_name,\n certificate=acm.Certificate.from_certificate_arn(self, \"cert\", cert_arn)\n)\napi = apigwv2.HttpApi(self, \"HttpProxyProdApi\",\n default_integration=HttpLambdaIntegration(\"DefaultIntegration\", handler),\n # https://${dn.domainName}/foo goes to prodApi $default stage\n default_domain_mapping=apigwv2.DomainMappingOptions(\n domain_name=dn,\n mapping_key=\"foo\"\n )\n)\n```\n\nTo migrate a domain endpoint from one type to another, you can add a new endpoint configuration via `addEndpoint()`\nand then configure DNS records to route traffic to the new endpoint. After that, you can remove the previous endpoint configuration.\nLearn more at [Migrating a custom domain name](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-migrate.html)\n\nTo associate a specific `Stage` to a custom domain mapping -\n\n```python\n# api: apigwv2.HttpApi\n# dn: apigwv2.DomainName\n\n\napi.add_stage(\"beta\",\n stage_name=\"beta\",\n auto_deploy=True,\n # https://${dn.domainName}/bar goes to the beta stage\n domain_mapping=apigwv2.DomainMappingOptions(\n domain_name=dn,\n mapping_key=\"bar\"\n )\n)\n```\n\nThe same domain name can be associated with stages across different `HttpApi` as so -\n\n```python\nfrom aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration\n\n# handler: lambda.Function\n# dn: apigwv2.DomainName\n\n\napi_demo = apigwv2.HttpApi(self, \"DemoApi\",\n default_integration=HttpLambdaIntegration(\"DefaultIntegration\", handler),\n # https://${dn.domainName}/demo goes to apiDemo $default stage\n default_domain_mapping=apigwv2.DomainMappingOptions(\n domain_name=dn,\n mapping_key=\"demo\"\n )\n)\n```\n\nThe `mappingKey` determines the base path of the URL with the custom domain. Each custom domain is only allowed\nto have one API mapping with undefined `mappingKey`. If more than one API mappings are specified, `mappingKey` will be required for all of them. In the sample above, the custom domain is associated\nwith 3 API mapping resources across different APIs and Stages.\n\n| API | Stage | URL |\n| :------------: | :---------: | :----: |\n| api | $default | `https://${domainName}/foo` |\n| api | beta | `https://${domainName}/bar` |\n| apiDemo | $default | `https://${domainName}/demo` |\n\nYou can retrieve the full domain URL with mapping key using the `domainUrl` property as so -\n\n```python\n# api_demo: apigwv2.HttpApi\n\ndemo_domain_url = api_demo.default_stage.domain_url\n```\n\n### Mutual TLS (mTLS)\n\nMutual 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.\n\n```python\nimport aws_cdk.aws_s3 as s3\nimport aws_cdk.aws_certificatemanager as acm\n# bucket: s3.Bucket\n\n\ncert_arn = \"arn:aws:acm:us-east-1:111111111111:certificate\"\ndomain_name = \"example.com\"\n\napigwv2.DomainName(self, \"DomainName\",\n domain_name=domain_name,\n certificate=acm.Certificate.from_certificate_arn(self, \"cert\", cert_arn),\n mtls=apigwv2.MTLSConfig(\n bucket=bucket,\n key=\"someca.pem\",\n version=\"version\"\n )\n)\n```\n\nInstructions for configuring your trust store can be found [here](https://aws.amazon.com/blogs/compute/introducing-mutual-tls-authentication-for-amazon-api-gateway/)\n\n### Managing access to HTTP APIs\n\nAPI Gateway supports multiple mechanisms for [controlling and managing access to your HTTP\nAPI](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-access-control.html) through authorizers.\n\nThese authorizers can be found in the [APIGatewayV2-Authorizers](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigatewayv2-authorizers-readme.html) constructs library.\n\n### Metrics\n\nThe API Gateway v2 service sends metrics around the performance of HTTP APIs to Amazon CloudWatch.\nThese metrics can be referred to using the metric APIs available on the `HttpApi` construct.\nThe APIs with the `metric` prefix can be used to get reference to specific metrics for this API. For example,\nthe method below refers to the client side errors metric for this API.\n\n```python\napi = apigwv2.HttpApi(self, \"my-api\")\nclient_error_metric = api.metric_client_error()\n```\n\nPlease 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\nthe `metric` methods from the `Stage` construct.\n\n```python\napi = apigwv2.HttpApi(self, \"my-api\")\nstage = apigwv2.HttpStage(self, \"Stage\",\n http_api=api\n)\nclient_error_metric = stage.metric_client_error()\n```\n\n### VPC Link\n\nPrivate integrations let HTTP APIs connect with AWS resources that are placed behind a VPC. These are usually Application\nLoad Balancers, Network Load Balancers or a Cloud Map service. The `VpcLink` construct enables this integration.\nThe following code creates a `VpcLink` to a private VPC.\n\n```python\nimport aws_cdk.aws_ec2 as ec2\n\n\nvpc = ec2.Vpc(self, \"VPC\")\nvpc_link = apigwv2.VpcLink(self, \"VpcLink\", vpc=vpc)\n```\n\nAny existing `VpcLink` resource can be imported into the CDK app via the `VpcLink.fromVpcLinkAttributes()`.\n\n```python\nimport aws_cdk.aws_ec2 as ec2\n\n# vpc: ec2.Vpc\n\nawesome_link = apigwv2.VpcLink.from_vpc_link_attributes(self, \"awesome-vpc-link\",\n vpc_link_id=\"us-east-1_oiuR12Abd\",\n vpc=vpc\n)\n```\n\n### Private Integration\n\nPrivate integrations enable integrating an HTTP API route with private resources in a VPC, such as Application Load Balancers or\nAmazon ECS container-based applications. Using private integrations, resources in a VPC can be exposed for access by\nclients outside of the VPC.\n\nThese integrations can be found in the [aws-apigatewayv2-integrations](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigatewayv2-integrations-readme.html) constructs library.\n\n## WebSocket API\n\nA WebSocket API in API Gateway is a collection of WebSocket routes that are integrated with backend HTTP endpoints,\nLambda functions, or other AWS services. You can use API Gateway features to help you with all aspects of the API\nlifecycle, from creation through monitoring your production APIs. [Read more](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-overview.html)\n\nWebSocket APIs have two fundamental concepts - Routes and Integrations.\n\nWebSocket APIs direct JSON messages to backend integrations based on configured routes. (Non-JSON messages are directed\nto the configured `$default` route.)\n\nIntegrations define how the WebSocket API behaves when a client reaches a specific Route. Learn more at\n[Configuring integrations](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integration-requests.html).\n\nIntegrations are available in the `aws-apigatewayv2-integrations` module and more information is available in that module.\n\nTo add the default WebSocket routes supported by API Gateway (`$connect`, `$disconnect` and `$default`), configure them as part of api props:\n\n```python\nfrom aws_cdk.aws_apigatewayv2_integrations import WebSocketLambdaIntegration\n\n# connect_handler: lambda.Function\n# disconnect_handler: lambda.Function\n# default_handler: lambda.Function\n\n\nweb_socket_api = apigwv2.WebSocketApi(self, \"mywsapi\",\n connect_route_options=apigwv2.WebSocketRouteOptions(integration=WebSocketLambdaIntegration(\"ConnectIntegration\", connect_handler)),\n disconnect_route_options=apigwv2.WebSocketRouteOptions(integration=WebSocketLambdaIntegration(\"DisconnectIntegration\", disconnect_handler)),\n default_route_options=apigwv2.WebSocketRouteOptions(integration=WebSocketLambdaIntegration(\"DefaultIntegration\", default_handler))\n)\n\napigwv2.WebSocketStage(self, \"mystage\",\n web_socket_api=web_socket_api,\n stage_name=\"dev\",\n auto_deploy=True\n)\n```\n\nTo retrieve a websocket URL and a callback URL:\n\n```python\n# web_socket_stage: apigwv2.WebSocketStage\n\n\nweb_socket_uRL = web_socket_stage.url\n# wss://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}\ncallback_uRL = web_socket_stage.callback_url\n```\n\nTo add any other route:\n\n```python\nfrom aws_cdk.aws_apigatewayv2_integrations import WebSocketLambdaIntegration\n\n# message_handler: lambda.Function\n\nweb_socket_api = apigwv2.WebSocketApi(self, \"mywsapi\")\nweb_socket_api.add_route(\"sendmessage\",\n integration=WebSocketLambdaIntegration(\"SendMessageIntegration\", message_handler)\n)\n```\n\nTo import an existing WebSocketApi:\n\n```python\nweb_socket_api = apigwv2.WebSocketApi.from_web_socket_api_attributes(self, \"mywsapi\", web_socket_id=\"api-1234\")\n```\n\n### Manage Connections Permission\n\nGrant permission to use API Gateway Management API of a WebSocket API by calling the `grantManageConnections` API.\nYou 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](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html).\n\n```python\n# fn: lambda.Function\n\n\nweb_socket_api = apigwv2.WebSocketApi(self, \"mywsapi\")\nstage = apigwv2.WebSocketStage(self, \"mystage\",\n web_socket_api=web_socket_api,\n stage_name=\"dev\"\n)\n# per stage permission\nstage.grant_management_api_access(fn)\n# for all the stages permission\nweb_socket_api.grant_manage_connections(fn)\n```\n\n### Managing access to WebSocket APIs\n\nAPI Gateway supports multiple mechanisms for [controlling and managing access to a WebSocket API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-control-access.html) through authorizers.\n\nThese authorizers can be found in the [APIGatewayV2-Authorizers](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigatewayv2-authorizers-readme.html) constructs library.\n\n### API Keys\n\nWebsocket 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](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html). These together allow you to configure controls around API access such as quotas and throttling, along with per-API Key metrics on usage.\n\nTo require an API Key when accessing the Websocket API:\n\n```python\nweb_socket_api = apigwv2.WebSocketApi(self, \"mywsapi\",\n api_key_selection_expression=apigwv2.WebSocketApiKeySelectionExpression.HEADER_X_API_KEY\n)\n```\n\n\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "The CDK Construct Library for AWS::APIGatewayv2",
"version": "1.203.0",
"project_urls": {
"Homepage": "https://github.com/aws/aws-cdk",
"Source": "https://github.com/aws/aws-cdk.git"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "0cad506495e8025a6bcbf85e05496ca5ae43bec7f0917bbd2f9a00113832d303",
"md5": "7079c17cf2a15e81601da8b8d96ddf02",
"sha256": "8a9dab703c7cde2895e55bb8f762bb653dbbb79ab295fb70ca2fef8a125ee01c"
},
"downloads": -1,
"filename": "aws_cdk.aws_apigatewayv2-1.203.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "7079c17cf2a15e81601da8b8d96ddf02",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "~=3.7",
"size": 452638,
"upload_time": "2023-05-31T22:52:28",
"upload_time_iso_8601": "2023-05-31T22:52:28.850933Z",
"url": "https://files.pythonhosted.org/packages/0c/ad/506495e8025a6bcbf85e05496ca5ae43bec7f0917bbd2f9a00113832d303/aws_cdk.aws_apigatewayv2-1.203.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "dd8386c7e0790edc1d059fec5be83bc1ccd23f7367f0ac704d15d0f0973a4cd2",
"md5": "bb876f4e636f16591d69eaab06383473",
"sha256": "c6b0a2de4c585655f4390445d7e328131d3ac4b4d6001b1cd10b57b078e8f093"
},
"downloads": -1,
"filename": "aws-cdk.aws-apigatewayv2-1.203.0.tar.gz",
"has_sig": false,
"md5_digest": "bb876f4e636f16591d69eaab06383473",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "~=3.7",
"size": 451552,
"upload_time": "2023-05-31T23:00:30",
"upload_time_iso_8601": "2023-05-31T23:00:30.259441Z",
"url": "https://files.pythonhosted.org/packages/dd/83/86c7e0790edc1d059fec5be83bc1ccd23f7367f0ac704d15d0f0973a4cd2/aws-cdk.aws-apigatewayv2-1.203.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-05-31 23:00:30",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "aws",
"github_project": "aws-cdk",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "aws-cdk.aws-apigatewayv2"
}