Package: aws-cdk.aws-apigatewayv2-alpha
AWS::APIGatewayv2 Construct Library---This API may emit warnings. Backward compatibility is not guaranteed.All constructs moved to aws-cdk-lib/aws-apigatewayv2.Table of ContentsIntroductionHTTP APIDefining HTTP APIsCross Origin Resource Sharing (CORS)Publishing HTTP APIsCustom DomainMutual TLSManaging access to HTTP APIsMetricsVPC LinkPrivate IntegrationWebSocket APIManage Connections PermissionManaging access to WebSocket APIsIntroductionAmazon 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 theAmazon API Gateway Developer Guide.This module supports features underAPI Gateway v2that lets users set up Websocket and HTTP APIs.
REST APIs can be created using theaws-cdk-lib/aws-apigatewaymodule.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 APIHTTP 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 APIsHTTP 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 atWorking with
routes. Use theANYmethod
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 atConfiguring integrations.Integrations are available at theaws-apigatewayv2-integrationsmodule 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 routeGET /bookswith an HTTP proxy integration. All other HTTP method calls to/booksroute to a default lambda proxy for the bookstore.fromaws_cdk.aws_apigatewayv2_integrations_alphaimportHttpUrlIntegration,HttpLambdaIntegration# book_store_default_fn: lambda.Functionget_books_integration=HttpUrlIntegration("GetBooksIntegration","https://get-books-proxy.example.com")book_store_default_integration=HttpLambdaIntegration("BooksIntegration",book_store_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=book_store_default_integration)The URL to the endpoint can be retrieved via theapiEndpointattribute. By default this URL is enabled for clients. UsedisableExecuteApiEndpointto disable it.http_api=apigwv2.HttpApi(self,"HttpApi",disable_execute_api_endpoint=True)ThedefaultIntegrationoption 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.fromaws_cdk.aws_apigatewayv2_integrations_alphaimportHttpUrlIntegrationapigwv2.HttpApi(self,"HttpProxyApi",default_integration=HttpUrlIntegration("DefaultIntegration","https://example.com"))Cross Origin Resource Sharing (CORS)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 preflightOPTIONSrequests, even
if there isn't anOPTIONSroute configured. Note that, when this option is used, API Gateway will ignore CORS headers
returned from your backend integration. Learn more aboutConfiguring CORS for an HTTP
API.ThecorsPreflightoption lets you specify a CORS configuration for an API.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 APIsA Stage is a logical reference to a lifecycle state of your API (for example,dev,prod,beta, orv2). 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.UseHttpStageto create a Stage resource for HTTP APIs. The following code sets up a Stage, whose URL is available athttps://{api_id}.execute-api.{region}.amazonaws.com/beta.# api: apigwv2.HttpApiapigwv2.HttpStage(self,"Stage",http_api=api,stage_name="beta")If you omit thestageNamewill create a$defaultstage. A$defaultstage is one that is served from the base of
the API's URL -https://{api_id}.execute-api.{region}.amazonaws.com/.Note that,HttpApiwill always creates a$defaultstage, unless thecreateDefaultStageproperty is unset.Custom DomainCustom 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$defaultstage of the API.importaws_cdk.aws_certificatemanagerasacmfromaws_cdk.aws_apigatewayv2_integrations_alphaimportHttpLambdaIntegration# handler: lambda.Functioncert_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 stagedefault_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 viaaddEndpoint()and then configure DNS records to route traffic to the new endpoint. After that, you can remove the previous endpoint configuration.
Learn more atMigrating a custom domain nameTo associate a specificStageto a custom domain mapping -# api: apigwv2.HttpApi# dn: apigwv2.DomainNameapi.add_stage("beta",stage_name="beta",auto_deploy=True,# https://${dn.domainName}/bar goes to the beta stagedomain_mapping=apigwv2.DomainMappingOptions(domain_name=dn,mapping_key="bar"))The same domain name can be associated with stages across differentHttpApias so -fromaws_cdk.aws_apigatewayv2_integrations_alphaimportHttpLambdaIntegration# handler: lambda.Function# dn: apigwv2.DomainNameapi_demo=apigwv2.HttpApi(self,"DemoApi",default_integration=HttpLambdaIntegration("DefaultIntegration",handler),# https://${dn.domainName}/demo goes to apiDemo $default stagedefault_domain_mapping=apigwv2.DomainMappingOptions(domain_name=dn,mapping_key="demo"))ThemappingKeydetermines the base path of the URL with the custom domain. Each custom domain is only allowed
to have one API mapping with undefinedmappingKey. If more than one API mappings are specified,mappingKeywill 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.APIStageURLapi$defaulthttps://${domainName}/fooapibetahttps://${domainName}/barapiDemo$defaulthttps://${domainName}/demoYou can retrieve the full domain URL with mapping key using thedomainUrlproperty as so -# api_demo: apigwv2.HttpApidemo_domain_url=api_demo.default_stage.domain_urlMutual 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.importaws_cdk.aws_s3ass3importaws_cdk.aws_certificatemanagerasacm# bucket: s3.Bucketcert_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 foundhereManaging access to HTTP APIsAPI Gateway supports multiple mechanisms forcontrolling and managing access to your HTTP
APIthrough authorizers.These authorizers can be found in theAPIGatewayV2-Authorizersconstructs library.MetricsThe 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 theHttpApiconstruct.
The APIs with themetricprefix 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=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
themetricmethods from theStageconstruct.api=apigwv2.HttpApi(self,"my-api")stage=apigwv2.HttpStage(self,"Stage",http_api=api)client_error_metric=stage.metric_client_error()VPC LinkPrivate 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. TheVpcLinkconstruct enables this integration.
The following code creates aVpcLinkto a private VPC.importaws_cdk.aws_ec2asec2importaws_cdk.aws_elasticloadbalancingv2aselbfromaws_cdk.aws_apigatewayv2_integrations_alphaimportHttpAlbIntegrationvpc=ec2.Vpc(self,"VPC")alb=elb.ApplicationLoadBalancer(self,"AppLoadBalancer",vpc=vpc)vpc_link=apigwv2.VpcLink(self,"VpcLink",vpc=vpc)# Creating an HTTP ALB Integration:alb_integration=HttpAlbIntegration("ALBIntegration",alb.listeners[0])Any existingVpcLinkresource can be imported into the CDK app via theVpcLink.fromVpcLinkAttributes().importaws_cdk.aws_ec2asec2# vpc: ec2.Vpcawesome_link=apigwv2.VpcLink.from_vpc_link_attributes(self,"awesome-vpc-link",vpc_link_id="us-east-1_oiuR12Abd",vpc=vpc)Private IntegrationPrivate 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 theaws-apigatewayv2-integrationsconstructs library.WebSocket APIA 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 moreWebSocket 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$defaultroute.)Integrations define how the WebSocket API behaves when a client reaches a specific Route. Learn more atConfiguring integrations.Integrations are available in theaws-apigatewayv2-integrationsmodule and more information is available in that module.To add the default WebSocket routes supported by API Gateway ($connect,$disconnectand$default), configure them as part of api props:fromaws_cdk.aws_apigatewayv2_integrations_alphaimportWebSocketLambdaIntegration# connect_handler: lambda.Function# disconnect_handler: lambda.Function# default_handler: lambda.Functionweb_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:# web_socket_stage: apigwv2.WebSocketStageweb_socket_uRL=web_socket_stage.url# wss://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}callback_uRL=web_socket_stage.callback_urlTo add any other route:fromaws_cdk.aws_apigatewayv2_integrations_alphaimportWebSocketLambdaIntegration# message_handler: lambda.Functionweb_socket_api=apigwv2.WebSocketApi(self,"mywsapi")web_socket_api.add_route("sendmessage",integration=WebSocketLambdaIntegration("SendMessageIntegration",message_handler))To add a route that can return a result:fromaws_cdk.aws_apigatewayv2_integrations_alphaimportWebSocketLambdaIntegration# message_handler: lambda.Functionweb_socket_api=apigwv2.WebSocketApi(self,"mywsapi")web_socket_api.add_route("sendmessage",integration=WebSocketLambdaIntegration("SendMessageIntegration",message_handler),return_response=True)To import an existing WebSocketApi:web_socket_api=apigwv2.WebSocketApi.from_web_socket_api_attributes(self,"mywsapi",web_socket_id="api-1234")Manage Connections PermissionGrant permission to use API Gateway Management API of a WebSocket API by calling thegrantManageConnectionsAPI.
You can use Management API to send a callback message to a connected client, get connection information, or disconnect the client. Learn more atUse @connections commands in your backend service.# fn: lambda.Functionweb_socket_api=apigwv2.WebSocketApi(self,"mywsapi")stage=apigwv2.WebSocketStage(self,"mystage",web_socket_api=web_socket_api,stage_name="dev")# per stage permissionstage.grant_management_api_access(fn)# for all the stages permissionweb_socket_api.grant_manage_connections(fn)Managing access to WebSocket APIsAPI Gateway supports multiple mechanisms forcontrolling and managing access to a WebSocket APIthrough authorizers.These authorizers can be found in theAPIGatewayV2-Authorizersconstructs library.API KeysWebsocket 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 withusage 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=apigwv2.WebSocketApi(self,"mywsapi",api_key_selection_expression=apigwv2.WebSocketApiKeySelectionExpression.HEADER_X_API_KEY)