Skip to content
v2.274.0

WebSocketApi L2 construct ​

Create a new API Gateway WebSocket API endpoint.

Example ​

ts
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),
});
python
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)
)
java
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());
csharp
// 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)
});
go
// 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 ​

ts
new WebSocketApi(scope: Construct, id: string, props?: WebSocketApiProps)
python
WebSocketApi(scope: Construct, id: str, props: typing.Optional[WebSocketApiProps] = None)
java
new WebSocketApi(Construct scope, String id, WebSocketApiProps props)
csharp
new WebSocketApi(Construct scope, string id, WebSocketApiProps? props = null)
go
NewWebSocketApi(Scope Construct, Id *string, Props WebSocketApiProps)

Construct Props ​

apiKeySelectionExpressionWebSocketApiKeySelectionExpressionapi_key_selection_expressionWebSocketApiKeySelectionExpressionapiKeySelectionExpressionWebSocketApiKeySelectionExpressionApiKeySelectionExpressionWebSocketApiKeySelectionExpressionApiKeySelectionExpressionWebSocketApiKeySelectionExpression#
An API key selection expression.

Default: Key is not required to access these APIs

Providing this option will require an API Key be provided to access the API.

apiNamestringapi_namestrapiNameStringApiNamestringApiName*string#
Name for the WebSocket API resource.

Default: id of the WebSocketApi construct.

connectRouteOptionsWebSocketRouteOptionsconnect_route_optionsWebSocketRouteOptionsconnectRouteOptionsWebSocketRouteOptionsConnectRouteOptionsWebSocketRouteOptionsConnectRouteOptionsWebSocketRouteOptions#
Options to configure a '$connect' route.

Default: no '$connect' route configured

defaultRouteOptionsWebSocketRouteOptionsdefault_route_optionsWebSocketRouteOptionsdefaultRouteOptionsWebSocketRouteOptionsDefaultRouteOptionsWebSocketRouteOptionsDefaultRouteOptionsWebSocketRouteOptions#
Options to configure a '$default' route.

Default: no '$default' route configured

descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*string= none#
The description of the API.
disableSchemaValidationbooleandisable_schema_validationbooldisableSchemaValidationBooleanDisableSchemaValidationboolDisableSchemaValidation*bool= false#
Avoid validating models when creating a deployment.
disconnectRouteOptionsWebSocketRouteOptionsdisconnect_route_optionsWebSocketRouteOptionsdisconnectRouteOptionsWebSocketRouteOptionsDisconnectRouteOptionsWebSocketRouteOptionsDisconnectRouteOptionsWebSocketRouteOptions#
Options to configure a '$disconnect' route.

Default: no '$disconnect' route configured

ipAddressTypeIpAddressTypeip_address_typeIpAddressTypeipAddressTypeIpAddressTypeIpAddressTypeIpAddressTypeIpAddressTypeIpAddressType#
The IP address types that can invoke the API.

Default: undefined - AWS default is IPV4

routeSelectionExpressionstringroute_selection_expressionstrrouteSelectionExpressionStringRouteSelectionExpressionstringRouteSelectionExpression*string= '$request.body.action'#
The route selection expression for the API.

Properties ​

apiEndpointstringapi_endpointstrapiEndpointStringApiEndpointstringApiEndpoint*stringrequired#
The default endpoint for an API.
apiIdstringapi_idstrapiIdStringApiIdstringApiId*stringrequired#
The identifier of this API Gateway API.
A reference to a Api resource.
The environment this resource belongs to.
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#
Indicates that this is a WebSocket API.

Will always return true, but is necessary to prevent accidental structural equality in TypeScript.

nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
webSocketApiNamestringweb_socket_api_namestrwebSocketApiNameStringWebSocketApiNamestringWebSocketApiName*string#
A human friendly name for this WebSocket API.

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#
Add a new route.
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)#
Override the cross-stack reference strength for this resource.
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)#
Apply the given removal policy to this resource.
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#
Use `arnForExecuteApiV2()` instead.
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#
Get the "execute-api" ARN.
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#
Import an existing WebSocket API into this CDK app.
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#
Grant access to the API Gateway management API for this WebSocket API to an IAM principal (Role/Group/User).

[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#
Checks if `x` is a construct.
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#
Returns true if the construct was created by CDK, and false otherwise.
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#
Check whether the given construct is a Resource.
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#
Return the given named metric for this Api Gateway.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

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.