Skip to content
v2.273.0

AWS APIGatewayv2 Construct Library ​

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

ts
import { HttpUrlIntegration, HttpLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

const getBooksIntegration = new HttpUrlIntegration('GetBooksIntegration', 'https://get-books-proxy.example.com');

declare const bookStoreDefaultFn: lambda.Function;
const bookStoreDefaultIntegration = new HttpLambdaIntegration('BooksIntegration', bookStoreDefaultFn);

const httpApi = new apigwv2.HttpApi(this, 'HttpApi');

httpApi.addRoutes({
  path: '/books',
  methods: [ apigwv2.HttpMethod.GET ],
  integration: getBooksIntegration,
});
httpApi.addRoutes({
  path: '/books',
  methods: [ apigwv2.HttpMethod.ANY ],
  integration: bookStoreDefaultIntegration,
});
python
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration, HttpLambdaIntegration

# book_store_default_fn: lambda.Function


get_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
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpLambdaIntegration;

Function bookStoreDefaultFn;


HttpUrlIntegration getBooksIntegration = new HttpUrlIntegration("GetBooksIntegration", "https://get-books-proxy.example.com");
HttpLambdaIntegration bookStoreDefaultIntegration = new HttpLambdaIntegration("BooksIntegration", bookStoreDefaultFn);

HttpApi httpApi = new HttpApi(this, "HttpApi");

httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/books")
        .methods(List.of(HttpMethod.GET))
        .integration(getBooksIntegration)
        .build());
httpApi.addRoutes(AddRoutesOptions.builder()
        .path("/books")
        .methods(List.of(HttpMethod.ANY))
        .integration(bookStoreDefaultIntegration)
        .build());
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;

Function bookStoreDefaultFn;


var getBooksIntegration = new HttpUrlIntegration("GetBooksIntegration", "https://get-books-proxy.example.com");
var bookStoreDefaultIntegration = new HttpLambdaIntegration("BooksIntegration", bookStoreDefaultFn);

var httpApi = new HttpApi(this, "HttpApi");

httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/books",
    Methods = new [] { HttpMethod.GET },
    Integration = getBooksIntegration
});
httpApi.AddRoutes(new AddRoutesOptions {
    Path = "/books",
    Methods = new [] { HttpMethod.ANY },
    Integration = bookStoreDefaultIntegration
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var bookStoreDefaultFn Function


getBooksIntegration := awscdk.NewHttpUrlIntegration(jsii.String("GetBooksIntegration"), jsii.String("https://get-books-proxy.example.com"))
bookStoreDefaultIntegration := awscdk.NewHttpLambdaIntegration(jsii.String("BooksIntegration"), bookStoreDefaultFn)

httpApi := apigwv2.NewHttpApi(this, jsii.String("HttpApi"))

httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/books"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_GET,
	},
	Integration: getBooksIntegration,
})
httpApi.AddRoutes(&AddRoutesOptions{
	Path: jsii.String("/books"),
	Methods: []HttpMethod{
		apigwv2.HttpMethod_ANY,
	},
	Integration: bookStoreDefaultIntegration,
})

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.

ts
const httpApi = new apigwv2.HttpApi(this, 'HttpApi', {
  disableExecuteApiEndpoint: true,
});
python
http_api = apigwv2.HttpApi(self, "HttpApi",
    disable_execute_api_endpoint=True
)
java
HttpApi httpApi = HttpApi.Builder.create(this, "HttpApi")
        .disableExecuteApiEndpoint(true)
        .build();
