

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

# AWS::Serverless::HttpApi
<a name="sam-resource-httpapi"></a>

创建 Amazon API Gateway HTTP API，这使您能够以比 REST 更低的延迟和更低的成本 RESTful APIs 进行创作 APIs。有关更多信息，请参阅《*API Gateway 开发者指南》APIs中的 “使用* [HTTP](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-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-httpapi-syntax"></a>

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

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

```
Type: AWS::Serverless::HttpApi
Properties:
  [AccessLogSettings](#sam-httpapi-accesslogsettings): [AccessLogSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-accesslogsettings)
  [Auth](#sam-httpapi-auth): HttpApiAuth
  [CorsConfiguration](#sam-httpapi-corsconfiguration): String | HttpApiCorsConfiguration
  [DefaultRouteSettings](#sam-httpapi-defaultroutesettings): [RouteSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-routesettings)
  [DefinitionBody](#sam-httpapi-definitionbody): JSON
  [DefinitionUri](#sam-httpapi-definitionuri): String | HttpApiDefinition
  [Description](#sam-httpapi-description): String
  [DisableExecuteApiEndpoint](#sam-httpapi-disableexecuteapiendpoint): Boolean
  [Domain](#sam-httpapi-domain): HttpApiDomainConfiguration
  [FailOnWarnings](#sam-httpapi-failonwarnings): Boolean
  Name: String
  PropagateTags: Boolean
  [RouteSettings](#sam-httpapi-routesettings): [RouteSettings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-routesettings)
  [StageName](#sam-httpapi-stagename): String
  [StageVariables](#sam-httpapi-stagevariables): [Json](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-stagevariables)
  [Tags](#sam-httpapi-tags): Map
```

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

 `AccessLogSettings`   <a name="sam-httpapi-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-httpapi-auth"></a>
配置授权，以控制对 API Gateway HTTP API 的访问。  
有关更多信息，请参阅《*API Gateway 开发*者指南》中的 “[ APIs 使用 JWT 授权者控制 HTTP 访问权限](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html)”。  
*类型*：[HttpApiAuth](sam-property-httpapi-httpapiauth.md)  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `CorsConfiguration`   <a name="sam-httpapi-corsconfiguration"></a>
管理所有 API Gateway HTTP 的跨源资源共享 (CORS)。 APIs以字符串形式指定要允许的域，或者指定一个 `HttpApiCorsConfiguration` 对象。请注意，CORS AWS SAM 需要修改你的 OpenAPI 定义，因此 CORS 只有在指定`DefinitionBody`了该属性时才起作用。  
有关更多信息，请参阅*《API Gateway 开发人员指南》*中的[为 HTTP API 配置 CORS](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html)。  
如果`CorsConfiguration`在 OpenAPI 定义和属性级别都进行了设置，则会将两个配置源 AWS SAM 合并，且属性优先。如果将此属性设置为 `true`，则允许所有来源。
*类型*：字符串 \$1 [HttpApiCorsConfiguration](sam-property-httpapi-httpapicorsconfiguration.md)  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

 `DefaultRouteSettings`   <a name="sam-httpapi-defaultroutesettings"></a>
此 HTTP API 的默认路由设置。这些设置适用于所有路由，除非被某些路由的 `RouteSettings` 属性覆盖。  
*类型*：[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)`属性。

 `DefinitionBody`   <a name="sam-httpapi-definitionbody"></a>
描述您的 HTTP API 的 OpenAPI 定义。如果您未指定 a `DefinitionUri` 或 a`DefinitionBody`，则会根据您的模板配置`DefinitionBody`为您 AWS SAM 生成。  
*类型*：JSON  
*必需*：否  
*CloudFormation 兼容性*：此属性类似于`AWS::ApiGatewayV2::Api`资源的`[Body](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html#cfn-apigatewayv2-api-body)`属性。如果提供了某些属性，则 AWS SAM 可以在将内容传递给`DefinitionBody`之前将其插入或修改 CloudFormation。属性包括相应`EventSource` HttpApi `AWS::Serverless::Function`资源的类型`Auth`和类型。

 `DefinitionUri`   <a name="sam-httpapi-definitionuri"></a>
定义 HTTP API 的 OpenAPI 定义的 Amazon Simple Storage Service (Amazon S3) URI、本地文件路径或位置对象。此属性引用的 Amazon S3 对象必须是有效的 OpenAPI 定义文件。如果您未指定`DefinitionUri`或`DefinitionBody`已指定，则会根据您的模板配置`DefinitionBody`为您 AWS SAM 生成。  
如果您提供本地文件路径，则模板必须经过包含 `sam deploy` 或 `sam package` 命令的工作流程，才能使定义正确转换。  
您引用的外部 OpenApi 定义文件不支持内部函数。`DefinitionUri`要将 OpenApi 定义导入到模板中，请使用带[有 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`属性。  
*类型*：字符串 \$1 [HttpApiDefinition](sam-property-httpapi-httpapidefinition.md)  
*必需*：否  
*CloudFormation 兼容性*：此属性类似于`AWS::ApiGatewayV2::Api`资源的`[BodyS3Location](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html#cfn-apigatewayv2-api-bodys3location)`属性。嵌套的 Amazon S3 属性的命名有所不同。

 `Description`   <a name="sam-httpapi-description"></a>
HTTP API 资源的描述。  
当您指定时`Description`， AWS SAM 将通过设置`description`字段来修改 HTTP API 资源的OpenApi 定义。以下情况将导致错误：  
+ 该`DefinitionBody`属性是使用 Open API 定义中设置的`description`字段指定的，这会导致 AWS SAM 无法解决的`description`字段冲突。
+ 该`DefinitionUri`属性已指定 — AWS SAM 不会修改从 Amazon S3 检索到的开放 API 定义。
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

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

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

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

`Name`  <a name="sam-httpapi-name"></a>
HTTP API 资源的名称。  
当您指定时`Name`， AWS SAM 将通过设置该字段来修改 HTTP API 资源的 OpenAPI 定义。`title`以下情况将导致错误：  
+ 该`DefinitionBody`属性是使用 Open API 定义中设置的`title`字段指定的，这会导致 AWS SAM 无法解决的`title`字段冲突。
+ 该`DefinitionUri`属性已指定 — AWS SAM 不会修改从 Amazon S3 检索到的开放 API 定义。
*类型*：字符串  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。

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

 `RouteSettings`   <a name="sam-httpapi-routesettings"></a>
此 HTTP API 的每个路由的路由设置。有关更多信息，请参阅 *API Gateway 开发者指南 APIs中的使用* [HTTP 路由](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html)。  
*类型*：[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-httpapi-stagename"></a>
API 阶段的名称。如果未指定名称，则 AWS SAM 使用 API Gateway 中的`$default`阶段。  
*类型*：字符串  
*必需*：否  
*默认值*：\$1default  
*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-httpapi-stagevariables"></a>
一个定义阶段变量的映射。变量名可以包含字母数字和下划线字符。这些值必须匹配 [A-Za-z0-9-.\$1\$1:/?\$1&=,]\$1。  
*类型*：[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-httpapi-tags"></a>
指定要添加到此 API Gateway 阶段的标签的映射（字符串到字符串）。密钥的长度可以在 1 到 128 个 Unicode 字符之间，并且不能包含前缀 `aws:`。您可以使用以下任一字符：Unicode 字母、数字、空格、`_`、`.`、`/`、`=`、`+` 和 `-` 的组合。值的长度可以在 1 到 256 个 Unicode 字符之间。  
*类型*：映射  
*必需*：否  
*CloudFormation 兼容性*：此属性是独有的 AWS SAM ，没有 CloudFormation 等效属性。  
*其他说明*：该`Tags`属性 AWS SAM 需要修改您的 OpenAPI 定义，因此只有在指定了该`DefinitionBody`属性时才会添加标签，如果指定了该属性，则不会添加任何标签。`DefinitionUri` AWS SAM 自动添加`httpapi:createdBy:SAM`标签。标签还会添加到 `AWS::ApiGatewayV2::Stage` 资源和 `AWS::ApiGatewayV2::DomainName` 资源（如果已指定 `DomainName`）。

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

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

在将此资源的逻辑 ID 传递给内置 `Ref` 函数时，`Ref` 会返回底层 `AWS::ApiGatewayV2::Api` 资源的 API ID，例如 `a1bcdef2gh`。

有关使用 `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)。

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

### 简单 HttpApi
<a name="sam-resource-httpapi--examples--simple-httpapi"></a>

以下示例显示了设置由 Lambda 函数支持的 HTTP API 端点所需的最低要求。此示例使用 AWS SAM 创建的默认 HTTP API。

#### YAML
<a name="sam-resource-httpapi--examples--simple-httpapi--yaml"></a>

```
AWSTemplateFormatVersion: '2010-09-09'
Description: AWS SAM template with a simple API definition
Resources:
  ApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      Events:
        ApiEvent:
          Type: HttpApi
      Handler: index.handler
      InlineCode: |
        def handler(event, context):
            return {'body': 'Hello World!', 'statusCode': 200}
      Runtime: python3.7
Transform: AWS::Serverless-2016-10-31
```

### HttpApi 使用身份验证
<a name="sam-resource-httpapi--examples--httpapi-with-auth"></a>

以下示例说明如何在 HTTP API 端点上设置授权。

#### YAML
<a name="sam-resource-httpapi--examples--httpapi-with-auth--yaml"></a>

```
Properties:
  FailOnWarnings: true
  Auth:
    DefaultAuthorizer: OAuth2
    Authorizers:
      OAuth2:
        AuthorizationScopes:
          - scope4
        JwtConfiguration:
          issuer: "https://www.example.com/v1/connect/oauth2"
          audience:
            - MyApi
        IdentitySource: "$request.querystring.param"
```

### HttpApi 使用 OpenAPI 定义
<a name="sam-resource-httpapi--examples--httpapi-with-openapi-definition"></a>

以下示例说明如何将 OpenAPI 定义添加到模板。

请注意，对于引用此 HTTP API HttpApi 的事件，请 AWS SAM 填写所有缺失的 Lambda 集成。 AWS SAM 还会添加 HttpApi 事件引用的任何缺失路径。

#### YAML
<a name="sam-resource-httpapi--examples--httpapi-with-openapi-definition--yaml"></a>

```
Properties:
  FailOnWarnings: true
  DefinitionBody:
    info:
      version: '1.0'
      title:
        Ref: AWS::StackName
    paths:
      "/":
        get:
          security:
          - OpenIdAuth:
            - scope1
            - scope2
          responses: {}
    openapi: 3.0.1
    securitySchemes:
      OpenIdAuth:
        type: openIdConnect
        x-amazon-apigateway-authorizer:
          identitySource: "$request.querystring.param"
          type: jwt
          jwtConfiguration:
            audience:
            - MyApi
            issuer: https://www.example.com/v1/connect/oidc
          openIdConnectUrl: https://www.example.com/v1/connect/oidc/.well-known/openid-configuration
```

### HttpApi 使用配置设置
<a name="sam-resource-httpapi--examples--httpapi-with-configuration-settings"></a>

以下示例说明如何将 HTTP API 和阶段配置添加到模板。

#### YAML
<a name="sam-resource-httpapi--examples--httpapi-with-configuration-settings--yaml"></a>

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
  StageName:
    Type: String
    Default: Prod
    
Resources:
  HttpApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      InlineCode: |
          def handler(event, context):
              import json
              return {
                  "statusCode": 200,
                  "body": json.dumps(event),
              }
      Handler: index.handler
      Runtime: python3.7
      Events:
        ExplicitApi: # warning: creates a public endpoint
          Type: HttpApi
          Properties:
            ApiId: !Ref HttpApi
            Method: GET
            Path: /path
            TimeoutInMillis: 15000
            PayloadFormatVersion: "2.0"
            RouteSettings:
              ThrottlingBurstLimit: 600

  HttpApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      StageName: !Ref StageName
      Tags:
        Tag: Value
      AccessLogSettings:
        DestinationArn: !GetAtt AccessLogs.Arn
        Format: $context.requestId
      DefaultRouteSettings:
        ThrottlingBurstLimit: 200
      RouteSettings:
        "GET /path":
          ThrottlingBurstLimit: 500 # overridden in HttpApi Event
      StageVariables:
        StageVar: Value
      FailOnWarnings: true

  AccessLogs:
    Type: AWS::Logs::LogGroup

Outputs:
  HttpApiUrl:
    Description: URL of your API endpoint
    Value:
      Fn::Sub: 'https://${HttpApi}.execute-api.${AWS::Region}.${AWS::URLSuffix}/${StageName}/'
  HttpApiId:
    Description: Api id of HttpApi
    Value:
      Ref: HttpApi
```