Skip to main content

The CDK Construct Library for AWS::APIGatewayv2

Project description

AWS::APIGatewayv2 Construct Library

---
Features Stability
CFN Resources Stable
Higher level constructs for HTTP APIs Experimental
Higher level constructs for Websocket APIs Experimental

CFN Resources: All classes with the Cfn prefix in this module (CFN Resources) 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 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.


Table of Contents

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.

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/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. 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, 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.

# Example automatically generated. See https://github.com/aws/jsii/issues/826
from aws_cdk.aws_apigatewayv2_integrations import HttpProxyIntegration, LambdaProxyIntegration

# books_default_fn is of type Function


get_books_integration = HttpProxyIntegration(
    url="https://get-books-proxy.myproxy.internal"
)
books_default_integration = LambdaProxyIntegration(
    handler=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.

# Example automatically generated. See https://github.com/aws/jsii/issues/826
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.

# Example automatically generated. See https://github.com/aws/jsii/issues/826
from aws_cdk.aws_apigatewayv2_integrations import HttpProxyIntegration


apigwv2.HttpApi(self, "HttpProxyApi",
    default_integration=HttpProxyIntegration(
        url="http://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 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 corsPreflight option lets you specify a CORS configuration for an API.

# Example automatically generated. See https://github.com/aws/jsii/issues/826
apigwv2.HttpApi(self, "HttpProxyApi",
    cors_preflight=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.

# Example automatically generated. See https://github.com/aws/jsii/issues/826
# api is of type 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.

# Example automatically generated. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_certificatemanager as acm
from aws_cdk.aws_apigatewayv2_integrations import LambdaProxyIntegration

# handler is of type 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=LambdaProxyIntegration(handler=handler),
    # https://${dn.domainName}/foo goes to prodApi $default stage
    default_domain_mapping=DomainMappingOptions(
        domain_name=dn,
        mapping_key="foo"
    )
)

To associate a specific Stage to a custom domain mapping -

# Example automatically generated. See https://github.com/aws/jsii/issues/826
# api is of type HttpApi
# dn is of type DomainName


api.add_stage("beta",
    stage_name="beta",
    auto_deploy=True,
    # https://${dn.domainName}/bar goes to the beta stage
    domain_mapping=DomainMappingOptions(
        domain_name=dn,
        mapping_key="bar"
    )
)

The same domain name can be associated with stages across different HttpApi as so -

# Example automatically generated. See https://github.com/aws/jsii/issues/826
from aws_cdk.aws_apigatewayv2_integrations import LambdaProxyIntegration

# handler is of type Function
# dn is of type DomainName


api_demo = apigwv2.HttpApi(self, "DemoApi",
    default_integration=LambdaProxyIntegration(handler=handler),
    # https://${dn.domainName}/demo goes to apiDemo $default stage
    default_domain_mapping=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 -

# Example automatically generated. See https://github.com/aws/jsii/issues/826
# api_demo is of type 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.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_s3 as s3

cert_arn = "arn:aws:acm:us-east-1:111111111111:certificate"
domain_name = "example.com"
bucket = s3.Bucket.from_bucket_name(stack, "TrustStoreBucket", ...)

DomainName(stack, "DomainName",
    domain_name=domain_name,
    certificate=Certificate.from_certificate_arn(stack, "cert", cert_arn),
    mtls={
        "bucket": bucket,
        "key": "someca.pem",
        "version": "version"
    }
)

Instructions for configuring your trust store can be found here

Managing access

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.

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.

# Example automatically generated. See https://github.com/aws/jsii/issues/826
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.

# Example automatically generated. See https://github.com/aws/jsii/issues/826
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.

# Example automatically generated. See https://github.com/aws/jsii/issues/826
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().

# Example automatically generated. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_ec2 as ec2

# vpc is of type 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 APIGatewayV2-Integrations 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

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:

# Example automatically generated. See https://github.com/aws/jsii/issues/826
from aws_cdk.aws_apigatewayv2_integrations import LambdaWebSocketIntegration

# connect_handler is of type Function
# disconnect_handler is of type Function
# default_handler is of type Function


web_socket_api = apigwv2.WebSocketApi(self, "mywsapi",
    connect_route_options=WebSocketRouteOptions(integration=LambdaWebSocketIntegration(handler=connect_handler)),
    disconnect_route_options=WebSocketRouteOptions(integration=LambdaWebSocketIntegration(handler=disconnect_handler)),
    default_route_options=WebSocketRouteOptions(integration=LambdaWebSocketIntegration(handler=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:

# Example automatically generated. See https://github.com/aws/jsii/issues/826
# web_socket_stage is of type 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:

# Example automatically generated. See https://github.com/aws/jsii/issues/826
from aws_cdk.aws_apigatewayv2_integrations import LambdaWebSocketIntegration

# message_handler is of type Function

web_socket_api = apigwv2.WebSocketApi(self, "mywsapi")
web_socket_api.add_route("sendmessage",
    integration=LambdaWebSocketIntegration(
        handler=message_handler
    )
)

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aws-cdk.aws-apigatewayv2-1.132.0.tar.gz (234.1 kB view hashes)

Uploaded Source

Built Distribution

aws_cdk.aws_apigatewayv2-1.132.0-py3-none-any.whl (233.6 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page