csharp
var httpApi = new HttpApi(this, "HttpApi", new HttpApiProps {
    DisableExecuteApiEndpoint = true
});
go
httpApi := apigwv2.NewHttpApi(this, jsii.String("HttpApi"), &HttpApiProps{
	DisableExecuteApiEndpoint: jsii.Boolean(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.

ts
import { HttpUrlIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

new apigwv2.HttpApi(this, 'HttpProxyApi', {
  defaultIntegration: new HttpUrlIntegration('DefaultIntegration', 'https://example.com'),
});
python
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration


apigwv2.HttpApi(self, "HttpProxyApi",
    default_integration=HttpUrlIntegration("DefaultIntegration", "https://example.com")
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;


HttpApi.Builder.create(this, "HttpProxyApi")
        .defaultIntegration(new HttpUrlIntegration("DefaultIntegration", "https://example.com"))
        .build();
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;


new HttpApi(this, "HttpProxyApi", new HttpApiProps {
    DefaultIntegration = new HttpUrlIntegration("DefaultIntegration", "https://example.com")
});
go
import "github.com/aws/aws-cdk-go/awscdk"


apigwv2.NewHttpApi(this, jsii.String("HttpProxyApi"), &HttpApiProps{
	DefaultIntegration: awscdk.NewHttpUrlIntegration(jsii.String("DefaultIntegration"), jsii.String("https://example.com")),
})

The routeSelectionExpression option allows configuring the HTTP API to accept only ${request.method} ${request.path}. Setting it to true automatically applies this value.

ts
new apigwv2.HttpApi(this, 'HttpProxyApi', {
  routeSelectionExpression: true,
});
python
apigwv2.HttpApi(self, "HttpProxyApi",
    route_selection_expression=True
)
java
HttpApi.Builder.create(this, "HttpProxyApi")
        .routeSelectionExpression(true)
        .build();
csharp
new HttpApi(this, "HttpProxyApi", new HttpApiProps {
    RouteSelectionExpression = true
});
go
apigwv2.NewHttpApi(this, jsii.String("HttpProxyApi"), &HttpApiProps{
	RouteSelectionExpression: jsii.Boolean(true),
})

You can configure IP address type for the API endpoint using ipAddressType property. Valid values are IPV4 (default) and DUAL_STACK.

ts
new apigwv2.HttpApi(this, 'HttpApi', {
  ipAddressType: apigwv2.IpAddressType.DUAL_STACK,
});
python
apigwv2.HttpApi(self, "HttpApi",
    ip_address_type=apigwv2.IpAddressType.DUAL_STACK
)
java
HttpApi.Builder.create(this, "HttpApi")
        .ipAddressType(IpAddressType.DUAL_STACK)
        .build();
csharp
new HttpApi(this, "HttpApi", new HttpApiProps {
    IpAddressType = IpAddressType.DUAL_STACK
});
go
apigwv2.NewHttpApi(this, jsii.String("HttpApi"), &HttpApiProps{
	IpAddressType: apigwv2.IpAddressType_DUAL_STACK,
})

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.

ts
new apigwv2.HttpApi(this, 'HttpProxyApi', {
  corsPreflight: {
    allowHeaders: ['Authorization'],
    allowMethods: [
      apigwv2.CorsHttpMethod.GET,
      apigwv2.CorsHttpMethod.HEAD,
      apigwv2.CorsHttpMethod.OPTIONS,
      apigwv2.CorsHttpMethod.POST,
    ],
    allowOrigins: ['*'],
    maxAge: Duration.days(10),
  },
});
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)
    )
)
java
HttpApi.Builder.create(this, "HttpProxyApi")
        .corsPreflight(CorsPreflightOptions.builder()
                .allowHeaders(List.of("Authorization"))
                .allowMethods(List.of(CorsHttpMethod.GET, CorsHttpMethod.HEAD, CorsHttpMethod.OPTIONS, CorsHttpMethod.POST))
                .allowOrigins(List.of("*"))
                .maxAge(Duration.days(10))
                .build())
        .build();
csharp
new HttpApi(this, "HttpProxyApi", new HttpApiProps {
    CorsPreflight = new CorsPreflightOptions {
        AllowHeaders = new [] { "Authorization" },
        AllowMethods = new [] { CorsHttpMethod.GET, CorsHttpMethod.HEAD, CorsHttpMethod.OPTIONS, CorsHttpMethod.POST },
        AllowOrigins = new [] { "*" },
        MaxAge = Duration.Days(10)
    }
});
go
apigwv2.NewHttpApi(this, jsii.String("HttpProxyApi"), &HttpApiProps{
	CorsPreflight: &CorsPreflightOptions{
		AllowHeaders: []*string{
			jsii.String("Authorization"),
		},
		AllowMethods: []CorsHttpMethod{
			apigwv2.CorsHttpMethod_GET,
			apigwv2.CorsHttpMethod_HEAD,
			apigwv2.CorsHttpMethod_OPTIONS,
			apigwv2.CorsHttpMethod_POST,
		},
		AllowOrigins: []*string{
			jsii.String("*"),
		},
		MaxAge: awscdk.Duration_Days(jsii.Number(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.

ts
declare const api: apigwv2.HttpApi;

new apigwv2.HttpStage(this, 'Stage', {
  httpApi: api,
  stageName: 'beta',
  description: 'My Stage',
});
python
# api: apigwv2.HttpApi


apigwv2.HttpStage(self, "Stage",
    http_api=api,
    stage_name="beta",
    description="My Stage"
)
java
HttpApi api;


HttpStage.Builder.create(this, "Stage")
        .httpApi(api)
        .stageName("beta")
        .description("My Stage")
        .build();
csharp
HttpApi api;


new HttpStage(this, "Stage", new HttpStageProps {
    HttpApi = api,
    StageName = "beta",
    Description = "My Stage"
});
go
var api HttpApi


apigwv2.NewHttpStage(this, jsii.String("Stage"), &HttpStageProps{
	HttpApi: api,
	StageName: jsii.String("beta"),
	Description: jsii.String("My Stage"),
})

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.

ts
import * as acm from 'aws-cdk-lib/aws-certificatemanager';
import { HttpLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

const certArn = 'arn:aws:acm:us-east-1:111111111111:certificate';
const domainName = 'example.com';

const dn = new apigwv2.DomainName(this, 'DN', {
  domainName: domainName,
  certificate: acm.Certificate.fromCertificateArn(this, 'cert', certArn),
});

declare const handler: lambda.Function;
const api = new apigwv2.HttpApi(this, 'HttpProxyProdApi', {
  defaultIntegration: new HttpLambdaIntegration('DefaultIntegration', handler),
  // https://${dn.domainName}/foo goes to prodApi $default stage
  defaultDomainMapping: {
    domainName: dn,
    mappingKey: 'foo',
  },
});
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"
    )
)
java
import software.amazon.awscdk.services.certificatemanager.*;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpLambdaIntegration;

Function handler;


String certArn = "arn:aws:acm:us-east-1:111111111111:certificate";
String domainName = "example.com";

DomainName dn = DomainName.Builder.create(this, "DN")
        .domainName(domainName)
        .certificate(Certificate.fromCertificateArn(this, "cert", certArn))
        .build();
HttpApi api = HttpApi.Builder.create(this, "HttpProxyProdApi")
        .defaultIntegration(new HttpLambdaIntegration("DefaultIntegration", handler))
        // https://${dn.domainName}/foo goes to prodApi $default stage
        .defaultDomainMapping(DomainMappingOptions.builder()
                .domainName(dn)
                .mappingKey("foo")
                .build())
        .build();
csharp
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AwsApigatewayv2Integrations;

Function handler;


var certArn = "arn:aws:acm:us-east-1:111111111111:certificate";
var domainName = "example.com";

var dn = new DomainName(this, "DN", new DomainNameProps {
    DomainName = domainName,
    Certificate = Certificate.FromCertificateArn(this, "cert", certArn)
});
var api = new HttpApi(this, "HttpProxyProdApi", new HttpApiProps {
    DefaultIntegration = new HttpLambdaIntegration("DefaultIntegration", handler),
    // https://${dn.domainName}/foo goes to prodApi $default stage
    DefaultDomainMapping = new DomainMappingOptions {
        DomainName = dn,
        MappingKey = "foo"
    }
});
go
import acm "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var handler Function


certArn := "arn:aws:acm:us-east-1:111111111111:certificate"
domainName := "example.com"

dn := apigwv2.NewDomainName(this, jsii.String("DN"), &DomainNameProps{
	DomainName: domainName,
	Certificate: acm.Certificate_FromCertificateArn(this, jsii.String("cert"), certArn),
})
api := apigwv2.NewHttpApi(this, jsii.String("HttpProxyProdApi"), &HttpApiProps{
	DefaultIntegration: awscdk.NewHttpLambdaIntegration(jsii.String("DefaultIntegration"), handler),
	// https://${dn.domainName}/foo goes to prodApi $default stage
	DefaultDomainMapping: &DomainMappingOptions{
		DomainName: dn,
		MappingKey: jsii.String("foo"),
	},
})

The IP address type for the domain name can be configured by using the ipAddressType property. Valid values are IPV4 (default) and DUAL_STACK.

ts
import * as acm from 'aws-cdk-lib/aws-certificatemanager';

declare const certificate: acm.ICertificate;
declare const domainName: string;

const dn = new apigwv2.DomainName(this, 'DN', {
  domainName: domainName,
  certificate: certificate,
  ipAddressType: apigwv2.IpAddressType.DUAL_STACK,
});
python
import aws_cdk.aws_certificatemanager as acm

# certificate: acm.ICertificate
# domain_name: str


dn = apigwv2.DomainName(self, "DN",
    domain_name=domain_name,
    certificate=certificate,
    ip_address_type=apigwv2.IpAddressType.DUAL_STACK
)
java
import software.amazon.awscdk.services.certificatemanager.*;

ICertificate certificate;
String domainName;


DomainName dn = DomainName.Builder.create(this, "DN")
        .domainName(domainName)
        .certificate(certificate)
        .ipAddressType(IpAddressType.DUAL_STACK)
        .build();
csharp
using Amazon.CDK.AWS.CertificateManager;

ICertificate certificate;
string domainName;


var dn = new DomainName(this, "DN", new DomainNameProps {
    DomainName = domainName,
    Certificate = certificate,
    IpAddressType = IpAddressType.DUAL_STACK
});
go
import acm "github.com/aws/aws-cdk-go/awscdk"

var certificate ICertificate
var domainName string


dn := apigwv2.NewDomainName(this, jsii.String("DN"), &DomainNameProps{
	DomainName: domainName,
	Certificate: certificate,
	IpAddressType: apigwv2.IpAddressType_DUAL_STACK,
})

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

To associate a specific Stage to a custom domain mapping -

ts
declare const api: apigwv2.HttpApi;
declare const dn: apigwv2.DomainName;

api.addStage('beta', {
  stageName: 'beta',
  autoDeploy: true,
  // https://${dn.domainName}/bar goes to the beta stage
  domainMapping: {
    domainName: dn,
    mappingKey: 'bar',
  },
});
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"
    )
)
java
HttpApi api;
DomainName dn;


api.addStage("beta", HttpStageOptions.builder()
        .stageName("beta")
        .autoDeploy(true)
        // https://${dn.domainName}/bar goes to the beta stage
        .domainMapping(DomainMappingOptions.builder()
                .domainName(dn)
                .mappingKey("bar")
                .build())
        .build());
csharp
HttpApi api;
DomainName dn;


api.AddStage("beta", new HttpStageOptions {
    StageName = "beta",
    AutoDeploy = true,
    // https://${dn.domainName}/bar goes to the beta stage
    DomainMapping = new DomainMappingOptions {
        DomainName = dn,
        MappingKey = "bar"
    }
});
go
var api HttpApi
var dn DomainName


api.AddStage(jsii.String("beta"), &HttpStageOptions{
	StageName: jsii.String("beta"),
	AutoDeploy: jsii.Boolean(true),
	// https://${dn.domainName}/bar goes to the beta stage
	DomainMapping: &DomainMappingOptions{
		DomainName: dn,
		MappingKey: jsii.String("bar"),
	},
})

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

ts
import { HttpLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

declare const handler: lambda.Function;
declare const dn: apigwv2.DomainName;

const apiDemo = new apigwv2.HttpApi(this, 'DemoApi', {
  defaultIntegration: new HttpLambdaIntegration('DefaultIntegration', handler),
  // https://${dn.domainName}/demo goes to apiDemo $default stage
  defaultDomainMapping: {
    domainName: dn,
    mappingKey: 'demo',
  },
});
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"
    )
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpLambdaIntegration;

Function handler;
DomainName dn;


HttpApi apiDemo = HttpApi.Builder.create(this, "DemoApi")
        .defaultIntegration(new HttpLambdaIntegration("DefaultIntegration", handler))
        // https://${dn.domainName}/demo goes to apiDemo $default stage
        .defaultDomainMapping(DomainMappingOptions.builder()
                .domainName(dn)
                .mappingKey("demo")
                .build())
        .build();
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;

Function handler;
DomainName dn;


var apiDemo = new HttpApi(this, "DemoApi", new HttpApiProps {
    DefaultIntegration = new HttpLambdaIntegration("DefaultIntegration", handler),
    // https://${dn.domainName}/demo goes to apiDemo $default stage
    DefaultDomainMapping = new DomainMappingOptions {
        DomainName = dn,
        MappingKey = "demo"
    }
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var handler Function
var dn DomainName


apiDemo := apigwv2.NewHttpApi(this, jsii.String("DemoApi"), &HttpApiProps{
	DefaultIntegration: awscdk.NewHttpLambdaIntegration(jsii.String("DefaultIntegration"), handler),
	// https://${dn.domainName}/demo goes to apiDemo $default stage
	DefaultDomainMapping: &DomainMappingOptions{
		DomainName: dn,
		MappingKey: jsii.String("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.

APIStageURL
api$defaulthttps://${domainName}/foo
apibetahttps://${domainName}/bar
apiDemo$defaulthttps://${domainName}/demo

You can retrieve the full domain URL with mapping key using the domainUrl property as so -

ts
declare const apiDemo: apigwv2.HttpApi;
const demoDomainUrl = apiDemo.defaultStage?.domainUrl; // returns "https://example.com/demo"
python
# api_demo: apigwv2.HttpApi

demo_domain_url = api_demo.default_stage.domain_url
java
HttpApi apiDemo;

String demoDomainUrl = apiDemo.getDefaultStage().getDomainUrl();
csharp
HttpApi apiDemo;

var demoDomainUrl = apiDemo.DefaultStage.DomainUrl;
go
var apiDemo HttpApi

demoDomainUrl := apiDemo.DefaultStage.DomainUrl

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.

ts
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as acm from 'aws-cdk-lib/aws-certificatemanager';

const certArn = 'arn:aws:acm:us-east-1:111111111111:certificate';
const domainName = 'example.com';
declare const bucket: s3.Bucket;

new apigwv2.DomainName(this, 'DomainName', {
  domainName,
  certificate: acm.Certificate.fromCertificateArn(this, 'cert', certArn),
  mtls: {
    bucket,
    key: 'someca.pem',
    version: 'version',
  },
});
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"
    )
)
java
import software.amazon.awscdk.services.s3.*;
import software.amazon.awscdk.services.certificatemanager.*;
Bucket bucket;


String certArn = "arn:aws:acm:us-east-1:111111111111:certificate";
String domainName = "example.com";

DomainName.Builder.create(this, "DomainName")
        .domainName(domainName)
        .certificate(Certificate.fromCertificateArn(this, "cert", certArn))
        .mtls(MTLSConfig.builder()
                .bucket(bucket)
                .key("someca.pem")
                .version("version")
                .build())
        .build();
csharp
using Amazon.CDK.AWS.S3;
using Amazon.CDK.AWS.CertificateManager;
Bucket bucket;


var certArn = "arn:aws:acm:us-east-1:111111111111:certificate";
var domainName = "example.com";

new DomainName(this, "DomainName", new DomainNameProps {
    DomainName = domainName,
    Certificate = Certificate.FromCertificateArn(this, "cert", certArn),
    Mtls = new MTLSConfig {
        Bucket = bucket,
        Key = "someca.pem",
        Version = "version"
    }
});
go
import s3 "github.com/aws/aws-cdk-go/awscdk"
import acm "github.com/aws/aws-cdk-go/awscdk"
var bucket Bucket


certArn := "arn:aws:acm:us-east-1:111111111111:certificate"
domainName := "example.com"

apigwv2.NewDomainName(this, jsii.String("DomainName"), &DomainNameProps{
	DomainName: jsii.String(DomainName),
	Certificate: acm.Certificate_FromCertificateArn(this, jsii.String("cert"), certArn),
	Mtls: &MTLSConfig{
		Bucket: *Bucket,
		Key: jsii.String("someca.pem"),
		Version: jsii.String("version"),
	},
})

Instructions for configuring your trust store can be found here

Managing access to HTTP APIs ​

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.

ts
const api = new apigwv2.HttpApi(this, 'my-api');
const clientErrorMetric = api.metricClientError();
python
api = apigwv2.HttpApi(self, "my-api")
client_error_metric = api.metric_client_error()
java
HttpApi api = new HttpApi(this, "my-api");
Metric clientErrorMetric = api.metricClientError();
csharp
var api = new HttpApi(this, "my-api");
var clientErrorMetric = api.MetricClientError();
go
api := apigwv2.NewHttpApi(this, jsii.String("my-api"))
clientErrorMetric := api.metricClientError()

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.

ts
const api = new apigwv2.HttpApi(this, 'my-api');
const stage = new apigwv2.HttpStage(this, 'Stage', {
  httpApi: api,
});
const clientErrorMetric = stage.metricClientError();
python
api = apigwv2.HttpApi(self, "my-api")
stage = apigwv2.HttpStage(self, "Stage",
    http_api=api
)
client_error_metric = stage.metric_client_error()
java
HttpApi api = new HttpApi(this, "my-api");
HttpStage stage = HttpStage.Builder.create(this, "Stage")
        .httpApi(api)
        .build();
Metric clientErrorMetric = stage.metricClientError();
csharp
var api = new HttpApi(this, "my-api");
var stage = new HttpStage(this, "Stage", new HttpStageProps {
    HttpApi = api
});
var clientErrorMetric = stage.MetricClientError();
go
api := apigwv2.NewHttpApi(this, jsii.String("my-api"))
stage := apigwv2.NewHttpStage(this, jsii.String("Stage"), &HttpStageProps{
	HttpApi: api,
})
clientErrorMetric := stage.metricClientError()

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.

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as elb from 'aws-cdk-lib/aws-elasticloadbalancingv2';
import { HttpAlbIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

const vpc = new ec2.Vpc(this, 'VPC');
const alb = new elb.ApplicationLoadBalancer(this, 'AppLoadBalancer', { vpc });

const vpcLink = new apigwv2.VpcLink(this, 'VpcLink', { vpc });

// Creating an HTTP ALB Integration:
const albIntegration = new HttpAlbIntegration('ALBIntegration', alb.listeners[0], {});
python
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_elasticloadbalancingv2 as elb
from aws_cdk.aws_apigatewayv2_integrations import HttpAlbIntegration


vpc = 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])
java
import software.amazon.awscdk.services.ec2.*;
import software.amazon.awscdk.services.elasticloadbalancingv2.*;
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpAlbIntegration;


Vpc vpc = new Vpc(this, "VPC");
ApplicationLoadBalancer alb = ApplicationLoadBalancer.Builder.create(this, "AppLoadBalancer").vpc(vpc).build();

VpcLink vpcLink = VpcLink.Builder.create(this, "VpcLink").vpc(vpc).build();

// Creating an HTTP ALB Integration:
HttpAlbIntegration albIntegration = HttpAlbIntegration.Builder.create("ALBIntegration", alb.getListeners()[0]).build();
csharp
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;
using Amazon.CDK.AwsApigatewayv2Integrations;


var vpc = new Vpc(this, "VPC");
var alb = new ApplicationLoadBalancer(this, "AppLoadBalancer", new ApplicationLoadBalancerProps { Vpc = vpc });

var vpcLink = new VpcLink(this, "VpcLink", new VpcLinkProps { Vpc = vpc });

// Creating an HTTP ALB Integration:
var albIntegration = new HttpAlbIntegration("ALBIntegration", alb.Listeners[0], new HttpAlbIntegrationProps { });
go
import ec2 "github.com/aws/aws-cdk-go/awscdk"
import elb "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("VPC"))
alb := elb.NewApplicationLoadBalancer(this, jsii.String("AppLoadBalancer"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
})

vpcLink := apigwv2.NewVpcLink(this, jsii.String("VpcLink"), &VpcLinkProps{
	Vpc: Vpc,
})

// Creating an HTTP ALB Integration:
albIntegration := awscdk.NewHttpAlbIntegration(jsii.String("ALBIntegration"), alb.Listeners[jsii.Number(0)], &HttpAlbIntegrationProps{
})

Any existing VpcLink resource can be imported into the CDK app via the VpcLink.fromVpcLinkAttributes().

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';

declare const vpc: ec2.Vpc;
const awesomeLink = apigwv2.VpcLink.fromVpcLinkAttributes(this, 'awesome-vpc-link', {
  vpcLinkId: 'us-east-1_oiuR12Abd',
  vpc,
});
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
)
java
import software.amazon.awscdk.services.ec2.*;

Vpc vpc;

IVpcLink awesomeLink = VpcLink.fromVpcLinkAttributes(this, "awesome-vpc-link", VpcLinkAttributes.builder()
        .vpcLinkId("us-east-1_oiuR12Abd")
        .vpc(vpc)
        .build());
csharp
using Amazon.CDK.AWS.EC2;

Vpc vpc;

var awesomeLink = VpcLink.FromVpcLinkAttributes(this, "awesome-vpc-link", new VpcLinkAttributes {
    VpcLinkId = "us-east-1_oiuR12Abd",
    Vpc = vpc
});
go
import ec2 "github.com/aws/aws-cdk-go/awscdk"

var vpc Vpc

awesomeLink := apigwv2.VpcLink_FromVpcLinkAttributes(this, jsii.String("awesome-vpc-link"), &VpcLinkAttributes{
	VpcLinkId: jsii.String("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 constructs library.

Generating ARN for Execute API ​

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.

ts
const api = new apigwv2.HttpApi(this, 'my-api');
const arn = api.arnForExecuteApi('GET', '/myApiPath', 'dev');
python
api = apigwv2.HttpApi(self, "my-api")
arn = api.arn_for_execute_api("GET", "/myApiPath", "dev")
java
HttpApi api = new HttpApi(this, "my-api");
String arn = api.arnForExecuteApi("GET", "/myApiPath", "dev");
csharp
var api = new HttpApi(this, "my-api");
var arn = api.ArnForExecuteApi("GET", "/myApiPath", "dev");
go
api := apigwv2.NewHttpApi(this, jsii.String("my-api"))
arn := api.arnForExecuteApi(jsii.String("GET"), jsii.String("/myApiPath"), jsii.String("dev"))
  • Ensure that the path parameter, if provided, starts with '/'.
  • The 'ANY' method can be used for matching any HTTP methods not explicitly defined.
  • The function gracefully handles undefined parameters by using wildcards, making it flexible for various API configurations.

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:

ts
import { WebSocketLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

declare const connectHandler: lambda.Function;
declare const disconnectHandler: lambda.Function;
declare const defaultHandler: lambda.Function;

const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi', {
  connectRouteOptions: { integration: new WebSocketLambdaIntegration('ConnectIntegration', connectHandler) },
  disconnectRouteOptions: { integration: new WebSocketLambdaIntegration('DisconnectIntegration',disconnectHandler) },
  defaultRouteOptions: { integration: new WebSocketLambdaIntegration('DefaultIntegration', defaultHandler) },
});

new apigwv2.WebSocketStage(this, 'mystage', {
  webSocketApi,
  stageName: 'dev',
  description: 'My Stage',
  autoDeploy: true,
});
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",
    description="My Stage",
    auto_deploy=True
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.WebSocketLambdaIntegration;

Function connectHandler;
Function disconnectHandler;
Function defaultHandler;


WebSocketApi webSocketApi = WebSocketApi.Builder.create(this, "mywsapi")
        .connectRouteOptions(WebSocketRouteOptions.builder().integration(new WebSocketLambdaIntegration("ConnectIntegration", connectHandler)).build())
        .disconnectRouteOptions(WebSocketRouteOptions.builder().integration(new WebSocketLambdaIntegration("DisconnectIntegration", disconnectHandler)).build())
        .defaultRouteOptions(WebSocketRouteOptions.builder().integration(new WebSocketLambdaIntegration("DefaultIntegration", defaultHandler)).build())
        .build();

WebSocketStage.Builder.create(this, "mystage")
        .webSocketApi(webSocketApi)
        .stageName("dev")
        .description("My Stage")
        .autoDeploy(true)
        .build();
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;

Function connectHandler;
Function disconnectHandler;
Function defaultHandler;


var webSocketApi = new WebSocketApi(this, "mywsapi", new WebSocketApiProps {
    ConnectRouteOptions = new WebSocketRouteOptions { Integration = new WebSocketLambdaIntegration("ConnectIntegration", connectHandler) },
    DisconnectRouteOptions = new WebSocketRouteOptions { Integration = new WebSocketLambdaIntegration("DisconnectIntegration", disconnectHandler) },
    DefaultRouteOptions = new WebSocketRouteOptions { Integration = new WebSocketLambdaIntegration("DefaultIntegration", defaultHandler) }
});

new WebSocketStage(this, "mystage", new WebSocketStageProps {
    WebSocketApi = webSocketApi,
    StageName = "dev",
    Description = "My Stage",
    AutoDeploy = true
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var connectHandler Function
var disconnectHandler Function
var defaultHandler Function


webSocketApi := apigwv2.NewWebSocketApi(this, jsii.String("mywsapi"), &WebSocketApiProps{
	ConnectRouteOptions: &WebSocketRouteOptions{
		Integration: awscdk.NewWebSocketLambdaIntegration(jsii.String("ConnectIntegration"), connectHandler),
	},
	DisconnectRouteOptions: &WebSocketRouteOptions{
		Integration: awscdk.NewWebSocketLambdaIntegration(jsii.String("DisconnectIntegration"), disconnectHandler),
	},
	DefaultRouteOptions: &WebSocketRouteOptions{
		Integration: awscdk.NewWebSocketLambdaIntegration(jsii.String("DefaultIntegration"), defaultHandler),
	},
})

apigwv2.NewWebSocketStage(this, jsii.String("mystage"), &WebSocketStageProps{
	WebSocketApi: WebSocketApi,
	StageName: jsii.String("dev"),
	Description: jsii.String("My Stage"),
	AutoDeploy: jsii.Boolean(true),
})

To retrieve a websocket URL and a callback URL:

ts
declare const webSocketStage: apigwv2.WebSocketStage;

const webSocketURL = webSocketStage.url;
// wss://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}
const callbackURL = webSocketStage.callbackUrl;
// https://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}
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
java
WebSocketStage webSocketStage;


String webSocketURL = webSocketStage.getUrl();
// wss://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}
String callbackURL = webSocketStage.getCallbackUrl();
csharp
WebSocketStage webSocketStage;


var webSocketURL = webSocketStage.Url;
// wss://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}
var callbackURL = webSocketStage.CallbackUrl;
go
var webSocketStage WebSocketStage


webSocketURL := webSocketStage.url
// wss://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}
callbackURL := webSocketStage.callbackUrl

To add any other route:

ts
import { WebSocketLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

declare const messageHandler: lambda.Function;
const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi');
webSocketApi.addRoute('sendmessage', {
  integration: new WebSocketLambdaIntegration('SendMessageIntegration', messageHandler),
});
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)
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.WebSocketLambdaIntegration;

Function messageHandler;

WebSocketApi webSocketApi = new WebSocketApi(this, "mywsapi");
webSocketApi.addRoute("sendmessage", WebSocketRouteOptions.builder()
        .integration(new WebSocketLambdaIntegration("SendMessageIntegration", messageHandler))
        .build());
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;

Function messageHandler;

var webSocketApi = new WebSocketApi(this, "mywsapi");
webSocketApi.AddRoute("sendmessage", new WebSocketRouteOptions {
    Integration = new WebSocketLambdaIntegration("SendMessageIntegration", messageHandler)
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var messageHandler Function

webSocketApi := apigwv2.NewWebSocketApi(this, jsii.String("mywsapi"))
webSocketApi.AddRoute(jsii.String("sendmessage"), &WebSocketRouteOptions{
	Integration: awscdk.NewWebSocketLambdaIntegration(jsii.String("SendMessageIntegration"), messageHandler),
})

To add a route that can return a result:

ts
import { WebSocketLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';

declare const messageHandler: lambda.Function;
const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi');
webSocketApi.addRoute('sendmessage', {
  integration: new WebSocketLambdaIntegration('SendMessageIntegration', messageHandler),
  returnResponse: true,
});
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),
    return_response=True
)
java
import software.amazon.awscdk.aws_apigatewayv2_integrations.WebSocketLambdaIntegration;

Function messageHandler;

WebSocketApi webSocketApi = new WebSocketApi(this, "mywsapi");
webSocketApi.addRoute("sendmessage", WebSocketRouteOptions.builder()
        .integration(new WebSocketLambdaIntegration("SendMessageIntegration", messageHandler))
        .returnResponse(true)
        .build());
csharp
using Amazon.CDK.AwsApigatewayv2Integrations;

Function messageHandler;

var webSocketApi = new WebSocketApi(this, "mywsapi");
webSocketApi.AddRoute("sendmessage", new WebSocketRouteOptions {
    Integration = new WebSocketLambdaIntegration("SendMessageIntegration", messageHandler),
    ReturnResponse = true
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var messageHandler Function

webSocketApi := apigwv2.NewWebSocketApi(this, jsii.String("mywsapi"))
webSocketApi.AddRoute(jsii.String("sendmessage"), &WebSocketRouteOptions{
	Integration: awscdk.NewWebSocketLambdaIntegration(jsii.String("SendMessageIntegration"), messageHandler),
	ReturnResponse: jsii.Boolean(true),
})

To import an existing WebSocketApi:

ts
const webSocketApi = apigwv2.WebSocketApi.fromWebSocketApiAttributes(this, 'mywsapi', { webSocketId: 'api-1234' });
python
web_socket_api = apigwv2.WebSocketApi.from_web_socket_api_attributes(self, "mywsapi", web_socket_id="api-1234")
java
IWebSocketApi webSocketApi = WebSocketApi.fromWebSocketApiAttributes(this, "mywsapi", WebSocketApiAttributes.builder().webSocketId("api-1234").build());
csharp
var webSocketApi = WebSocketApi.FromWebSocketApiAttributes(this, "mywsapi", new WebSocketApiAttributes { WebSocketId = "api-1234" });
go
webSocketApi := apigwv2.WebSocketApi_FromWebSocketApiAttributes(this, jsii.String("mywsapi"), &WebSocketApiAttributes{
	WebSocketId: jsii.String("api-1234"),
})

To generate an ARN for Execute API:

ts
const api = new apigwv2.WebSocketApi(this, 'mywsapi');
const arn = api.arnForExecuteApiV2('$connect', 'dev');
python
api = apigwv2.WebSocketApi(self, "mywsapi")
arn = api.arn_for_execute_api_v2("$connect", "dev")
java
WebSocketApi api = new WebSocketApi(this, "mywsapi");
String arn = api.arnForExecuteApiV2("$connect", "dev");
csharp
var api = new WebSocketApi(this, "mywsapi");
var arn = api.ArnForExecuteApiV2("$connect", "dev");
go
api := apigwv2.NewWebSocketApi(this, jsii.String("mywsapi"))
arn := api.ArnForExecuteApiV2(jsii.String("$connect"), jsii.String("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 disableSchemaValidation to true.

ts
new apigwv2.WebSocketApi(this, 'api', {
  disableSchemaValidation: true,
});
python
apigwv2.WebSocketApi(self, "api",
    disable_schema_validation=True
)
java
WebSocketApi.Builder.create(this, "api")
        .disableSchemaValidation(true)
        .build();
csharp
new WebSocketApi(this, "api", new WebSocketApiProps {
    DisableSchemaValidation = true
});
go
apigwv2.NewWebSocketApi(this, jsii.String("api"), &WebSocketApiProps{
	DisableSchemaValidation: jsii.Boolean(true),
})

You can configure IP address type for the API endpoint using ipAddressType property. Valid values are IPV4 (default) and DUAL_STACK.

ts
new apigwv2.WebSocketApi(this, 'WebSocketApi', {
  ipAddressType: apigwv2.IpAddressType.DUAL_STACK,
});
python
apigwv2.WebSocketApi(self, "WebSocketApi",
    ip_address_type=apigwv2.IpAddressType.DUAL_STACK
)
java
WebSocketApi.Builder.create(this, "WebSocketApi")
        .ipAddressType(IpAddressType.DUAL_STACK)
        .build();
csharp
new WebSocketApi(this, "WebSocketApi", new WebSocketApiProps {
    IpAddressType = IpAddressType.DUAL_STACK
});
go
apigwv2.NewWebSocketApi(this, jsii.String("WebSocketApi"), &WebSocketApiProps{
	IpAddressType: apigwv2.IpAddressType_DUAL_STACK,
})

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.

ts
declare const fn: lambda.Function;

const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi');
const stage = new apigwv2.WebSocketStage(this, 'mystage', {
  webSocketApi,
  stageName: 'dev',
});
// per stage permission
stage.grantManagementApiAccess(fn);
// for all the stages permission
webSocketApi.grantManageConnections(fn);
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)
java
Function fn;


WebSocketApi webSocketApi = new WebSocketApi(this, "mywsapi");
WebSocketStage stage = WebSocketStage.Builder.create(this, "mystage")
        .webSocketApi(webSocketApi)
        .stageName("dev")
        .build();
// per stage permission
stage.grantManagementApiAccess(fn);
// for all the stages permission
webSocketApi.grantManageConnections(fn);
csharp
Function fn;


var webSocketApi = new WebSocketApi(this, "mywsapi");
var stage = new WebSocketStage(this, "mystage", new WebSocketStageProps {
    WebSocketApi = webSocketApi,
    StageName = "dev"
});
// per stage permission
stage.GrantManagementApiAccess(fn);
// for all the stages permission
webSocketApi.GrantManageConnections(fn);
go
var fn Function


webSocketApi := apigwv2.NewWebSocketApi(this, jsii.String("mywsapi"))
stage := apigwv2.NewWebSocketStage(this, jsii.String("mystage"), &WebSocketStageProps{
	WebSocketApi: WebSocketApi,
	StageName: jsii.String("dev"),
})
// per stage permission
stage.GrantManagementApiAccess(fn)
// for all the stages permission
webSocketApi.GrantManageConnections(fn)

Managing access to WebSocket APIs ​

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.

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. 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:

ts
const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi',{
  apiKeySelectionExpression: apigwv2.WebSocketApiKeySelectionExpression.HEADER_X_API_KEY,
});
python
web_socket_api = apigwv2.WebSocketApi(self, "mywsapi",
    api_key_selection_expression=apigwv2.WebSocketApiKeySelectionExpression.HEADER_X_API_KEY
)
java
WebSocketApi webSocketApi = WebSocketApi.Builder.create(this, "mywsapi")
        .apiKeySelectionExpression(WebSocketApiKeySelectionExpression.HEADER_X_API_KEY)
        .build();
csharp
var webSocketApi = new WebSocketApi(this, "mywsapi", new WebSocketApiProps {
    ApiKeySelectionExpression = WebSocketApiKeySelectionExpression.HEADER_X_API_KEY
});
go
webSocketApi := apigwv2.NewWebSocketApi(this, jsii.String("mywsapi"), &WebSocketApiProps{
	ApiKeySelectionExpression: apigwv2.WebSocketApiKeySelectionExpression_HEADER_X_API_KEY(),
})

Usage Plan and API Keys ​

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:

ts
const apiKey = new apigwv2.ApiKey(this, "ApiKey");

const usagePlan = new apigwv2.UsagePlan(this, "UsagePlan", {
  usagePlanName: "WebSocketUsagePlan",
  throttle: {
    rateLimit: 10,
    burstLimit: 2
  }
});

usagePlan.addApiKey(apiKey);
python
api_key = apigwv2.ApiKey(self, "ApiKey")

usage_plan = apigwv2.UsagePlan(self, "UsagePlan",
    usage_plan_name="WebSocketUsagePlan",
    throttle=apigwv2.ThrottleSettings(
        rate_limit=10,
        burst_limit=2
    )
)

usage_plan.add_api_key(api_key)
java
ApiKey apiKey = new ApiKey(this, "ApiKey");

UsagePlan usagePlan = UsagePlan.Builder.create(this, "UsagePlan")
        .usagePlanName("WebSocketUsagePlan")
        .throttle(ThrottleSettings.builder()
                .rateLimit(10)
                .burstLimit(2)
                .build())
        .build();

usagePlan.addApiKey(apiKey);
csharp
var apiKey = new ApiKey(this, "ApiKey");

var usagePlan = new UsagePlan(this, "UsagePlan", new UsagePlanProps {
    UsagePlanName = "WebSocketUsagePlan",
    Throttle = new ThrottleSettings {
        RateLimit = 10,
        BurstLimit = 2
    }
});

usagePlan.AddApiKey(apiKey);
go
apiKey := apigwv2.NewApiKey(this, jsii.String("ApiKey"))

usagePlan := apigwv2.NewUsagePlan(this, jsii.String("UsagePlan"), &UsagePlanProps{
	UsagePlanName: jsii.String("WebSocketUsagePlan"),
	Throttle: &ThrottleSettings{
		RateLimit: jsii.Number(10),
		BurstLimit: jsii.Number(2),
	},
})

usagePlan.addApiKey(apiKey)

To associate a plan to a given WebSocketAPI stage:

ts
const api = new apigwv2.WebSocketApi(this, 'my-api');
const stage = new apigwv2.WebSocketStage(this, 'my-stage', {
  webSocketApi: api,
  stageName: 'dev',
});

const usagePlan = new apigwv2.UsagePlan(this, 'my-usage-plan', {
  usagePlanName: 'Basic',
});

usagePlan.addApiStage({
  api: api,
  stage: stage,
});
python
api = apigwv2.WebSocketApi(self, "my-api")
stage = apigwv2.WebSocketStage(self, "my-stage",
    web_socket_api=api,
    stage_name="dev"
)

usage_plan = apigwv2.UsagePlan(self, "my-usage-plan",
    usage_plan_name="Basic"
)

usage_plan.add_api_stage(
    api=api,
    stage=stage
)
java
WebSocketApi api = new WebSocketApi(this, "my-api");
WebSocketStage stage = WebSocketStage.Builder.create(this, "my-stage")
        .webSocketApi(api)
        .stageName("dev")
        .build();

UsagePlan usagePlan = UsagePlan.Builder.create(this, "my-usage-plan")
        .usagePlanName("Basic")
        .build();

usagePlan.addApiStage(UsagePlanPerApiStage.builder()
        .api(api)
        .stage(stage)
        .build());
csharp
var api = new WebSocketApi(this, "my-api");
var stage = new WebSocketStage(this, "my-stage", new WebSocketStageProps {
    WebSocketApi = api,
    StageName = "dev"
});

var usagePlan = new UsagePlan(this, "my-usage-plan", new UsagePlanProps {
    UsagePlanName = "Basic"
});

usagePlan.AddApiStage(new UsagePlanPerApiStage {
    Api = api,
    Stage = stage
});
go
api := apigwv2.NewWebSocketApi(this, jsii.String("my-api"))
stage := apigwv2.NewWebSocketStage(this, jsii.String("my-stage"), &WebSocketStageProps{
	WebSocketApi: api,
	StageName: jsii.String("dev"),
})

usagePlan := apigwv2.NewUsagePlan(this, jsii.String("my-usage-plan"), &UsagePlanProps{
	UsagePlanName: jsii.String("Basic"),
})

usagePlan.AddApiStage(&UsagePlanPerApiStage{
	Api: api,
	Stage: stage,
})

Existing usage plans can be imported into a CDK app using its id.

ts
const usagePlan: apigwv2.IUsagePlan = apigwv2.UsagePlan.fromUsagePlanId(this, 'imported-usage-plan', '<usage-plan-id>');
python
usage_plan = apigwv2.UsagePlan.from_usage_plan_id(self, "imported-usage-plan", "<usage-plan-id>")
java
IUsagePlan usagePlan = UsagePlan.fromUsagePlanId(this, "imported-usage-plan", "<usage-plan-id>");
csharp
var usagePlan = UsagePlan.FromUsagePlanId(this, "imported-usage-plan", "<usage-plan-id>");
go
usagePlan := apigwv2.UsagePlan_FromUsagePlanId(this, jsii.String("imported-usage-plan"), jsii.String("<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.

ts
// Auto-generated name and value
const autoKey = new apigwv2.ApiKey(this, 'AutoKey');

// Explicit name and value
const explicitKey = new apigwv2.ApiKey(this, 'ExplicitKey', {
  apiKeyName: 'MyWebSocketApiKey',
  value: 'MyApiKeyThatIsAtLeast20Characters',
});
python
# Auto-generated name and value
auto_key = apigwv2.ApiKey(self, "AutoKey")

# Explicit name and value
explicit_key = apigwv2.ApiKey(self, "ExplicitKey",
    api_key_name="MyWebSocketApiKey",
    value="MyApiKeyThatIsAtLeast20Characters"
)
java
// Auto-generated name and value
ApiKey autoKey = new ApiKey(this, "AutoKey");

// Explicit name and value
ApiKey explicitKey = ApiKey.Builder.create(this, "ExplicitKey")
        .apiKeyName("MyWebSocketApiKey")
        .value("MyApiKeyThatIsAtLeast20Characters")
        .build();
csharp
// Auto-generated name and value
var autoKey = new ApiKey(this, "AutoKey");

// Explicit name and value
var explicitKey = new ApiKey(this, "ExplicitKey", new ApiKeyProps {
    ApiKeyName = "MyWebSocketApiKey",
    Value = "MyApiKeyThatIsAtLeast20Characters"
});
go
// Auto-generated name and value
autoKey := apigwv2.NewApiKey(this, jsii.String("AutoKey"))

// Explicit name and value
explicitKey := apigwv2.NewApiKey(this, jsii.String("ExplicitKey"), &ApiKeyProps{
	ApiKeyName: jsii.String("MyWebSocketApiKey"),
	Value: jsii.String("MyApiKeyThatIsAtLeast20Characters"),
})

Existing API keys can also be imported into a CDK app using its id.

ts
const importedKey = apigwv2.ApiKey.fromApiKeyId(this, 'imported-key', '<api-key-id>');
python
imported_key = apigwv2.ApiKey.from_api_key_id(self, "imported-key", "<api-key-id>")
java
IApiKey importedKey = ApiKey.fromApiKeyId(this, "imported-key", "<api-key-id>");
csharp
var importedKey = ApiKey.FromApiKeyId(this, "imported-key", "<api-key-id>");
go
importedKey := apigwv2.ApiKey_FromApiKeyId(this, jsii.String("imported-key"), jsii.String("<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.

ts
import * as iam from 'aws-cdk-lib/aws-iam';

const user = new iam.User(this, 'User');
const apiKey = new apigwv2.ApiKey(this, 'ApiKey', {
  customerId: 'test-customer',
});
apiKey.grantRead(user);
python
import aws_cdk.aws_iam as iam


user = iam.User(self, "User")
api_key = apigwv2.ApiKey(self, "ApiKey",
    customer_id="test-customer"
)
api_key.grant_read(user)
java
import software.amazon.awscdk.services.iam.*;


User user = new User(this, "User");
ApiKey apiKey = ApiKey.Builder.create(this, "ApiKey")
        .customerId("test-customer")
        .build();
apiKey.grantRead(user);
csharp
using Amazon.CDK.AWS.IAM;


var user = new User(this, "User");
var apiKey = new ApiKey(this, "ApiKey", new ApiKeyProps {
    CustomerId = "test-customer"
});
apiKey.GrantRead(user);
go
import iam "github.com/aws/aws-cdk-go/awscdk"


user := iam.NewUser(this, jsii.String("User"))
apiKey := apigwv2.NewApiKey(this, jsii.String("ApiKey"), &ApiKeyProps{
	CustomerId: jsii.String("test-customer"),
})
apiKey.grantRead(user)

Adding an API Key to an imported WebSocketApi ​

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.

ts
declare const webSocketApi: apigwv2.IWebSocketApi;

const importedStage = apigwv2.WebSocketStage.fromWebSocketStageAttributes(this, 'imported-stage', {
  stageName: 'myStage',
  api: webSocketApi,
});

const apiKey = new apigwv2.ApiKey(this, 'MyApiKey');

const usagePlan = new apigwv2.UsagePlan(this, 'MyUsagePlan', {
  apiStages: [{ api: webSocketApi, stage: importedStage }],
});

usagePlan.addApiKey(apiKey);
python
# web_socket_api: apigwv2.IWebSocketApi


imported_stage = apigwv2.WebSocketStage.from_web_socket_stage_attributes(self, "imported-stage",
    stage_name="myStage",
    api=web_socket_api
)

api_key = apigwv2.ApiKey(self, "MyApiKey")

usage_plan = apigwv2.UsagePlan(self, "MyUsagePlan",
    api_stages=[apigwv2.UsagePlanPerApiStage(api=web_socket_api, stage=imported_stage)]
)

usage_plan.add_api_key(api_key)
java
IWebSocketApi webSocketApi;


IWebSocketStage importedStage = WebSocketStage.fromWebSocketStageAttributes(this, "imported-stage", WebSocketStageAttributes.builder()
        .stageName("myStage")
        .api(webSocketApi)
        .build());

ApiKey apiKey = new ApiKey(this, "MyApiKey");

UsagePlan usagePlan = UsagePlan.Builder.create(this, "MyUsagePlan")
        .apiStages(List.of(UsagePlanPerApiStage.builder().api(webSocketApi).stage(importedStage).build()))
        .build();

usagePlan.addApiKey(apiKey);
csharp
IWebSocketApi webSocketApi;


var importedStage = WebSocketStage.FromWebSocketStageAttributes(this, "imported-stage", new WebSocketStageAttributes {
    StageName = "myStage",
    Api = webSocketApi
});

var apiKey = new ApiKey(this, "MyApiKey");

var usagePlan = new UsagePlan(this, "MyUsagePlan", new UsagePlanProps {
    ApiStages = new [] { new UsagePlanPerApiStage { Api = webSocketApi, Stage = importedStage } }
});

usagePlan.AddApiKey(apiKey);
go
var webSocketApi IWebSocketApi


importedStage := apigwv2.WebSocketStage_FromWebSocketStageAttributes(this, jsii.String("imported-stage"), &WebSocketStageAttributes{
	StageName: jsii.String("myStage"),
	Api: webSocketApi,
})

apiKey := apigwv2.NewApiKey(this, jsii.String("MyApiKey"))

usagePlan := apigwv2.NewUsagePlan(this, jsii.String("MyUsagePlan"), &UsagePlanProps{
	ApiStages: []UsagePlanPerApiStage{
		&UsagePlanPerApiStage{
			Api: webSocketApi,
			Stage: importedStage,
		},
	},
})

usagePlan.addApiKey(apiKey)

Multiple API Keys ​

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 addApiKey() method

ts
declare const usagePlan: apigwv2.UsagePlan;
declare const apiKey: apigwv2.ApiKey;

usagePlan.addApiKey(apiKey, {
 overrideLogicalId: 'MyCustomLogicalId',
});
python
# usage_plan: apigwv2.UsagePlan
# api_key: apigwv2.ApiKey


usage_plan.add_api_key(api_key,
    override_logical_id="MyCustomLogicalId"
)
java
UsagePlan usagePlan;
ApiKey apiKey;


usagePlan.addApiKey(apiKey, AddApiKeyOptions.builder()
        .overrideLogicalId("MyCustomLogicalId")
        .build());
csharp
UsagePlan usagePlan;
ApiKey apiKey;


usagePlan.AddApiKey(apiKey, new AddApiKeyOptions {
    OverrideLogicalId = "MyCustomLogicalId"
});
go
var usagePlan UsagePlan
var apiKey ApiKey


usagePlan.addApiKey(apiKey, &AddApiKeyOptions{
	OverrideLogicalId: jsii.String("MyCustomLogicalId"),
})

Rate Limited API Key ​

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 :

ts
declare const api: apigwv2.WebSocketApi;
declare const stage: apigwv2.WebSocketStage;

const key = new apigwv2.RateLimitedApiKey(this, 'rate-limited-api-key', {
  customerId: 'test-customer',
  apiStages: [{
    api: api,
    stage: stage
  }],
  quota: {
    limit: 10000,
    period: apigwv2.Period.MONTH
  },
  throttle: {
    rateLimit: 100,
    burstLimit: 200
  }
});
python
# api: apigwv2.WebSocketApi
# stage: apigwv2.WebSocketStage


key = apigwv2.RateLimitedApiKey(self, "rate-limited-api-key",
    customer_id="test-customer",
    api_stages=[apigwv2.UsagePlanPerApiStage(
        api=api,
        stage=stage
    )],
    quota=apigwv2.QuotaSettings(
        limit=10000,
        period=apigwv2.Period.MONTH
    ),
    throttle=apigwv2.ThrottleSettings(
        rate_limit=100,
        burst_limit=200
    )
)
java
WebSocketApi api;
WebSocketStage stage;


RateLimitedApiKey key = RateLimitedApiKey.Builder.create(this, "rate-limited-api-key")
        .customerId("test-customer")
        .apiStages(List.of(UsagePlanPerApiStage.builder()
                .api(api)
                .stage(stage)
                .build()))
        .quota(QuotaSettings.builder()
                .limit(10000)
                .period(Period.MONTH)
                .build())
        .throttle(ThrottleSettings.builder()
                .rateLimit(100)
                .burstLimit(200)
                .build())
        .build();
csharp
WebSocketApi api;
WebSocketStage stage;


var key = new RateLimitedApiKey(this, "rate-limited-api-key", new RateLimitedApiKeyProps {
    CustomerId = "test-customer",
    ApiStages = new [] { new UsagePlanPerApiStage {
        Api = api,
        Stage = stage
    } },
    Quota = new QuotaSettings {
        Limit = 10000,
        Period = Period.MONTH
    },
    Throttle = new ThrottleSettings {
        RateLimit = 100,
        BurstLimit = 200
    }
});
go
var api WebSocketApi
var stage WebSocketStage


key := apigwv2.NewRateLimitedApiKey(this, jsii.String("rate-limited-api-key"), &RateLimitedApiKeyProps{
	CustomerId: jsii.String("test-customer"),
	ApiStages: []UsagePlanPerApiStage{
		&UsagePlanPerApiStage{
			Api: api,
			Stage: stage,
		},
	},
	Quota: &QuotaSettings{
		Limit: jsii.Number(10000),
		Period: apigwv2.Period_MONTH,
	},
	Throttle: &ThrottleSettings{
		RateLimit: jsii.Number(100),
		BurstLimit: jsii.Number(200),
	},
})

Common Config ​

Common config for both HTTP API and WebSocket API

Route Settings ​

Represents a collection of route settings.

ts
declare const api: apigwv2.HttpApi;

new apigwv2.HttpStage(this, 'Stage', {
  httpApi: api,
  throttle: {
    rateLimit: 1000,
    burstLimit: 1000,
  },
  detailedMetricsEnabled: true,
});
python
# api: apigwv2.HttpApi


apigwv2.HttpStage(self, "Stage",
    http_api=api,
    throttle=apigwv2.ThrottleSettings(
        rate_limit=1000,
        burst_limit=1000
    ),
    detailed_metrics_enabled=True
)
java
HttpApi api;


HttpStage.Builder.create(this, "Stage")
        .httpApi(api)
        .throttle(ThrottleSettings.builder()
                .rateLimit(1000)
                .burstLimit(1000)
                .build())
        .detailedMetricsEnabled(true)
        .build();
csharp
HttpApi api;


new HttpStage(this, "Stage", new HttpStageProps {
    HttpApi = api,
    Throttle = new ThrottleSettings {
        RateLimit = 1000,
        BurstLimit = 1000
    },
    DetailedMetricsEnabled = true
});
go
var api HttpApi


apigwv2.NewHttpStage(this, jsii.String("Stage"), &HttpStageProps{
	HttpApi: api,
	Throttle: &ThrottleSettings{
		RateLimit: jsii.Number(1000),
		BurstLimit: jsii.Number(1000),
	},
	DetailedMetricsEnabled: jsii.Boolean(true),
})

Access Logging ​

You can turn on logging to write logs to CloudWatch Logs. Read more at Configure logging for HTTP APIs or WebSocket APIs

ts
import * as logs from 'aws-cdk-lib/aws-logs';

declare const httpApi: apigwv2.HttpApi;
declare const webSocketApi : apigwv2.WebSocketApi;
declare const logGroup: logs.LogGroup;

new apigwv2.HttpStage(this, 'HttpStage', {
  httpApi,
  accessLogSettings: {
    destination: new apigwv2.LogGroupLogDestination(logGroup),
  },
});

new apigwv2.WebSocketStage(this, 'WebSocketStage', {
  webSocketApi,
  stageName: 'dev',
  accessLogSettings: {
    destination: new apigwv2.LogGroupLogDestination(logGroup),
  },
});
python
import aws_cdk.aws_logs as logs

# http_api: apigwv2.HttpApi
# web_socket_api: apigwv2.WebSocketApi
# log_group: logs.LogGroup


apigwv2.HttpStage(self, "HttpStage",
    http_api=http_api,
    access_log_settings={
        "destination": apigwv2.LogGroupLogDestination(log_group)
    }
)

apigwv2.WebSocketStage(self, "WebSocketStage",
    web_socket_api=web_socket_api,
    stage_name="dev",
    access_log_settings={
        "destination": apigwv2.LogGroupLogDestination(log_group)
    }
)
java
import software.amazon.awscdk.services.logs.*;

HttpApi httpApi;
WebSocketApi webSocketApi;
LogGroup logGroup;


HttpStage.Builder.create(this, "HttpStage")
        .httpApi(httpApi)
        .accessLogSettings(Map.of(
                "destination", new LogGroupLogDestination(logGroup)))
        .build();

WebSocketStage.Builder.create(this, "WebSocketStage")
        .webSocketApi(webSocketApi)
        .stageName("dev")
        .accessLogSettings(Map.of(
                "destination", new LogGroupLogDestination(logGroup)))
        .build();
csharp
using Amazon.CDK.AWS.Logs;

HttpApi httpApi;
WebSocketApi webSocketApi;
LogGroup logGroup;


new HttpStage(this, "HttpStage", new HttpStageProps {
    HttpApi = httpApi,
    AccessLogSettings = new Dictionary<string, IAccessLogDestination> {
        { "destination", new LogGroupLogDestination(logGroup) }
    }
});

new WebSocketStage(this, "WebSocketStage", new WebSocketStageProps {
    WebSocketApi = webSocketApi,
    StageName = "dev",
    AccessLogSettings = new Dictionary<string, IAccessLogDestination> {
        { "destination", new LogGroupLogDestination(logGroup) }
    }
});
go
import logs "github.com/aws/aws-cdk-go/awscdk"

var httpApi HttpApi
var webSocketApi WebSocketApi
var logGroup LogGroup


apigwv2.NewHttpStage(this, jsii.String("HttpStage"), &HttpStageProps{
	HttpApi: HttpApi,
	AccessLogSettings: map[string]IAccessLogDestination{
		"destination": apigwv2.NewLogGroupLogDestination(logGroup),
	},
})

apigwv2.NewWebSocketStage(this, jsii.String("WebSocketStage"), &WebSocketStageProps{
	WebSocketApi: WebSocketApi,
	StageName: jsii.String("dev"),
	AccessLogSettings: map[string]IAccessLogDestination{
		"destination": apigwv2.NewLogGroupLogDestination(logGroup),
	},
})

The following code will generate the access log in the CLF format.

ts
import * as apigw from 'aws-cdk-lib/aws-apigateway';
import * as logs from 'aws-cdk-lib/aws-logs';

declare const api: apigwv2.HttpApi;
declare const logGroup: logs.LogGroup;

const stage = new apigwv2.HttpStage(this, 'Stage', {
  httpApi: api,
  accessLogSettings: {
    destination: new apigwv2.LogGroupLogDestination(logGroup),
    format: apigw.AccessLogFormat.clf(),
  },
});
python
import aws_cdk.aws_apigateway as apigw
import aws_cdk.aws_logs as logs

# api: apigwv2.HttpApi
# log_group: logs.LogGroup


stage = apigwv2.HttpStage(self, "Stage",
    http_api=api,
    access_log_settings={
        "destination": apigwv2.LogGroupLogDestination(log_group),
        "format": apigw.AccessLogFormat.clf()
    }
)
java
import software.amazon.awscdk.services.apigateway.*;
import software.amazon.awscdk.services.logs.*;

HttpApi api;
LogGroup logGroup;


HttpStage stage = HttpStage.Builder.create(this, "Stage")
        .httpApi(api)
        .accessLogSettings(Map.of(
                "destination", new LogGroupLogDestination(logGroup),
                "format", AccessLogFormat.clf()))
        .build();
csharp
using Amazon.CDK.AWS.APIGateway;
using Amazon.CDK.AWS.Logs;

HttpApi api;
LogGroup logGroup;


var stage = new HttpStage(this, "Stage", new HttpStageProps {
    HttpApi = api,
    AccessLogSettings = new Dictionary<string, object> {
        { "destination", new LogGroupLogDestination(logGroup) },
        { "format", AccessLogFormat.Clf() }
    }
});
go
import apigw "github.com/aws/aws-cdk-go/awscdk"
import logs "github.com/aws/aws-cdk-go/awscdk"

var api HttpApi
var logGroup LogGroup


stage := apigwv2.NewHttpStage(this, jsii.String("Stage"), &HttpStageProps{
	HttpApi: api,
	AccessLogSettings: map[string]interface{}{
		"destination": apigwv2.NewLogGroupLogDestination(logGroup),
		"format": apigw.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.

ts
import * as apigw from 'aws-cdk-lib/aws-apigateway';
import * as logs from 'aws-cdk-lib/aws-logs';

declare const api: apigwv2.HttpApi;
declare const logGroup: logs.LogGroup;

const stage = new apigwv2.HttpStage(this, 'Stage', {
  httpApi: api,
  accessLogSettings: {
    destination: new apigwv2.LogGroupLogDestination(logGroup),
    format: apigw.AccessLogFormat.custom(
      `${apigw.AccessLogField.contextRequestId()} ${apigw.AccessLogField.contextErrorMessage()} ${apigw.AccessLogField.contextErrorMessageString()}
      ${apigw.AccessLogField.contextAuthorizerError()} ${apigw.AccessLogField.contextAuthorizerIntegrationStatus()}`
    ),
  },
});
python
import aws_cdk.aws_apigateway as apigw
import aws_cdk.aws_logs as logs

# api: apigwv2.HttpApi
# log_group: logs.LogGroup


stage = apigwv2.HttpStage(self, "Stage",
    http_api=api,
    access_log_settings={
        "destination": apigwv2.LogGroupLogDestination(log_group),
        "format": apigw.AccessLogFormat.custom(f"""{apigw.AccessLogField.contextRequestId()} {apigw.AccessLogField.contextErrorMessage()} {apigw.AccessLogField.contextErrorMessageString()}
                  {apigw.AccessLogField.contextAuthorizerError()} {apigw.AccessLogField.contextAuthorizerIntegrationStatus()}""")
    }
)
java
import software.amazon.awscdk.services.apigateway.*;
import software.amazon.awscdk.services.logs.*;

HttpApi api;
LogGroup logGroup;


HttpStage stage = HttpStage.Builder.create(this, "Stage")
        .httpApi(api)
        .accessLogSettings(Map.of(
                "destination", new LogGroupLogDestination(logGroup),
                "format", AccessLogFormat.custom(String.format("%s %s %s%n      %s %s", AccessLogField.contextRequestId(), AccessLogField.contextErrorMessage(), AccessLogField.contextErrorMessageString(), AccessLogField.contextAuthorizerError(), AccessLogField.contextAuthorizerIntegrationStatus()))))
        .build();
csharp
using Amazon.CDK.AWS.APIGateway;
using Amazon.CDK.AWS.Logs;

HttpApi api;
LogGroup logGroup;


var stage = new HttpStage(this, "Stage", new HttpStageProps {
    HttpApi = api,
    AccessLogSettings = new Dictionary<string, object> {
        { "destination", new LogGroupLogDestination(logGroup) },
        { "format", AccessLogFormat.Custom($@"{apigw.AccessLogField.contextRequestId()} {apigw.AccessLogField.contextErrorMessage()} {apigw.AccessLogField.contextErrorMessageString()}
              {apigw.AccessLogField.contextAuthorizerError()} {apigw.AccessLogField.contextAuthorizerIntegrationStatus()}") }
    }
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import logs "github.com/aws/aws-cdk-go/awscdk"

var api HttpApi
var logGroup LogGroup


stage := apigwv2.NewHttpStage(this, jsii.String("Stage"), &HttpStageProps{
	HttpApi: api,
	AccessLogSettings: map[string]interface{}{
		"destination": apigwv2.NewLogGroupLogDestination(logGroup),
		"format": apigw.AccessLogFormat_custom(
		fmt.Sprintf("%v %v %v\n      %v %v", apigw.AccessLogField_contextRequestId(), apigw.AccessLogField_contextErrorMessage(), apigw.AccessLogField_contextErrorMessageString(), apigw.AccessLogField_contextAuthorizerError(), apigw.AccessLogField_contextAuthorizerIntegrationStatus())),
	},
})

Types ​

NameKindSummary
ApiKeyConstruct (L2)An API Gateway ApiKey.
ApiMappingConstruct (L2)Create a new API mapping for API Gateway API endpoint.
DomainNameConstruct (L2)Custom domain resource for the API.
HttpApiConstruct (L2)Create a new API Gateway HTTP API endpoint.
HttpAuthorizerConstruct (L2)An authorizer for Http Apis.
HttpIntegrationConstruct (L2)The integration for an API route.
HttpRouteConstruct (L2)Route class that creates the Route for API Gateway HTTP API.
HttpStageConstruct (L2)Represents a stage where an instance of the API is deployed.
RateLimitedApiKeyConstruct (L2)An API Gateway ApiKey, for which a rate limiting configuration can be specified.
UsagePlanConstruct (L2)A UsagePlan.
VpcLinkConstruct (L2)Define a new VPC Link Specifies an API Gateway VPC link for a HTTP API to access resources in an Amazon Virtual Private Cloud (VPC).
WebSocketApiConstruct (L2)Create a new API Gateway WebSocket API endpoint.
WebSocketAuthorizerConstruct (L2)An authorizer for WebSocket Apis.
WebSocketIntegrationConstruct (L2)The integration for an API route.
WebSocketRouteConstruct (L2)Route class that creates the Route for API Gateway WebSocket API.
WebSocketStageConstruct (L2)Represents a stage where an instance of the API is deployed.
CfnApiConstruct (L1)The AWS::ApiGatewayV2::Api resource creates an API.
CfnApiGatewayManagedOverridesConstruct (L1)The AWS::ApiGatewayV2::ApiGatewayManagedOverrides resource overrides the default properties of API Gateway-managed resources that are implicitly configured for you when you use quick create.
CfnApiMappingConstruct (L1)The AWS::ApiGatewayV2::ApiMapping resource contains an API mapping.
CfnAuthorizerConstruct (L1)The AWS::ApiGatewayV2::Authorizer resource creates an authorizer for a WebSocket API or an HTTP API.
CfnDeploymentConstruct (L1)The AWS::ApiGatewayV2::Deployment resource creates a deployment for an API.
CfnDomainNameConstruct (L1)The AWS::ApiGatewayV2::DomainName resource specifies a custom domain name for your API in Amazon API Gateway (API Gateway).
CfnIntegrationConstruct (L1)The AWS::ApiGatewayV2::Integration resource creates an integration for an API.
CfnIntegrationResponseConstruct (L1)The AWS::ApiGatewayV2::IntegrationResponse resource updates an integration response for an WebSocket API.
CfnModelConstruct (L1)The AWS::ApiGatewayV2::Model resource updates data model for a WebSocket API.
CfnPortalProductConstruct (L1)Represents a portal product in Amazon API Gateway V2, which is a logical grouping of APIs that can be published in a developer portal.
CfnRouteConstruct (L1)The AWS::ApiGatewayV2::Route resource creates a route for an API.
CfnRouteResponseConstruct (L1)The AWS::ApiGatewayV2::RouteResponse resource creates a route response for a WebSocket API.
CfnRoutingRuleConstruct (L1)Represents a routing rule.
CfnStageConstruct (L1)The AWS::ApiGatewayV2::Stage resource specifies a stage for an API.
CfnVpcLinkConstruct (L1)The AWS::ApiGatewayV2::VpcLink resource creates a VPC link.
AccessLogDestinationConfigStructOptions when binding a log destination to a HttpApi Stage.
AddApiKeyOptionsStructOptions to the UsagePlan.addApiKey() method.
AddRoutesOptionsStructOptions for the Route with Integration resource.
ApiKeyOptionsStructThe options for creating an API Key.
ApiKeyPropsStructApiKey Properties.
ApiMappingAttributesStructThe attributes used to import existing ApiMapping.
ApiMappingPropsStructProperties used to create the ApiMapping resource.
AuthorizerPayloadVersionEnumPayload format version for lambda authorizers.
BatchHttpRouteOptionsStructOptions used when configuring multiple routes, at once.
CfnApi.BodyS3LocationPropertyStructThe BodyS3Location property specifies an S3 location from which to import an OpenAPI definition.
CfnApi.CorsPropertyStructThe Cors property specifies a CORS configuration for an API.
CfnApiGatewayManagedOverrides.AccessLogSettingsPropertyStructThe AccessLogSettings property overrides the access log settings for an API Gateway-managed stage.
CfnApiGatewayManagedOverrides.IntegrationOverridesPropertyStructThe IntegrationOverrides property overrides the integration settings for an API Gateway-managed integration.
CfnApiGatewayManagedOverrides.RouteOverridesPropertyStructThe RouteOverrides property overrides the route configuration for an API Gateway-managed route.
CfnApiGatewayManagedOverrides.RouteSettingsPropertyStructThe RouteSettings property overrides the route settings for an API Gateway-managed route.
CfnApiGatewayManagedOverrides.StageOverridesPropertyStructThe StageOverrides property overrides the stage configuration for an API Gateway-managed stage.
CfnApiGatewayManagedOverridesPropsStructProperties for defining a CfnApiGatewayManagedOverrides.
CfnApiMappingPropsStructProperties for defining a CfnApiMapping.
CfnApiPropsStructProperties for defining a CfnApi.
CfnAuthorizer.JWTConfigurationPropertyStructThe JWTConfiguration property specifies the configuration of a JWT authorizer.
CfnAuthorizerPropsStructProperties for defining a CfnAuthorizer.
CfnDeploymentPropsStructProperties for defining a CfnDeployment.
CfnDomainName.DomainNameConfigurationPropertyStructThe DomainNameConfiguration property type specifies the configuration for an API's domain name.
CfnDomainName.MutualTlsAuthenticationPropertyStructIf specified, API Gateway performs two-way authentication between the client and the server.
CfnDomainNamePropsStructProperties for defining a CfnDomainName.
CfnIntegration.ResponseParameterListPropertyStruct
CfnIntegration.ResponseParameterMapPropertyStructmap of response parameter lists.
CfnIntegration.ResponseParameterPropertyStructSupported only for HTTP APIs.
CfnIntegration.TlsConfigPropertyStructThe TlsConfig property specifies the TLS configuration for a private integration.
CfnIntegrationPropsStructProperties for defining a CfnIntegration.
CfnIntegrationResponsePropsStructProperties for defining a CfnIntegrationResponse.
CfnModelPropsStructProperties for defining a CfnModel.
CfnPortalProductPropsStructProperties for defining a CfnPortalProduct.
CfnRoute.ParameterConstraintsPropertyStruct
CfnRoutePropsStructProperties for defining a CfnRoute.
CfnRouteResponse.ParameterConstraintsPropertyStructSpecifies whether the parameter is required.
CfnRouteResponsePropsStructProperties for defining a CfnRouteResponse.
CfnRoutingRule.ActionInvokeApiPropertyStructRepresents an InvokeApi action.
CfnRoutingRule.ActionPropertyStructRepresents a routing rule action.
CfnRoutingRule.ConditionPropertyStructRepresents a condition.
CfnRoutingRule.MatchBasePathsPropertyStructRepresents a MatchBasePaths condition.
CfnRoutingRule.MatchHeadersPropertyStructRepresents a MatchHeaders condition.
CfnRoutingRule.MatchHeaderValuePropertyStructRepresents a MatchHeaderValue .
CfnRoutingRulePropsStructProperties for defining a CfnRoutingRule.
CfnStage.AccessLogSettingsPropertyStructSettings for logging access in a stage.
CfnStage.RouteSettingsPropertyStructRepresents a collection of route settings.
CfnStagePropsStructProperties for defining a CfnStage.
CfnVpcLinkPropsStructProperties for defining a CfnVpcLink.
ContentHandlingEnumIntegration content handling.
CorsHttpMethodEnumSupported CORS HTTP methods.
CorsPreflightOptionsStructOptions for the CORS Configuration.
DomainMappingOptionsStructOptions for DomainMapping.
DomainNameAttributesStructcustom domain name attributes.
DomainNamePropsStructproperties used for creating the DomainName.
EndpointOptionsStructproperties for creating a domain name endpoint.
EndpointTypeEnumEndpoint type for a domain name.
GrantInvokeOptionsStructOptions for granting invoke access.
HttpApiAttributesStructAttributes for importing an HttpApi into the CDK.
HttpApiHelperFacadeCalculations and operations for HTTP APIs.
HttpApiPropsStructProperties to initialize an instance of HttpApi.
HttpAuthorizerAttributesStructReference to an http authorizer.
HttpAuthorizerPropsStructProperties to initialize an instance of HttpAuthorizer.
HttpAuthorizerTypeEnumSupported Authorizer types.
HttpConnectionTypeEnumSupported connection types.
HttpIntegrationPropsStructThe integration properties.
HttpIntegrationSubtypeEnumSupported integration subtypes.
HttpIntegrationTypeEnumSupported integration types.
HttpMethodEnumSupported HTTP methods.
HttpNoneAuthorizerClassExplicitly configure no authorizers on specific HTTP API routes.
HttpRouteAuthorizerBindOptionsStructInput to the bind() operation, that binds an authorizer to a route.
HttpRouteAuthorizerConfigStructResults of binding an authorizer to an http route.
HttpRouteIntegrationClassThe interface that various route integration classes will inherit.
HttpRouteIntegrationBindOptionsStructOptions to the HttpRouteIntegration during its bind operation.
HttpRouteIntegrationConfigStructConfig returned back as a result of the bind.
HttpRouteKeyClassHTTP route in APIGateway is a combination of the HTTP method and the path component.
HttpRoutePropsStructProperties to initialize a new Route.
HttpStageAttributesStructThe attributes used to import existing HttpStage.
HttpStageOptionsStructThe options to create a new Stage for an HTTP API.
HttpStagePropsStructProperties to initialize an instance of HttpStage.
IAccessLogDestinationInterfaceAccess log destination for a HttpApi Stage.
IAccessLogSettingsInterfaceSettings for access logging.
IApiInterfaceRepresents a API Gateway HTTP/WebSocket API.
IApiKeyInterfaceAPI keys are alphanumeric string values that you distribute to app developer customers to grant access to your API.
IApiMappingInterfaceRepresents an ApiGatewayV2 ApiMapping resource.
IAuthorizerInterfaceRepresents an Authorizer.
IDomainNameInterfaceRepresents an APIGatewayV2 DomainName.
IHttpApiInterfaceRepresents an HTTP API.
IHttpApiRefInterfaceRepresents a reference to an HTTP API.
IHttpAuthorizerInterfaceAn authorizer for HTTP APIs.
IHttpIntegrationInterfaceRepresents an Integration for an HTTP API.
IHttpRouteInterfaceRepresents a Route for an HTTP API.
IHttpRouteAuthorizerInterfaceAn authorizer that can attach to an Http Route.
IHttpStageInterfaceRepresents the HttpStage.
IHttpStageRefInterfaceRepresents a reference to an HTTP Stage.
IIntegrationInterfaceRepresents an integration to an API Route.
IMappingValueInterfaceRepresents a Mapping Value.
IntegrationCredentialsClassCredentials used for AWS Service integrations.
IpAddressTypeEnumSupported IP Address Types.
IRouteInterfaceRepresents a route.
IStageInterfaceRepresents a Stage.
IUsagePlanInterfaceA UsagePlan, either managed by this CDK app, or imported.
IVpcLinkInterfaceRepresents an API Gateway VpcLink.
IWebSocketApiInterfaceRepresents a WebSocket API.
IWebSocketApiRefInterfaceRepresents a reference to an HTTP API.
IWebSocketAuthorizerInterfaceAn authorizer for WebSocket APIs.
IWebSocketIntegrationInterfaceRepresents an Integration for an WebSocket API.
IWebSocketRouteInterfaceRepresents a Route for an WebSocket API.
IWebSocketRouteAuthorizerInterfaceAn authorizer that can attach to an WebSocket Route.
IWebSocketStageInterfaceRepresents the WebSocketStage.
LogGroupLogDestinationClassUse CloudWatch Logs as a custom access log destination for API Gateway.
MappingValueClassRepresents a Mapping Value.
MTLSConfigStructThe mTLS authentication configuration for a custom domain name.
ParameterMappingClassRepresents a Parameter Mapping.
PassthroughBehaviorEnumIntegration Passthrough Behavior.
PayloadFormatVersionClassPayload format version for lambda proxy integration.
PeriodEnumTime period for which quota settings apply.
QuotaSettingsStructSpecifies the maximum number of requests that clients can make to API Gateway APIs.
RateLimitedApiKeyPropsStructRateLimitedApiKey properties.
SecurityPolicyEnumThe minimum version of the SSL protocol that you want API Gateway to use for HTTPS connections.
StageAttributesStructThe attributes used to import existing Stage.
StageOptionsStructOptions required to create a new stage.
ThrottleSettingsStructContainer for defining throttling parameters to API stages.
UsagePlanPerApiStageStructRepresents the API stages that a usage plan applies to.
UsagePlanPropsStructProperties for defining an API Gateway Usage Plan for WebSocket APIs.
VpcLinkAttributesStructAttributes when importing a new VpcLink.
VpcLinkPropsStructProperties for a VpcLink.
WebSocketApiAttributesStructAttributes for importing a WebSocketApi into the CDK.
WebSocketApiKeySelectionExpressionClassRepresents the currently available API Key Selection Expressions.
WebSocketApiPropsStructProps for WebSocket API.
WebSocketAuthorizerAttributesStructReference to an WebSocket authorizer.
WebSocketAuthorizerPropsStructProperties to initialize an instance of WebSocketAuthorizer.
WebSocketAuthorizerTypeEnumSupported Authorizer types.
WebSocketIntegrationPropsStructThe integration properties.
WebSocketIntegrationTypeEnumWebSocket Integration Types.
WebSocketNoneAuthorizerClassExplicitly configure no authorizers on specific WebSocket API routes.
WebSocketRouteAuthorizerBindOptionsStructInput to the bind() operation, that binds an authorizer to a route.
WebSocketRouteAuthorizerConfigStructResults of binding an authorizer to an WebSocket route.
WebSocketRouteIntegrationClassThe interface that various route integration classes will inherit.
WebSocketRouteIntegrationBindOptionsStructOptions to the WebSocketRouteIntegration during its bind operation.
WebSocketRouteIntegrationConfigStructConfig returned back as a result of the bind.
WebSocketRouteOptionsStructOptions used to add route to the API.
WebSocketRoutePropsStructProperties to initialize a new Route.
WebSocketStageAttributesStructThe attributes used to import existing WebSocketStage.
WebSocketStagePropsStructProperties to initialize an instance of WebSocketStage.