

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

# AWS::Serverless::Api
<a name="sam-resource-api"></a>

创建一组可通过 HTTPS 端点调用的 Amazon API Gateway 资源和方法。

无需将[AWS::Serverless::Api](#sam-resource-api)资源明确添加到 AWS 无服务器应用程序定义模板中。这种类型的资源是通过 [AWS::Serverless::Function](sam-resource-function.md) 资源上定义的 Api 事件的并集隐式创建的，这些资源定义于未引用 [AWS::Serverless::Api](#sam-resource-api) 资源的模板。

应使用[AWS::Serverless::Api](#sam-resource-api)资源来定义和记录 API OpenApi，这样可以更好地配置底层 Amazon API Gateway 资源。

我们建议您使用 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-api-syntax"></a>

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

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

```
Type: AWS::Serverless::Api
Properties:
  [AccessLogSetting](#sam-api-accesslogsetting): [AccessLogSetting](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-accesslogsetting)
  AlwaysDeploy: Boolean
  [ApiKeySourceType](#sam-api-apikeysourcetype): String
  [Auth](#sam-api-auth): ApiAuth
  [BinaryMediaTypes](#sam-api-binarymediatypes): List
  [CacheClusterEnabled](#sam-api-cacheclusterenabled): Boolean
  [CacheClusterSize](#sam-api-cacheclustersize): String
  [CanarySetting](#sam-api-canarysetting): [CanarySetting](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-canarysetting)
  [Cors](#sam-api-cors): String | CorsConfiguration
  [DefinitionBody](#sam-api-definitionbody): JSON
  [DefinitionUri](#sam-api-definitionuri): String | ApiDefinition
  [Description](#sam-api-description): String
  [DisableExecuteApiEndpoint](#sam-api-disableexecuteapiendpoint): Boolean
  [Domain](#sam-api-domain): DomainConfiguration
  [EndpointConfiguration](#sam-api-endpointconfiguration): EndpointConfiguration
  [FailOnWarnings](#sam-api-failonwarnings): Boolean
  [GatewayResponses](#sam-api-gatewayresponses): Map
  MergeDefinitions: Boolean
  [MethodSettings](#sam-api-methodsettings): MethodSettings
  [MinimumCompressionSize](#sam-api-minimumcompressionsize): Integer
  [Mode](#sam-api-mode): String
  [Models](#sam-api-models): Map
  [Name](#sam-api-name): String
  [OpenApiVersion](#sam-api-openapiversion): String
  PropagateTags: Boolean
  [Policy](#sam-api-policy): JSON
  [StageName](#sam-api-stagename): String
  [Tags](#sam-api-tags): Map
  [TracingEnabled](#sam-api-tracingenabled): Boolean
  [Variables](#sam-api-variables): Map
```

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

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

 `AlwaysDeploy`   <a name="sam-api-alwaysdeploy"></a>
即使未检测到 API 的更改，也要始终部署 API。  
*类型*：布尔值  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `ApiKeySourceType`   <a name="sam-api-apikeysourcetype"></a>
用于根据使用计划对请求进行计量的 API 键的源。有效值为 `HEADER` 和 `AUTHORIZER`。  
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::RestApi`资源的`[ApiKeySourceType](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-apikeysourcetype)`属性。

 `Auth`   <a name="sam-api-auth"></a>
配置授权，以控制对 API Gateway API 的访问。  
有关使用配置访问权限的更多信息， AWS SAM 请参阅[使用您的 AWS SAM 模板控制 API 访问权限](serverless-controlling-access-to-apis.md)。有关如何覆盖全局授权方的示例，请参阅 [覆盖 Amazon API Gateway REST API 的全局授权方](sam-property-function-apifunctionauth.md#sam-property-function-apifunctionauth--examples--override)。  
*类型*：[ApiAuth](sam-property-api-apiauth.md)  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `BinaryMediaTypes`   <a name="sam-api-binarymediatypes"></a>
您的 API 可能返回的 MIME 类型列表。使用它来启用对的二进制支持APIs。  
*类型*：列表  
*必需*：否  
*CloudFormation 兼容性*：此属性类似于`AWS::ApiGateway::RestApi`资源的`[BinaryMediaTypes](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-binarymediatypes)`属性。的列表 BinaryMediaTypes 已添加到 CloudFormation 资源和 OpenAPI 文档中。

 `CacheClusterEnabled`   <a name="sam-api-cacheclusterenabled"></a>
指示是否为阶段启用缓存。要缓存响应，还必须在 `MethodSettings` 下将 `CachingEnabled` 设置为 `true`。  
*类型*：布尔值  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::Stage`资源的`[CacheClusterEnabled](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-cacheclusterenabled)`属性。

 `CacheClusterSize`   <a name="sam-api-cacheclustersize"></a>
阶段的缓存群集大小。  
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::Stage`资源的`[CacheClusterSize](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-cacheclustersize)`属性。

 `CanarySetting`   <a name="sam-api-canarysetting"></a>
将金丝雀设置配置为常规部署的某个阶段。  
*类型*：[CanarySetting](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-canarysetting)  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::Stage`资源的`[CanarySetting](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-canarysetting)`属性。

 `Cors`   <a name="sam-api-cors"></a>
管理所有 API Gateway 的跨源资源共享 (CORS)。 APIs使用字符串指定允许使用的域，或使用其他 Cors 配置指定词典。  
CORS AWS SAM 需要修改你的 OpenAPI 定义。在 `DefinitionBody` 中创建内联 OpenAPI 定义以开启 CORS。
有关 CORS 的更多信息，请参阅*《API Gateway 开发人员指南》*中的[为 API Gateway REST API 资源启用 CORS](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html)。  
*类型*：字符串 \$1 [CorsConfiguration](sam-property-api-corsconfiguration.md)  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `DefinitionBody`   <a name="sam-api-definitionbody"></a>
描述您的 API 的 OpenAPI 规范。如果 `DefinitionUri` 和 `DefinitionBody` 均未指定，SAM 将根据模板配置为您生成 `DefinitionBody`。  
要引用定义 API 的本地 OpenAPI 文件，请使用 `AWS::Include` 转换。要了解更多信息，请参阅[如何 AWS SAM 上传本地文件](deploy-upload-local-files.md)。  
*类型*：JSON  
*必需*：否  
*CloudFormation 兼容性*：此属性类似于`AWS::ApiGateway::RestApi`资源的`[Body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body)`属性。如果提供了某些属性，则可以在将内容传递给DefinitionBody 之前在中插入或修改内容 CloudFormation。属性包括 `Auth`、`BinaryMediaTypes`、`Cors`、`GatewayResponses`、`Models`、和 `AWS::Serverless::Function` 相应 Api 类型的 `EventSource`。

 `DefinitionUri`   <a name="sam-api-definitionuri"></a>
Amazon S3 Uri、本地文件路径或定义 API 的 OpenAPI 文档的位置对象。此属性引用的 Amazon S3 对象必须是有效的 OpenAPI 文件。如果 `DefinitionUri` 和 `DefinitionBody` 均未指定，SAM 将根据模板配置为您生成 `DefinitionBody`。  
如果提供了本地文件路径，则模板必须经过包含 `sam deploy` 或 `sam package` 命令的工作流程，才能使定义正确转换。  
引用的外部 OpenApi 文件不支持内部函数。`DefinitionUri`改用带[有 Include 转换](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/create-reusable-transform-function-snippets-and-add-to-your-template-with-aws-include-transform.html)的`DefinitionBody`属性将 OpenApi 定义导入到模板中。  
*类型*：字符串 \$1 [ApiDefinition](sam-property-api-apidefinition.md)  
*必需*：否  
*CloudFormation 兼容性*：此属性类似于`AWS::ApiGateway::RestApi`资源的`[BodyS3Location](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-bodys3location)`属性。嵌套的 Amazon S3 属性的命名有所不同。

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

 `DisableExecuteApiEndpoint`   <a name="sam-api-disableexecuteapiendpoint"></a>
指定客户端是否可以使用默认 `execute-api` 端点调用您的 API。默认情况下，客户端可以使用默认 `https://{api_id}.execute-api.{region}.amazonaws.com` 调用您的 API。如果要求客户端使用自定义域名来调用 API，请指定 `True`。  
*类型*：布尔值  
*必需*：否  
*CloudFormation 兼容性*：此属性类似于`AWS::ApiGateway::RestApi`资源的`[ DisableExecuteApiEndpoint](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-disableexecuteapiendpoint)`属性。它直接传递给 `[ x-amazon-apigateway-endpoint-configuration](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-endpoint-configuration.html)` 扩展的 `disableExecuteApiEndpoint` 属性，然后添加到 `AWS::ApiGateway::RestApi` 资源的 ` [ Body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body)` 属性中。

 `Domain`   <a name="sam-api-domain"></a>
为此 API Gateway API 配置自定义域。  
*类型*：[DomainConfiguration](sam-property-api-domainconfiguration.md)  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `EndpointConfiguration`   <a name="sam-api-endpointconfiguration"></a>
REST API 的端点类型。  
*类型*：[EndpointConfiguration](sam-property-api-endpointconfiguration.md)  
*必需*：否  
*CloudFormation 兼容性*：此属性类似于`AWS::ApiGateway::RestApi`资源的`[EndpointConfiguration](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-endpointconfiguration)`属性。嵌套配置属性的命名有所不同。

 `FailOnWarnings`   <a name="sam-api-failonwarnings"></a>
指定在遇到警告时是回滚 (`true`) 还是不回滚 (`false`) API 创建。默认值为 `false`。  
*类型*：布尔值  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::RestApi`资源的`[FailOnWarnings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-failonwarnings)`属性。

 `GatewayResponses`   <a name="sam-api-gatewayresponses"></a>
为 API 配置网关响应。网关响应是 API Gateway 直接返回或使用 Lambda 授权方返回的响应。有关更多信息，请参阅[网关响应的 Api Gateway OpenApi 扩展](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-gateway-responses.html)文档。  
*类型*：映射  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `MergeDefinitions`   <a name="sam-api-mergedefinitions"></a>
AWS SAM 从您的 API 事件源生成OpenAPI规范。指定`true`将其 AWS SAM 合并到`AWS::Serverless::Api`资源中定义的内联OpenAPI规范中。指定 `false` 以不合并。  
`MergeDefinitions` 需要定义 `AWS::Serverless::Api` 的 `DefinitionBody` 属性。`MergeDefinitions` 与 `AWS::Serverless::Api` 的 `DefinitionUri` 属性不兼容。  
*默认值*：`false`  
*类型*：布尔值  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `MethodSettings`   <a name="sam-api-methodsettings"></a>
配置 API 阶段的所有设置，包括日志、指标、CacheTTL、节流。  
*类型*：[ MethodSetting](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-stage-methodsetting.html) 列表  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::Stage`资源的`[MethodSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-methodsettings)`属性。

 `MinimumCompressionSize`   <a name="sam-api-minimumcompressionsize"></a>
允许根据客户端的 Accept-Encoding 标头压缩响应正文。当响应正文大小大于或等于您配置的阈值时，就会触发压缩。最大正文大小阈值为 10 MB（10,485,760 字节）。- 支持以下压缩类型：gzip、deflate 和身份。  
*类型*：整数  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::RestApi`资源的`[MinimumCompressionSize](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-minimumcompressionsize)`属性。

 `Mode`   <a name="sam-api-mode"></a>
此属性仅在您使用 OpenAPI 定义 REST API 时才适用。`Mode` 确定 API Gateway 如何处理资源更新。有关更多信息，请参阅 [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html) 资源类型的[模式](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-mode)属性。  
*有效值*：`overwrite` 或 `merge`  
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::RestApi`资源的`[Mode](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-mode)`属性。

 `Models`   <a name="sam-api-models"></a>
您的 API 方法要使用的架构。可以使用 JSON 或 YAML 描述这些架构。有关示例模型，请参阅本页底部的“示例”部分。  
*类型*：映射  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `Name`   <a name="sam-api-name"></a>
API Gateway RestApi 资源的名称  
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::RestApi`资源的`[Name](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-name)`属性。

 `OpenApiVersion`   <a name="sam-api-openapiversion"></a>
 OpenApi 要使用的版本。这可以是 `2.0` Swagger 规范，也可以是 OpenApi 3.0 版本之一，比如。`3.0.1`有关 OpenAPI 的更多信息，请参阅 [OpenAPI 规范](https://swagger.io/specification/)。  
 AWS SAM 创建一个默认情况下名为`Stage`的阶段。将此属性设置为任何有效值将阻止阶段 `Stage` 的创建。
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

`PropagateTags`  <a name="sam-api-propagatetags"></a>
指明是否将 `Tags` 属性中的标签传递给 [AWS::Serverless::Api](sam-specification-generated-resources-api.md) 生成的资源。指定 `True` 以在生成的资源中传播标签。  
*类型*：布尔值  
*必需*：否  
*默认值*：`False`  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

`Policy`  <a name="sam-api-policy"></a>
一个策略文档，其中包含 API 的权限。要设置策略的 ARN，请使用 `!Join` 内部函数（`""` 作为分隔符）以及值 `"execute-api:/"` 和 `"*"`。  
*类型*：JSON  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::RestApi`资源的 P [ol](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-policy) icy 属性。

 `StageName`   <a name="sam-api-stagename"></a>
阶段的名称，API Gateway 将它用作调用的统一资源标识符 (URI) 中的第一个路径部分。  
要引用阶段资源，请使用 `<api-logical-id>.Stage`。有关指定 [AWS::Serverless::Api](#sam-resource-api) 资源时引用生成资源的更多信息，请参阅 [CloudFormation 指定时AWS::Serverless::Api生成的资源](sam-specification-generated-resources-api.md)。有关生成的 CloudFormation 资源的一般信息，请参阅[生成的 CloudFormation 资源用于 AWS SAM](sam-specification-generated-resources.md)。  
*类型*：字符串  
*是否必需*：是  
*CloudFormation 兼容性*：此属性类似于`AWS::ApiGateway::Stage`资源的`[StageName](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-stagename)`属性。它在 SAM 中为必需，但在 API Gateway 中并非必需  
*附加说明*：隐式 API 的阶段名称为 “Prod”。

 `Tags`   <a name="sam-api-tags"></a>
指定要添加到此 API Gateway 阶段的标签的映射（字符串到字符串）。有关标签的有效键和值的详细信息，请参阅*《AWS CloudFormation 用户指南》*中的[资源标签](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)。  
*类型*：映射  
*必需*：否  
*CloudFormation 兼容性*：此属性类似于`AWS::ApiGateway::Stage`资源的`[Tags](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-tags)`属性。SAM 中的 Tags 属性由 Key: Value CloudFormation 对组成；其中包含标签对象的列表。

 `TracingEnabled`   <a name="sam-api-tracingenabled"></a>
指示是否为阶段启用通过 X-Ray 进行的主动跟踪。有关 X-Ray 的更多信息，请参阅 *API Gateway 开发者指南中的 APIs 使用 X-Ray* [跟踪用户向 REST 发出的请求](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-xray.html)。  
*类型*：布尔值  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::Stage`资源的`[TracingEnabled](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-tracingenabled)`属性。

 `Variables`   <a name="sam-api-variables"></a>
一个定义阶段变量的映射 (字符串到字符串)，其中变量名作为键，变量值作为值。变量名称只能包含字母数字字符。值必须匹配以下正则表达式：`[A-Za-z0-9._~:/?#&=,-]+`。  
*类型*：映射  
*必需*：否  
*CloudFormation 兼容性*：此属性直接传递给`AWS::ApiGateway::Stage`资源的`[Variables](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-variables)`属性。

## 返回值
<a name="sam-resource-api-return-values"></a>

### Ref
<a name="sam-resource-api-return-values-ref"></a>

当向 `Ref` 内置函数提供此资源的逻辑 ID 时，它将返回底层 API Gateway API 的 ID。

有关使用 `Ref` 函数的更多信息，请参阅*《AWS CloudFormation 用户指南》*中的 [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html)。

### Fn:: GetAtt
<a name="sam-resource-api-return-values-fn--getatt"></a>

`Fn::GetAtt` 返回一个此类型指定属性的值。以下为可用属性和示例返回值。

有关使用 `Fn::GetAtt` 的更多信息，请参阅*《AWS CloudFormation 用户指南》*中的 [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html)。

`RootResourceId`  <a name="RootResourceId-fn::getatt"></a>
`RestApi` 资源的根资源 ID，例如 `a0bc123d4e`。

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

### SimpleApiExample
<a name="sam-resource-api--examples--simpleapiexample"></a>

一个 Hello World AWS SAM 模板文件，其中包含带有 API 端点的 Lambda 函数。这是正在运行的无服务器应用程序的完整 AWS SAM 模板文件。

#### YAML
<a name="sam-resource-api--examples--simpleapiexample--yaml"></a>

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS SAM template with a simple API definition
Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
  ApiFunction: # Adds a GET method at the root resource via an Api event
    Type: AWS::Serverless::Function
    Properties:
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /
            Method: get
            RestApiId:
              Ref: ApiGatewayApi
      Runtime: python3.10
      Handler: index.handler
      InlineCode: |
        def handler(event, context):
            return {'body': 'Hello World!', 'statusCode': 200}
```

### ApiCorsExample
<a name="sam-resource-api--examples--apicorsexample"></a>

一个 AWS SAM 模板片段，其中包含在外部 Swagger 文件中定义的 API 以及 Lambda 集成和 CORS 配置。这只是显示[AWS::Serverless::Api](#sam-resource-api)定义的 AWS SAM 模板文件的一部分。

#### YAML
<a name="sam-resource-api--examples--apicorsexample--yaml"></a>

```
Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      # Allows www.example.com to call these APIs
      # SAM will automatically add AllowMethods with a list of methods for this API
      Cors: "'www.example.com'"
      DefinitionBody: # Pull in an OpenApi definition from S3
        'Fn::Transform':
          Name: 'AWS::Include'
          # Replace "bucket" with your bucket name
          Parameters:
            Location: s3://bucket/swagger.yaml
```

### ApiCognitoAuthExample
<a name="sam-resource-api--examples--apicognitoauthexample"></a>

包含使用 Amazon Cognito 授权针对该 API 的请求的 API 的 AWS SAM 模板片段。这只是显示[AWS::Serverless::Api](#sam-resource-api)定义的 AWS SAM 模板文件的一部分。

#### YAML
<a name="sam-resource-api--examples--apicognitoauthexample--yaml"></a>

```
Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Cors: "'*'"
      Auth:
        DefaultAuthorizer: MyCognitoAuthorizer
        Authorizers:
          MyCognitoAuthorizer:
            UserPoolArn:
              Fn::GetAtt: [MyCognitoUserPool, Arn]
```

### ApiModelsExample
<a name="sam-resource-api--examples--apimodelsexample"></a>

带有包含模型架构的 API 的 AWS SAM 模板片段。这只是 AWS SAM 模板文件的一部分，显示了一个包含两个模型架构的[AWS::Serverless::Api](#sam-resource-api)定义。

#### YAML
<a name="sam-resource-api--examples--apimodelsexample--yaml"></a>

```
Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Models:
        User:
          type: object
          required:
            - username
            - employee_id
          properties:
            username:
              type: string
            employee_id:
              type: integer
            department:
              type: string
        Item:
          type: object
          properties:
            count:
              type: integer
            category:
              type: string
            price:
              type: integer
```

### 缓存示例
<a name="sam-resource-api--examples--caching-example"></a>

一个 Hello World AWS SAM 模板文件，其中包含带有 API 端点的 Lambda 函数。API 已为一种资源和方法启用缓存。有关缓存的更多信息，请参阅的*《API Gateway 开发人员指南》*中的[启用 API 缓存以增强响应能力](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-caching.html)。

#### YAML
<a name="sam-resource-api--examples--caching-example--yaml"></a>

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS SAM template with a simple API definition with caching turned on
Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      CacheClusterEnabled: true
      CacheClusterSize: '0.5'
      MethodSettings:
        - ResourcePath: /
          HttpMethod: GET
          CachingEnabled: true
          CacheTtlInSeconds: 300
      Tags:
        CacheMethods: All 

  ApiFunction: # Adds a GET method at the root resource via an Api event
    Type: AWS::Serverless::Function
    Properties:
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /
            Method: get
            RestApiId:
              Ref: ApiGatewayApi
      Runtime: python3.10
      Handler: index.handler
      InlineCode: |
        def handler(event, context):
            return {'body': 'Hello World!', 'statusCode': 200}
```

### 带私有 API 的自定义域示例
<a name="sam-resource-api--examples--custom-domain-example"></a>

一个 Hello World AWS SAM 模板文件，其中包含一个 Lambda 函数，该函数的 API 终端节点映射到私有域。该模板在 VPC 端点与私有域之间创建域访问关联。有关更多信息，请参阅 [API Gateway APIs 中的私有自定义域名](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-custom-domains.html)。

#### YAML
<a name="sam-resource-api--examples--custom-domain-example--yaml"></a>

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS SAM template configured with a custom domain using a private API

Parameters:
    DomainName:
      Type: String
      Default: mydomain.example.com
    CertificateArn:
      Type: String
    HostedZoneId:
      Type: String
    VpcEndpointId:
      Type: String
    VpcEndpointDomainName:
      Type: String
    VpcEndpointHostedZoneId:
      Type: String

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      InlineCode: |
        def handler(event, context):
            return {'body': 'Hello World!', 'statusCode': 200}
      Handler: index.handler
      Runtime: python3.13
      Events:
        Fetch:
          Type: Api
          Properties:
            RestApiId:
              Ref: MyApi
            Method: Get
            Path: /get
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      EndpointConfiguration:
        Type: PRIVATE
        VPCEndpointIds:
        - !Ref VpcEndpointId
      Policy:
        Version: '2012-10-17		 	 	 '
        Statement:
        - Effect: Allow
          Principal: '*'
          Action: execute-api:Invoke
          Resource: execute-api:/*
        - Effect: Deny
          Principal: '*'
          Action: execute-api:Invoke
          Resource: execute-api:/*
          Condition:
            StringNotEquals:
              aws:SourceVpce: !Ref VpcEndpointId
      Domain:
        DomainName: !Ref DomainName
        CertificateArn: !Ref CertificateArn
        EndpointConfiguration: PRIVATE
        BasePath:
        - /
        Route53:
          HostedZoneId: !Ref HostedZoneId
          VpcEndpointDomainName: !Ref VpcEndpointDomainName
          VpcEndpointHostedZoneId: !Ref VpcEndpointHostedZoneId
        AccessAssociation:
          VpcEndpointId: !Ref VpcEndpointId
        Policy:
          Version: '2012-10-17		 	 	 '
          Statement:
          - Effect: Allow
            Principal: '*'
            Action: execute-api:Invoke
            Resource: execute-api:/*
          - Effect: Deny
            Principal: '*'
            Action: execute-api:Invoke
            Resource: execute-api:/*
            Condition:
              StringNotEquals:
                aws:SourceVpce: !Ref VpcEndpointId
```