

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# AWS::Serverless::WebSocketApi
<a name="sam-resource-websocketapi"></a>

创建 Amazon API Gateway WebSocket API，使您能够创建双向交互式通信应用程序。 WebSocket APIs 允许服务器向客户端发送消息，而无需客户端请求消息。有关更多信息，请参阅 *API Gateway 开发者指南 WebSocket APIs*中的[使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api.html)。

我们建议您使用 CloudFormation 挂钩或 IAM 策略来验证 API Gateway 资源是否附加了授权者来控制对它们的访问。

有关使用 CloudFormation 挂钩的更多信息，请参阅 *CloudFormation CLI 用户指南*和[apigw-enforce-authorizer](https://github.com/aws-cloudformation/aws-cloudformation-samples/tree/main/hooks/python-hooks/apigw-enforce-authorizer/) GitHub 存储库中的[注册挂钩](https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/registering-hook-python.html)。

有关使用 IAM 策略的更多信息，请参阅*《API Gateway 开发人员指南》*中的[要求 API 路由具有授权](https://docs.aws.amazon.com/apigateway/latest/developerguide/security_iam_id-based-policy-examples.html#security_iam_id-based-policy-examples-require-authorization)。

**注意**  
部署到时 AWS CloudFormation， AWS SAM 会将您的 AWS SAM 资源转换为 CloudFormation 资源。有关更多信息，请参阅 [生成的 CloudFormation 资源用于 AWS SAM](sam-specification-generated-resources.md)。

## 语法
<a name="sam-resource-websocketapi-syntax"></a>

要在 AWS Serverless Application Model (AWS SAM) 模板中声明此实体，请使用以下语法。

### YAML
<a name="sam-resource-websocketapi-syntax.yaml"></a>

```
Type: AWS::Serverless::WebSocketApi
Properties:
  [ApiKeySelectionExpression](#sam-websocketapi-apikeyselectionexpression): {{String}}
  [AccessLogSettings](#sam-websocketapi-accesslogsettings): {{[AccessLogSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-accesslogsettings)}}
  [Auth](#sam-websocketapi-auth): {{WebSocketApiAuth}}
  [DefaultRouteSettings](#sam-websocketapi-defaultroutesettings): {{[RouteSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-routesettings)}}
  [Description](#sam-websocketapi-description): {{String}}
  [DisableExecuteApiEndpoint](#sam-websocketapi-disableexecuteapiendpoint): {{Boolean}}
  [DisableSchemaValidation](#sam-websocketapi-disableschemavalidation): {{Boolean}}
  [Domain](#sam-websocketapi-domain): {{WebSocketApiDomainConfiguration}}
  [IpAddressType](#sam-websocketapi-ipaddresstype): {{String}}
  [Name](#sam-websocketapi-name): {{String}}
  [PropagateTags](#sam-websocketapi-propagatetags): {{Boolean}}
  [Routes](#sam-websocketapi-routes): {{RouteConfiguration}}
  [RouteSelectionExpression](#sam-websocketapi-routeselectionexpression): {{String}}
  [RouteSettings](#sam-websocketapi-routesettings): {{[RouteSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-routesettings)}}
  [StageName](#sam-websocketapi-stagename): {{String}}
  [StageVariables](#sam-websocketapi-stagevariables): {{[Json](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-stagevariables)}}
  [Tags](#sam-websocketapi-tags): {{Map}}
```

## Properties
<a name="sam-resource-websocketapi-properties"></a>

 `ApiKeySelectionExpression`   <a name="sam-websocketapi-apikeyselectionexpression"></a>
一个 API 键选择表达式。有关更多信息，请参阅 [API Gate *way 开发者指南中的 API* 密钥选择表达式](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions)。  
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Api`资源的`[ApiKeySelectionExpression](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html#cfn-apigatewayv2-api-apikeyselectionexpression)`属性。

 `AccessLogSettings`   <a name="sam-websocketapi-accesslogsettings"></a>
某个阶段的访问日志记录的设置。  
*类型*：[AccessLogSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-accesslogsettings)  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Stage`资源的`[AccessLogSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-accesslogsettings)`属性。

 `Auth`   <a name="sam-websocketapi-auth"></a>
配置授权，以控制对您的 WebSocket API 的访问权限。授权已应用于`$connect`路径。  
有关更多信息，请参阅《*API Gateway 开发者指南*》 WebSocket APIs中的[控制访问权限](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-control-access.html)。  
*类型*：[WebSocketApiAuth](sam-property-websocketapi-websocketapiauth.md)  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `DefaultRouteSettings`   <a name="sam-websocketapi-defaultroutesettings"></a>
此 WebSocket API 的默认路由设置。这些设置适用于所有路由，除非被某些路由的 `RouteSettings` 属性覆盖。  
*类型*：[RouteSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-routesettings)  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Stage`资源的`[DefaultRouteSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-defaultroutesettings)`属性。

 `Description`   <a name="sam-websocketapi-description"></a>
对 WebSocket API 的描述。  
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Api`资源的`[Description](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html#cfn-apigatewayv2-api-description)`属性。

 `DisableExecuteApiEndpoint`   <a name="sam-websocketapi-disableexecuteapiendpoint"></a>
指定客户端是否可以使用默认 `execute-api` 端点调用您的 API。如果要求客户端使用自定义域名调用 API，请禁用默认端点。  
*类型*：布尔值  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Api`资源的`[DisableExecuteApiEndpoint](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html#cfn-apigatewayv2-api-disableexecuteapiendpoint)`属性。

 `DisableSchemaValidation`   <a name="sam-websocketapi-disableschemavalidation"></a>
在创建部署时避免验证模型。  
*类型*：布尔值  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Api`资源的`[DisableSchemaValidation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html#cfn-apigatewayv2-api-disableschemavalidation)`属性。

 `Domain`   <a name="sam-websocketapi-domain"></a>
为此 WebSocket API 配置自定义网域。  
WebSocket APIs 不支持双向 TLS 身份验证 (MTLS)。如果指定`MutualTlsAuthentication`或`OwnershipVerificationCertificateArn`， AWS SAM 将返回错误。
*类型*：[WebSocketApiDomainConfiguration](sam-property-websocketapi-websocketapidomainconfiguration.md)  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `IpAddressType`   <a name="sam-websocketapi-ipaddresstype"></a>
API 的 IP 地址类型。有效值 IPv4 仅`ipv4``dualstack`适用于 IPv4 和 IPv6。  
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Api`资源的`[IpAddressType](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html#cfn-apigatewayv2-api-ipaddresstype)`属性。

 `Name`   <a name="sam-websocketapi-name"></a>
 WebSocket API 的名称。如果您未指定名称，则会为您 AWS SAM 生成一个名称。  
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Api`资源的`[Name](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html#cfn-apigatewayv2-api-name)`属性。

 `PropagateTags`   <a name="sam-websocketapi-propagatetags"></a>
如果`true`，则 AWS SAM 将该`Tags`属性添加到 AWS SAM 生成的`AWS::ApiGatewayV2::Stage`和`AWS::ApiGatewayV2::DomainName`资源中。  
*类型*：布尔值  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `Routes`   <a name="sam-websocketapi-routes"></a>
此 WebSocket API 的路由配置。路由定义如何将消息路由到 Lambda 函数。每条路由都由一个路由密钥和一个 Lambda 函数 ARN 组成。  
WebSocket APIs 支持三种预定义路由：`$connect``$disconnect`、和`$default`。您也可以定义自定义路由。  
*类型*：[RouteConfiguration](sam-property-websocketapi-routeconfiguration.md)  
*是否必需*：是  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `RouteSelectionExpression`   <a name="sam-websocketapi-routeselectionexpression"></a>
 WebSocket API 的路径选择表达式。有关更多信息，请参阅 *API Gateway 开发者指南*中的[路由选择表达式](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-route-selection-expressions)。  
一个常见的值是`$request.body.action`，它根据消息正文中的`action`字段路由消息。  
*类型*：字符串  
*是否必需*：是  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Api`资源的`[RouteSelectionExpression](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html#cfn-apigatewayv2-api-routeselectionexpression)`属性。

 `RouteSettings`   <a name="sam-websocketapi-routesettings"></a>
此 WebSocket API 的路由设置。这些设置会覆盖`DefaultRouteSettings`特定路径的。  
*类型*：[RouteSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-routesettings)  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Stage`资源的`[RouteSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-routesettings)`属性。

 `StageName`   <a name="sam-websocketapi-stagename"></a>
API 阶段的名称。如果未指定名称，则 AWS SAM 使用`default`作为舞台名称。  
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Stage`资源的`[StageName](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-stagename)`属性。

 `StageVariables`   <a name="sam-websocketapi-stagevariables"></a>
一个定义阶段变量的映射。变量名可以包含字母数字和下划线字符，并且值必须匹配`[A-Za-z0-9-._~:/?#&=,]+`。  
*类型*：[Json](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-stagevariables)  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGatewayV2::Stage`资源的`[StageVariables](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-stagevariables)`属性。

 `Tags`   <a name="sam-websocketapi-tags"></a>
用于指定要添加到此 WebSocket API 的标签的映射（字符串到字符串）。有关标签的有效键和值的详细信息，请参阅*《CloudFormation 用户指南》*中的[资源标签](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)。  
*类型*：映射  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

## 示例
<a name="sam-resource-websocketapi-examples"></a>

### 简单的 WebSocket API
<a name="sam-resource-websocketapi-examples-simple"></a>

以下示例创建了一个包含三条路由 WebSocket 的 API。

```
Resources:
  MyWebSocketApi:
    Type: AWS::Serverless::WebSocketApi
    Properties:
      RouteSelectionExpression: $request.body.action
      Routes:
        $connect:
          FunctionArn: !GetAtt ConnectFunction.Arn
        $disconnect:
          FunctionArn: !GetAtt DisconnectFunction.Arn
        sendMessage:
          FunctionArn: !GetAtt SendMessageFunction.Arn

  ConnectFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.connect
      Runtime: nodejs20.x
      CodeUri: ./src

  DisconnectFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.disconnect
      Runtime: nodejs20.x
      CodeUri: ./src

  SendMessageFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.sendMessage
      Runtime: nodejs20.x
      CodeUri: ./src
```

### WebSocket 带有 Lambda 授权器的 API
<a name="sam-resource-websocketapi-examples-auth"></a>

以下示例创建了一个带有 Lambda 授权方 WebSocket 的 API。

```
Resources:
  MyWebSocketApi:
    Type: AWS::Serverless::WebSocketApi
    Properties:
      RouteSelectionExpression: $request.body.action
      Auth:
        AuthType: CUSTOM
        AuthArn: !GetAtt AuthorizerFunction.Arn
        IdentitySource:
          - route.request.header.Authorization
      Routes:
        $connect:
          FunctionArn: !GetAtt ConnectFunction.Arn
        sendMessage:
          FunctionArn: !GetAtt SendMessageFunction.Arn

  AuthorizerFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.authorize
      Runtime: nodejs20.x
      CodeUri: ./src

  ConnectFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.connect
      Runtime: nodejs20.x
      CodeUri: ./src

  SendMessageFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.sendMessage
      Runtime: nodejs20.x
      CodeUri: ./src
```