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.
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,
});
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
)
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());
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
});
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.
const httpApi = new apigwv2.HttpApi(this, 'HttpApi', {
disableExecuteApiEndpoint: true,
});
http_api = apigwv2.HttpApi(self, "HttpApi",
disable_execute_api_endpoint=True
)
HttpApi httpApi = HttpApi.Builder.create(this, "HttpApi")
.disableExecuteApiEndpoint(true)
.build();
var httpApi = new HttpApi(this, "HttpApi", new HttpApiProps {
DisableExecuteApiEndpoint = true
});
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.
import { HttpUrlIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
new apigwv2.HttpApi(this, 'HttpProxyApi', {
defaultIntegration: new HttpUrlIntegration('DefaultIntegration', 'https://example.com'),
});
from aws_cdk.aws_apigatewayv2_integrations import HttpUrlIntegration
apigwv2.HttpApi(self, "HttpProxyApi",
default_integration=HttpUrlIntegration("DefaultIntegration", "https://example.com")
)
import software.amazon.awscdk.aws_apigatewayv2_integrations.HttpUrlIntegration;
HttpApi.Builder.create(this, "HttpProxyApi")
.defaultIntegration(new HttpUrlIntegration("DefaultIntegration", "https://example.com"))
.build();
using Amazon.CDK.AwsApigatewayv2Integrations;
new HttpApi(this, "HttpProxyApi", new HttpApiProps {
DefaultIntegration = new HttpUrlIntegration("DefaultIntegration", "https://example.com")
});
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.
new apigwv2.HttpApi(this, 'HttpProxyApi', {
routeSelectionExpression: true,
});
apigwv2.HttpApi(self, "HttpProxyApi",
route_selection_expression=True
)
HttpApi.Builder.create(this, "HttpProxyApi")
.routeSelectionExpression(true)
.build();
new HttpApi(this, "HttpProxyApi", new HttpApiProps {
RouteSelectionExpression = true
});
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.
new apigwv2.HttpApi(this, 'HttpApi', {
ipAddressType: apigwv2.IpAddressType.DUAL_STACK,
});
apigwv2.HttpApi(self, "HttpApi",
ip_address_type=apigwv2.IpAddressType.DUAL_STACK
)
HttpApi.Builder.create(this, "HttpApi")
.ipAddressType(IpAddressType.DUAL_STACK)
.build();
new HttpApi(this, "HttpApi", new HttpApiProps {
IpAddressType = IpAddressType.DUAL_STACK
});
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.
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),
},
});
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)
)
)
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();
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)
}
});
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.
declare const api: apigwv2.HttpApi;
new apigwv2.HttpStage(this, 'Stage', {
httpApi: api,
stageName: 'beta',
description: 'My Stage',
});
# api: apigwv2.HttpApi
apigwv2.HttpStage(self, "Stage",
http_api=api,
stage_name="beta",
description="My Stage"
)
HttpApi api;
HttpStage.Builder.create(this, "Stage")
.httpApi(api)
.stageName("beta")
.description("My Stage")
.build();
HttpApi api;
new HttpStage(this, "Stage", new HttpStageProps {
HttpApi = api,
StageName = "beta",
Description = "My Stage"
});
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.
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',
},
});
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"
)
)
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();
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"
}
});
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.
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,
});
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
)
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();
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
});
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 -
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',
},
});
# 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"
)
)
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());
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"
}
});
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 -
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',
},
});
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"
)
)
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();
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"
}
});
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.
| 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 -
declare const apiDemo: apigwv2.HttpApi;
const demoDomainUrl = apiDemo.defaultStage?.domainUrl; // returns "https://example.com/demo"
# api_demo: apigwv2.HttpApi
demo_domain_url = api_demo.default_stage.domain_url
HttpApi apiDemo;
String demoDomainUrl = apiDemo.getDefaultStage().getDomainUrl();
HttpApi apiDemo;
var demoDomainUrl = apiDemo.DefaultStage.DomainUrl;
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.
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',
},
});
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"
)
)
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();
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"
}
});
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.
const api = new apigwv2.HttpApi(this, 'my-api');
const clientErrorMetric = api.metricClientError();
api = apigwv2.HttpApi(self, "my-api")
client_error_metric = api.metric_client_error()
HttpApi api = new HttpApi(this, "my-api");
Metric clientErrorMetric = api.metricClientError();
var api = new HttpApi(this, "my-api");
var clientErrorMetric = api.MetricClientError();
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.
const api = new apigwv2.HttpApi(this, 'my-api');
const stage = new apigwv2.HttpStage(this, 'Stage', {
httpApi: api,
});
const clientErrorMetric = stage.metricClientError();
api = apigwv2.HttpApi(self, "my-api")
stage = apigwv2.HttpStage(self, "Stage",
http_api=api
)
client_error_metric = stage.metric_client_error()
HttpApi api = new HttpApi(this, "my-api");
HttpStage stage = HttpStage.Builder.create(this, "Stage")
.httpApi(api)
.build();
Metric clientErrorMetric = stage.metricClientError();
var api = new HttpApi(this, "my-api");
var stage = new HttpStage(this, "Stage", new HttpStageProps {
HttpApi = api
});
var clientErrorMetric = stage.MetricClientError();
api := apigwv2.NewHttpApi(this, jsii.String("my-api"))
stage := apigwv2.NewHttpStage(this, jsii.String("Stage"), &HttpStageProps{
HttpApi: api,
})
clientErrorMetric := stage.metricClientError()
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.
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], {});
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])
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();
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 { });
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().
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,
});
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
)
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());
using Amazon.CDK.AWS.EC2;
Vpc vpc;
var awesomeLink = VpcLink.FromVpcLinkAttributes(this, "awesome-vpc-link", new VpcLinkAttributes {
VpcLinkId = "us-east-1_oiuR12Abd",
Vpc = vpc
});
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.
const api = new apigwv2.HttpApi(this, 'my-api');
const arn = api.arnForExecuteApi('GET', '/myApiPath', 'dev');
api = apigwv2.HttpApi(self, "my-api")
arn = api.arn_for_execute_api("GET", "/myApiPath", "dev")
HttpApi api = new HttpApi(this, "my-api");
String arn = api.arnForExecuteApi("GET", "/myApiPath", "dev");
var api = new HttpApi(this, "my-api");
var arn = api.ArnForExecuteApi("GET", "/myApiPath", "dev");
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:
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,
});
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
)
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();
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
});
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:
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}
# 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
WebSocketStage webSocketStage;
String webSocketURL = webSocketStage.getUrl();
// wss://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}
String callbackURL = webSocketStage.getCallbackUrl();
WebSocketStage webSocketStage;
var webSocketURL = webSocketStage.Url;
// wss://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}
var callbackURL = webSocketStage.CallbackUrl;
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:
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),
});
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)
)
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());
using Amazon.CDK.AwsApigatewayv2Integrations;
Function messageHandler;
var webSocketApi = new WebSocketApi(this, "mywsapi");
webSocketApi.AddRoute("sendmessage", new WebSocketRouteOptions {
Integration = new WebSocketLambdaIntegration("SendMessageIntegration", messageHandler)
});
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:
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,
});
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
)
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());
using Amazon.CDK.AwsApigatewayv2Integrations;
Function messageHandler;
var webSocketApi = new WebSocketApi(this, "mywsapi");
webSocketApi.AddRoute("sendmessage", new WebSocketRouteOptions {
Integration = new WebSocketLambdaIntegration("SendMessageIntegration", messageHandler),
ReturnResponse = true
});
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:
const webSocketApi = apigwv2.WebSocketApi.fromWebSocketApiAttributes(this, 'mywsapi', { webSocketId: 'api-1234' });
web_socket_api = apigwv2.WebSocketApi.from_web_socket_api_attributes(self, "mywsapi", web_socket_id="api-1234")
IWebSocketApi webSocketApi = WebSocketApi.fromWebSocketApiAttributes(this, "mywsapi", WebSocketApiAttributes.builder().webSocketId("api-1234").build());
var webSocketApi = WebSocketApi.FromWebSocketApiAttributes(this, "mywsapi", new WebSocketApiAttributes { WebSocketId = "api-1234" });
webSocketApi := apigwv2.WebSocketApi_FromWebSocketApiAttributes(this, jsii.String("mywsapi"), &WebSocketApiAttributes{
WebSocketId: jsii.String("api-1234"),
})
To generate an ARN for Execute API:
const api = new apigwv2.WebSocketApi(this, 'mywsapi');
const arn = api.arnForExecuteApiV2('$connect', 'dev');
api = apigwv2.WebSocketApi(self, "mywsapi")
arn = api.arn_for_execute_api_v2("$connect", "dev")
WebSocketApi api = new WebSocketApi(this, "mywsapi");
String arn = api.arnForExecuteApiV2("$connect", "dev");
var api = new WebSocketApi(this, "mywsapi");
var arn = api.ArnForExecuteApiV2("$connect", "dev");
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.
new apigwv2.WebSocketApi(this, 'api', {
disableSchemaValidation: true,
});
apigwv2.WebSocketApi(self, "api",
disable_schema_validation=True
)
WebSocketApi.Builder.create(this, "api")
.disableSchemaValidation(true)
.build();
new WebSocketApi(this, "api", new WebSocketApiProps {
DisableSchemaValidation = true
});
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.
new apigwv2.WebSocketApi(this, 'WebSocketApi', {
ipAddressType: apigwv2.IpAddressType.DUAL_STACK,
});
apigwv2.WebSocketApi(self, "WebSocketApi",
ip_address_type=apigwv2.IpAddressType.DUAL_STACK
)
WebSocketApi.Builder.create(this, "WebSocketApi")
.ipAddressType(IpAddressType.DUAL_STACK)
.build();
new WebSocketApi(this, "WebSocketApi", new WebSocketApiProps {
IpAddressType = IpAddressType.DUAL_STACK
});
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.
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);
# 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)
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);
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);
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:
const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi',{
apiKeySelectionExpression: apigwv2.WebSocketApiKeySelectionExpression.HEADER_X_API_KEY,
});
web_socket_api = apigwv2.WebSocketApi(self, "mywsapi",
api_key_selection_expression=apigwv2.WebSocketApiKeySelectionExpression.HEADER_X_API_KEY
)
WebSocketApi webSocketApi = WebSocketApi.Builder.create(this, "mywsapi")
.apiKeySelectionExpression(WebSocketApiKeySelectionExpression.HEADER_X_API_KEY)
.build();
var webSocketApi = new WebSocketApi(this, "mywsapi", new WebSocketApiProps {
ApiKeySelectionExpression = WebSocketApiKeySelectionExpression.HEADER_X_API_KEY
});
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:
const apiKey = new apigwv2.ApiKey(this, "ApiKey");
const usagePlan = new apigwv2.UsagePlan(this, "UsagePlan", {
usagePlanName: "WebSocketUsagePlan",
throttle: {
rateLimit: 10,
burstLimit: 2
}
});
usagePlan.addApiKey(apiKey);
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)
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);
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);
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:
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,
});
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
)
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());
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
});
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.
const usagePlan: apigwv2.IUsagePlan = apigwv2.UsagePlan.fromUsagePlanId(this, 'imported-usage-plan', '<usage-plan-id>');
usage_plan = apigwv2.UsagePlan.from_usage_plan_id(self, "imported-usage-plan", "<usage-plan-id>")
IUsagePlan usagePlan = UsagePlan.fromUsagePlanId(this, "imported-usage-plan", "<usage-plan-id>");
var usagePlan = UsagePlan.FromUsagePlanId(this, "imported-usage-plan", "<usage-plan-id>");
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.
// 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',
});
# 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"
)
// 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();
// 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"
});
// 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.
const importedKey = apigwv2.ApiKey.fromApiKeyId(this, 'imported-key', '<api-key-id>');
imported_key = apigwv2.ApiKey.from_api_key_id(self, "imported-key", "<api-key-id>")
IApiKey importedKey = ApiKey.fromApiKeyId(this, "imported-key", "<api-key-id>");
var importedKey = ApiKey.FromApiKeyId(this, "imported-key", "<api-key-id>");
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.
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);
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)
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);
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);
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.
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);
# 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)
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);
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);
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
declare const usagePlan: apigwv2.UsagePlan;
declare const apiKey: apigwv2.ApiKey;
usagePlan.addApiKey(apiKey, {
overrideLogicalId: 'MyCustomLogicalId',
});
# usage_plan: apigwv2.UsagePlan
# api_key: apigwv2.ApiKey
usage_plan.add_api_key(api_key,
override_logical_id="MyCustomLogicalId"
)
UsagePlan usagePlan;
ApiKey apiKey;
usagePlan.addApiKey(apiKey, AddApiKeyOptions.builder()
.overrideLogicalId("MyCustomLogicalId")
.build());
UsagePlan usagePlan;
ApiKey apiKey;
usagePlan.AddApiKey(apiKey, new AddApiKeyOptions {
OverrideLogicalId = "MyCustomLogicalId"
});
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 :
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
}
});
# 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
)
)
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();
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
}
});
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.
declare const api: apigwv2.HttpApi;
new apigwv2.HttpStage(this, 'Stage', {
httpApi: api,
throttle: {
rateLimit: 1000,
burstLimit: 1000,
},
detailedMetricsEnabled: true,
});
# api: apigwv2.HttpApi
apigwv2.HttpStage(self, "Stage",
http_api=api,
throttle=apigwv2.ThrottleSettings(
rate_limit=1000,
burst_limit=1000
),
detailed_metrics_enabled=True
)
HttpApi api;
HttpStage.Builder.create(this, "Stage")
.httpApi(api)
.throttle(ThrottleSettings.builder()
.rateLimit(1000)
.burstLimit(1000)
.build())
.detailedMetricsEnabled(true)
.build();
HttpApi api;
new HttpStage(this, "Stage", new HttpStageProps {
HttpApi = api,
Throttle = new ThrottleSettings {
RateLimit = 1000,
BurstLimit = 1000
},
DetailedMetricsEnabled = true
});
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
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),
},
});
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)
}
)
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();
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) }
}
});
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.
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(),
},
});
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()
}
)
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();
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() }
}
});
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.
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()}`
),
},
});
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()}""")
}
)
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();
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()}") }
}
});
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
| Name | Kind | Summary |
|---|---|---|
ApiKey | Construct (L2) | An API Gateway ApiKey. |
ApiMapping | Construct (L2) | Create a new API mapping for API Gateway API endpoint. |
DomainName | Construct (L2) | Custom domain resource for the API. |
HttpApi | Construct (L2) | Create a new API Gateway HTTP API endpoint. |
HttpAuthorizer | Construct (L2) | An authorizer for Http Apis. |
HttpIntegration | Construct (L2) | The integration for an API route. |
HttpRoute | Construct (L2) | Route class that creates the Route for API Gateway HTTP API. |
HttpStage | Construct (L2) | Represents a stage where an instance of the API is deployed. |
RateLimitedApiKey | Construct (L2) | An API Gateway ApiKey, for which a rate limiting configuration can be specified. |
UsagePlan | Construct (L2) | A UsagePlan. |
VpcLink | Construct (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). |
WebSocketApi | Construct (L2) | Create a new API Gateway WebSocket API endpoint. |
WebSocketAuthorizer | Construct (L2) | An authorizer for WebSocket Apis. |
WebSocketIntegration | Construct (L2) | The integration for an API route. |
WebSocketRoute | Construct (L2) | Route class that creates the Route for API Gateway WebSocket API. |
WebSocketStage | Construct (L2) | Represents a stage where an instance of the API is deployed. |
CfnApi | Construct (L1) | The AWS::ApiGatewayV2::Api resource creates an API. |
CfnApiGatewayManagedOverrides | Construct (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. |
CfnApiMapping | Construct (L1) | The AWS::ApiGatewayV2::ApiMapping resource contains an API mapping. |
CfnAuthorizer | Construct (L1) | The AWS::ApiGatewayV2::Authorizer resource creates an authorizer for a WebSocket API or an HTTP API. |
CfnDeployment | Construct (L1) | The AWS::ApiGatewayV2::Deployment resource creates a deployment for an API. |
CfnDomainName | Construct (L1) | The AWS::ApiGatewayV2::DomainName resource specifies a custom domain name for your API in Amazon API Gateway (API Gateway). |
CfnIntegration | Construct (L1) | The AWS::ApiGatewayV2::Integration resource creates an integration for an API. |
CfnIntegrationResponse | Construct (L1) | The AWS::ApiGatewayV2::IntegrationResponse resource updates an integration response for an WebSocket API. |
CfnModel | Construct (L1) | The AWS::ApiGatewayV2::Model resource updates data model for a WebSocket API. |
CfnPortalProduct | Construct (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. |
CfnRoute | Construct (L1) | The AWS::ApiGatewayV2::Route resource creates a route for an API. |
CfnRouteResponse | Construct (L1) | The AWS::ApiGatewayV2::RouteResponse resource creates a route response for a WebSocket API. |
CfnRoutingRule | Construct (L1) | Represents a routing rule. |
CfnStage | Construct (L1) | The AWS::ApiGatewayV2::Stage resource specifies a stage for an API. |
CfnVpcLink | Construct (L1) | The AWS::ApiGatewayV2::VpcLink resource creates a VPC link. |
AccessLogDestinationConfig | Struct | Options when binding a log destination to a HttpApi Stage. |
AddApiKeyOptions | Struct | Options to the UsagePlan.addApiKey() method. |
AddRoutesOptions | Struct | Options for the Route with Integration resource. |
ApiKeyOptions | Struct | The options for creating an API Key. |
ApiKeyProps | Struct | ApiKey Properties. |
ApiMappingAttributes | Struct | The attributes used to import existing ApiMapping. |
ApiMappingProps | Struct | Properties used to create the ApiMapping resource. |
AuthorizerPayloadVersion | Enum | Payload format version for lambda authorizers. |
BatchHttpRouteOptions | Struct | Options used when configuring multiple routes, at once. |
CfnApi.BodyS3LocationProperty | Struct | The BodyS3Location property specifies an S3 location from which to import an OpenAPI definition. |
CfnApi.CorsProperty | Struct | The Cors property specifies a CORS configuration for an API. |
CfnApiGatewayManagedOverrides.AccessLogSettingsProperty | Struct | The AccessLogSettings property overrides the access log settings for an API Gateway-managed stage. |
CfnApiGatewayManagedOverrides.IntegrationOverridesProperty | Struct | The IntegrationOverrides property overrides the integration settings for an API Gateway-managed integration. |
CfnApiGatewayManagedOverrides.RouteOverridesProperty | Struct | The RouteOverrides property overrides the route configuration for an API Gateway-managed route. |
CfnApiGatewayManagedOverrides.RouteSettingsProperty | Struct | The RouteSettings property overrides the route settings for an API Gateway-managed route. |
CfnApiGatewayManagedOverrides.StageOverridesProperty | Struct | The StageOverrides property overrides the stage configuration for an API Gateway-managed stage. |
CfnApiGatewayManagedOverridesProps | Struct | Properties for defining a CfnApiGatewayManagedOverrides. |
CfnApiMappingProps | Struct | Properties for defining a CfnApiMapping. |
CfnApiProps | Struct | Properties for defining a CfnApi. |
CfnAuthorizer.JWTConfigurationProperty | Struct | The JWTConfiguration property specifies the configuration of a JWT authorizer. |
CfnAuthorizerProps | Struct | Properties for defining a CfnAuthorizer. |
CfnDeploymentProps | Struct | Properties for defining a CfnDeployment. |
CfnDomainName.DomainNameConfigurationProperty | Struct | The DomainNameConfiguration property type specifies the configuration for an API's domain name. |
CfnDomainName.MutualTlsAuthenticationProperty | Struct | If specified, API Gateway performs two-way authentication between the client and the server. |
CfnDomainNameProps | Struct | Properties for defining a CfnDomainName. |
CfnIntegration.ResponseParameterListProperty | Struct | |
CfnIntegration.ResponseParameterMapProperty | Struct | map of response parameter lists. |
CfnIntegration.ResponseParameterProperty | Struct | Supported only for HTTP APIs. |
CfnIntegration.TlsConfigProperty | Struct | The TlsConfig property specifies the TLS configuration for a private integration. |
CfnIntegrationProps | Struct | Properties for defining a CfnIntegration. |
CfnIntegrationResponseProps | Struct | Properties for defining a CfnIntegrationResponse. |
CfnModelProps | Struct | Properties for defining a CfnModel. |
CfnPortalProductProps | Struct | Properties for defining a CfnPortalProduct. |
CfnRoute.ParameterConstraintsProperty | Struct | |
CfnRouteProps | Struct | Properties for defining a CfnRoute. |
CfnRouteResponse.ParameterConstraintsProperty | Struct | Specifies whether the parameter is required. |
CfnRouteResponseProps | Struct | Properties for defining a CfnRouteResponse. |
CfnRoutingRule.ActionInvokeApiProperty | Struct | Represents an InvokeApi action. |
CfnRoutingRule.ActionProperty | Struct | Represents a routing rule action. |
CfnRoutingRule.ConditionProperty | Struct | Represents a condition. |
CfnRoutingRule.MatchBasePathsProperty | Struct | Represents a MatchBasePaths condition. |
CfnRoutingRule.MatchHeadersProperty | Struct | Represents a MatchHeaders condition. |
CfnRoutingRule.MatchHeaderValueProperty | Struct | Represents a MatchHeaderValue . |
CfnRoutingRuleProps | Struct | Properties for defining a CfnRoutingRule. |
CfnStage.AccessLogSettingsProperty | Struct | Settings for logging access in a stage. |
CfnStage.RouteSettingsProperty | Struct | Represents a collection of route settings. |
CfnStageProps | Struct | Properties for defining a CfnStage. |
CfnVpcLinkProps | Struct | Properties for defining a CfnVpcLink. |
ContentHandling | Enum | Integration content handling. |
CorsHttpMethod | Enum | Supported CORS HTTP methods. |
CorsPreflightOptions | Struct | Options for the CORS Configuration. |
DomainMappingOptions | Struct | Options for DomainMapping. |
DomainNameAttributes | Struct | custom domain name attributes. |
DomainNameProps | Struct | properties used for creating the DomainName. |
EndpointOptions | Struct | properties for creating a domain name endpoint. |
EndpointType | Enum | Endpoint type for a domain name. |
GrantInvokeOptions | Struct | Options for granting invoke access. |
HttpApiAttributes | Struct | Attributes for importing an HttpApi into the CDK. |
HttpApiHelper | Facade | Calculations and operations for HTTP APIs. |
HttpApiProps | Struct | Properties to initialize an instance of HttpApi. |
HttpAuthorizerAttributes | Struct | Reference to an http authorizer. |
HttpAuthorizerProps | Struct | Properties to initialize an instance of HttpAuthorizer. |
HttpAuthorizerType | Enum | Supported Authorizer types. |
HttpConnectionType | Enum | Supported connection types. |
HttpIntegrationProps | Struct | The integration properties. |
HttpIntegrationSubtype | Enum | Supported integration subtypes. |
HttpIntegrationType | Enum | Supported integration types. |
HttpMethod | Enum | Supported HTTP methods. |
HttpNoneAuthorizer | Class | Explicitly configure no authorizers on specific HTTP API routes. |
HttpRouteAuthorizerBindOptions | Struct | Input to the bind() operation, that binds an authorizer to a route. |
HttpRouteAuthorizerConfig | Struct | Results of binding an authorizer to an http route. |
HttpRouteIntegration | Class | The interface that various route integration classes will inherit. |
HttpRouteIntegrationBindOptions | Struct | Options to the HttpRouteIntegration during its bind operation. |
HttpRouteIntegrationConfig | Struct | Config returned back as a result of the bind. |
HttpRouteKey | Class | HTTP route in APIGateway is a combination of the HTTP method and the path component. |
HttpRouteProps | Struct | Properties to initialize a new Route. |
HttpStageAttributes | Struct | The attributes used to import existing HttpStage. |
HttpStageOptions | Struct | The options to create a new Stage for an HTTP API. |
HttpStageProps | Struct | Properties to initialize an instance of HttpStage. |
IAccessLogDestination | Interface | Access log destination for a HttpApi Stage. |
IAccessLogSettings | Interface | Settings for access logging. |
IApi | Interface | Represents a API Gateway HTTP/WebSocket API. |
IApiKey | Interface | API keys are alphanumeric string values that you distribute to app developer customers to grant access to your API. |
IApiMapping | Interface | Represents an ApiGatewayV2 ApiMapping resource. |
IAuthorizer | Interface | Represents an Authorizer. |
IDomainName | Interface | Represents an APIGatewayV2 DomainName. |
IHttpApi | Interface | Represents an HTTP API. |
IHttpApiRef | Interface | Represents a reference to an HTTP API. |
IHttpAuthorizer | Interface | An authorizer for HTTP APIs. |
IHttpIntegration | Interface | Represents an Integration for an HTTP API. |
IHttpRoute | Interface | Represents a Route for an HTTP API. |
IHttpRouteAuthorizer | Interface | An authorizer that can attach to an Http Route. |
IHttpStage | Interface | Represents the HttpStage. |
IHttpStageRef | Interface | Represents a reference to an HTTP Stage. |
IIntegration | Interface | Represents an integration to an API Route. |
IMappingValue | Interface | Represents a Mapping Value. |
IntegrationCredentials | Class | Credentials used for AWS Service integrations. |
IpAddressType | Enum | Supported IP Address Types. |
IRoute | Interface | Represents a route. |
IStage | Interface | Represents a Stage. |
IUsagePlan | Interface | A UsagePlan, either managed by this CDK app, or imported. |
IVpcLink | Interface | Represents an API Gateway VpcLink. |
IWebSocketApi | Interface | Represents a WebSocket API. |
IWebSocketApiRef | Interface | Represents a reference to an HTTP API. |
IWebSocketAuthorizer | Interface | An authorizer for WebSocket APIs. |
IWebSocketIntegration | Interface | Represents an Integration for an WebSocket API. |
IWebSocketRoute | Interface | Represents a Route for an WebSocket API. |
IWebSocketRouteAuthorizer | Interface | An authorizer that can attach to an WebSocket Route. |
IWebSocketStage | Interface | Represents the WebSocketStage. |
LogGroupLogDestination | Class | Use CloudWatch Logs as a custom access log destination for API Gateway. |
MappingValue | Class | Represents a Mapping Value. |
MTLSConfig | Struct | The mTLS authentication configuration for a custom domain name. |
ParameterMapping | Class | Represents a Parameter Mapping. |
PassthroughBehavior | Enum | Integration Passthrough Behavior. |
PayloadFormatVersion | Class | Payload format version for lambda proxy integration. |
Period | Enum | Time period for which quota settings apply. |
QuotaSettings | Struct | Specifies the maximum number of requests that clients can make to API Gateway APIs. |
RateLimitedApiKeyProps | Struct | RateLimitedApiKey properties. |
SecurityPolicy | Enum | The minimum version of the SSL protocol that you want API Gateway to use for HTTPS connections. |
StageAttributes | Struct | The attributes used to import existing Stage. |
StageOptions | Struct | Options required to create a new stage. |
ThrottleSettings | Struct | Container for defining throttling parameters to API stages. |
UsagePlanPerApiStage | Struct | Represents the API stages that a usage plan applies to. |
UsagePlanProps | Struct | Properties for defining an API Gateway Usage Plan for WebSocket APIs. |
VpcLinkAttributes | Struct | Attributes when importing a new VpcLink. |
VpcLinkProps | Struct | Properties for a VpcLink. |
WebSocketApiAttributes | Struct | Attributes for importing a WebSocketApi into the CDK. |
WebSocketApiKeySelectionExpression | Class | Represents the currently available API Key Selection Expressions. |
WebSocketApiProps | Struct | Props for WebSocket API. |
WebSocketAuthorizerAttributes | Struct | Reference to an WebSocket authorizer. |
WebSocketAuthorizerProps | Struct | Properties to initialize an instance of WebSocketAuthorizer. |
WebSocketAuthorizerType | Enum | Supported Authorizer types. |
WebSocketIntegrationProps | Struct | The integration properties. |
WebSocketIntegrationType | Enum | WebSocket Integration Types. |
WebSocketNoneAuthorizer | Class | Explicitly configure no authorizers on specific WebSocket API routes. |
WebSocketRouteAuthorizerBindOptions | Struct | Input to the bind() operation, that binds an authorizer to a route. |
WebSocketRouteAuthorizerConfig | Struct | Results of binding an authorizer to an WebSocket route. |
WebSocketRouteIntegration | Class | The interface that various route integration classes will inherit. |
WebSocketRouteIntegrationBindOptions | Struct | Options to the WebSocketRouteIntegration during its bind operation. |
WebSocketRouteIntegrationConfig | Struct | Config returned back as a result of the bind. |
WebSocketRouteOptions | Struct | Options used to add route to the API. |
WebSocketRouteProps | Struct | Properties to initialize a new Route. |
WebSocketStageAttributes | Struct | The attributes used to import existing WebSocketStage. |
WebSocketStageProps | Struct | Properties to initialize an instance of WebSocketStage. |