WebSocketApi L2 construct
Create a new API Gateway WebSocket API endpoint.
Example
import { WebSocketLambdaIntegration } from 'aws-cdk-lib/aws-apigatewayv2-integrations';
const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi');
new apigwv2.WebSocketStage(this, 'mystage', {
webSocketApi,
stageName: 'dev',
autoDeploy: true,
});
declare const messageHandler: lambda.Function;
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")
apigwv2.WebSocketStage(self, "mystage",
web_socket_api=web_socket_api,
stage_name="dev",
auto_deploy=True
)
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");
WebSocketStage.Builder.create(this, "mystage")
.webSocketApi(webSocketApi)
.stageName("dev")
.autoDeploy(true)
.build();
webSocketApi.addRoute("sendMessage", WebSocketRouteOptions.builder()
.integration(new WebSocketLambdaIntegration("SendMessageIntegration", messageHandler))
.build());
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AwsApigatewayv2Integrations;
Function messageHandler;
var webSocketApi = new WebSocketApi(this, "mywsapi");
new WebSocketStage(this, "mystage", new WebSocketStageProps {
WebSocketApi = webSocketApi,
StageName = "dev",
AutoDeploy = true
});
webSocketApi.AddRoute("sendMessage", new WebSocketRouteOptions {
Integration = new WebSocketLambdaIntegration("SendMessageIntegration", messageHandler)
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import "github.com/aws/aws-cdk-go/awscdk"
var messageHandler Function
webSocketApi := apigwv2.NewWebSocketApi(this, jsii.String("mywsapi"))
apigwv2.NewWebSocketStage(this, jsii.String("mystage"), &WebSocketStageProps{
WebSocketApi: WebSocketApi,
StageName: jsii.String("dev"),
AutoDeploy: jsii.Boolean(true),
})
webSocketApi.AddRoute(jsii.String("sendMessage"), &WebSocketRouteOptions{
Integration: awscdk.NewWebSocketLambdaIntegration(jsii.String("SendMessageIntegration"), messageHandler),
})
Initializer
new WebSocketApi(scope: Construct, id: string, props?: WebSocketApiProps)
WebSocketApi(scope: Construct, id: str, props: typing.Optional[WebSocketApiProps] = None)
new WebSocketApi(Construct scope, String id, WebSocketApiProps props)
new WebSocketApi(Construct scope, string id, WebSocketApiProps? props = null)
NewWebSocketApi(Scope Construct, Id *string, Props WebSocketApiProps)
Construct Props
apiKeySelectionExpressionWebSocketApiKeySelectionExpressionapi_key_selection_expressionWebSocketApiKeySelectionExpressionapiKeySelectionExpressionWebSocketApiKeySelectionExpressionApiKeySelectionExpressionWebSocketApiKeySelectionExpressionApiKeySelectionExpressionWebSocketApiKeySelectionExpression#Default: Key is not required to access these APIs
Providing this option will require an API Key be provided to access the API.
Default: id of the WebSocketApi construct.
connectRouteOptionsWebSocketRouteOptionsconnect_route_optionsWebSocketRouteOptionsconnectRouteOptionsWebSocketRouteOptionsConnectRouteOptionsWebSocketRouteOptionsConnectRouteOptionsWebSocketRouteOptions#Default: no '$connect' route configured
defaultRouteOptionsWebSocketRouteOptionsdefault_route_optionsWebSocketRouteOptionsdefaultRouteOptionsWebSocketRouteOptionsDefaultRouteOptionsWebSocketRouteOptionsDefaultRouteOptionsWebSocketRouteOptions#Default: no '$default' route configured
disableSchemaValidationbooleandisable_schema_validationbooldisableSchemaValidationBooleanDisableSchemaValidationboolDisableSchemaValidation*bool= false#disconnectRouteOptionsWebSocketRouteOptionsdisconnect_route_optionsWebSocketRouteOptionsdisconnectRouteOptionsWebSocketRouteOptionsDisconnectRouteOptionsWebSocketRouteOptionsDisconnectRouteOptionsWebSocketRouteOptions#Default: no '$disconnect' route configured
ipAddressTypeIpAddressTypeip_address_typeIpAddressTypeipAddressTypeIpAddressTypeIpAddressTypeIpAddressTypeIpAddressTypeIpAddressType#Default: undefined - AWS default is IPV4
routeSelectionExpressionstringroute_selection_expressionstrrouteSelectionExpressionStringRouteSelectionExpressionstringRouteSelectionExpression*string= '$request.body.action'#Properties
apiRefApiReferenceapi_refApiReferenceapiRefApiReferenceApiRefApiReferenceApiRefApiReferencerequired#envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironmentrequired#notes
For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.
For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.
isWebsocketApibooleanis_websocket_apiboolisWebsocketApiBooleanIsWebsocketApiboolIsWebsocketApi*boolrequired#Will always return true, but is necessary to prevent accidental structural equality in TypeScript.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#webSocketApiNamestringweb_socket_api_namestrwebSocketApiNameStringWebSocketApiNamestringWebSocketApiName*string#Note that this is different from webSocketApiId.
Methods
addRoute(routeKey: string, options: WebSocketRouteOptions): WebSocketRoutedef add_route(self, route_key: str, options: WebSocketRouteOptions) -> WebSocketRoutepublic WebSocketRoute addRoute(String routeKey, WebSocketRouteOptions options)public WebSocketRoute AddRoute(string routeKey, WebSocketRouteOptions options)func AddRoute(RouteKey *string, Options WebSocketRouteOptions) WebSocketRoute#applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#notes · 1 parameter
When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.
Parameters
strengthstrengthstrengthstrengthStrength— - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#notes
The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.
The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).
arnForExecuteApi(method?: string, path?: string, stage?: string): stringdef arn_for_execute_api(self, method: typing.Optional[str] = None, path: typing.Optional[str] = None, stage: typing.Optional[str] = None) -> strpublic String arnForExecuteApi(String method, String path, String stage)public string ArnForExecuteApi(string? method = null, string? path = null, string? stage = null)func ArnForExecuteApi(Method *string, Path *string, Stage *string) *stringdeprecated#arnForExecuteApiV2(route?: string, stage?: string): stringdef arn_for_execute_api_v2(self, route: typing.Optional[str] = None, stage: typing.Optional[str] = None) -> strpublic String arnForExecuteApiV2(String route, String stage)public string ArnForExecuteApiV2(string? route = null, string? stage = null)func ArnForExecuteApiV2(Route *string, Stage *string) *string#fromWebSocketApiAttributes(scope: Construct, id: string, attrs: WebSocketApiAttributes): IWebSocketApi@staticmethod def from_web_socket_api_attributes(scope: Construct, id: str, attrs: WebSocketApiAttributes) -> IWebSocketApipublic static IWebSocketApi fromWebSocketApiAttributes(Construct scope, String id, WebSocketApiAttributes attrs)public static IWebSocketApi FromWebSocketApiAttributes(Construct scope, string id, WebSocketApiAttributes attrs)func FromWebSocketApiAttributes(Scope Construct, Id *string, Attrs WebSocketApiAttributes) IWebSocketApistatic#grantManageConnections(identity: IGrantable): Grantdef grant_manage_connections(self, identity: IGrantable) -> Grantpublic Grant grantManageConnections(IGrantable identity)public Grant GrantManageConnections(IGrantable identity)func GrantManageConnections(Identity IGrantable) Grant#[disable-awslint:no-grants]
1 parameter
Parameters
identityidentityidentityidentityIdentity— The principal.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#notes · 1 parameter · returns
Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.
Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.
Parameters
xxxxX— Any object.
Returns: true if x is an object created from a class which extends Construct.
isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#metric(metricName: string, props?: MetricOptions): Metricdef metric(self, metric_name: str, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric(String metricName, MetricOptions props)public Metric Metric(string metricName, MetricOptions? props = null)func Metric(MetricName *string, Props MetricOptions) Metric#toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.