

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

建立 Amazon API Gateway HTTP API，這可讓您建立比 REST API 更低延遲和成本的 RESTful APIs。 APIs 如需詳細資訊，請參閱[APIs開發人員指南》中的使用 HTTP](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html) *API*。

我們建議您使用 CloudFormation 勾點或 IAM 政策來驗證 API Gateway 資源是否已連接授權方，以控制對它們的存取。

如需使用 CloudFormation 勾點的詳細資訊，請參閱 *CloudFormation CLI 使用者指南*中的[註冊勾點](https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/registering-hook-python.html)和 [apigw-enforce-authorizer](https://github.com/aws-cloudformation/aws-cloudformation-samples/tree/main/hooks/python-hooks/apigw-enforce-authorizer/) GitHub 儲存庫。

如需使用 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 開發人員指南*》中的[使用 JWT 授權方控制對 HTTP API 的存取](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 APIs 的跨來源資源共用 (CORS)。指定要允許做為字串的網域，或指定`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 定義。如果您未指定 `DefinitionUri`或 `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。對應`AWS::Serverless::Function`資源`EventSource`的屬性包括 `Auth`和 HttpApi 類型的 。

 `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 定義匯入範本，請使用 `DefinitionBody` 屬性搭配[包含轉換](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/create-reusable-transform-function-snippets-and-add-to-your-template-with-aws-include-transform.html)。  
*類型*：字串 \$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` 屬性是在開啟 API 定義中以 `description` 欄位集指定 – 這會導致 AWS SAM 無法解析`description`的欄位衝突。
+ 屬性`DefinitionUri`已指定 – AWS SAM 不會修改從 Amazon S3 擷取的 Open API 定義。
*類型：*字串  
*必要*：否  
*CloudFormation 相容性*：此屬性對 是唯一的 AWS SAM ，並且沒有 CloudFormation 同等屬性。

 `DisableExecuteApiEndpoint`   <a name="sam-httpapi-disableexecuteapiendpoint"></a>
指定用戶端是否可以使用預設`execute-api`端點 叫用 HTTP API`https://{api_id}.execute-api.{region}.amazonaws.com`。根據預設，用戶端可以使用預設 端點叫用您的 API。若要要求用戶端僅使用自訂網域名稱來叫用 API，請停用預設端點。  
若要使用此屬性，您必須指定 `DefinitionBody` 屬性而非 `DefinitionUri` 屬性，或在 OpenAPI 定義`x-amazon-apigateway-endpoint-configuration``disableExecuteApiEndpoint`中使用 定義。  
*類型*：布林值  
*必要*：否  
*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>
指定在遇到警告時是否要轉返 HTTP API 建立 (`true`) 與否 (`false`)。預設值為 `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 將透過設定 `title` 欄位來修改 HTTP API 資源的 OpenAPI 定義。下列案例將導致錯誤：  
+ `DefinitionBody` 屬性是在開啟 API 定義中以 `title` 欄位集指定 – 這會導致 AWS SAM 無法解析`title`的欄位衝突。
+ 屬性`DefinitionUri`已指定 – AWS SAM 不會修改從 Amazon S3 擷取的 Open 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 每個路由的路由設定。如需詳細資訊，請參閱[APIs》中的使用 HTTP API 的路由](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&=，】＋。  
*類型*：[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
```

### 具有 Auth 的 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"
```

### 具有 OpenAPI 定義的 HttpApi
<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
```