

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

# 建立私有 API
<a name="apigateway-private-api-create"></a>

建立私有 API 之前，會先建立 API Gateway 的 VPC 端點。接著，您會建立私有 API，並為其附加資源政策。或者，您可以為 VPC 端點與私有 API 建立關聯，以簡化您調用 API 的方式。最後，部署 API。

下列程序說明如何完成該作業。您可以使用 AWS 管理主控台 AWS CLI 或 AWS SDK 建立私有 REST API。

## 先決條件
<a name="apigateway-private-api-create-interface-vpc-prerequisites"></a>

若要遵循這些步驟，您必須擁有已完整設定的 VPC。如需了解如何建立 VPC，請參閱《Amazon VPC 使用者指南》**中的[僅建立 VPC](https://docs.aws.amazon.com/vpc/latest/userguide/create-vpc.html#create-vpc-only)。要在建立 VPC 時遵循所有建議步驟，請啟用私有 DNS。如此一來，您就可以在 VPC 中調用 API，而不必傳遞主機或 `x-apigw-api-id` 標頭。

若要啟用私有 DNS，VPC 的 `enableDnsSupport` 和 `enableDnsHostnames` 屬性必須設為 `true`。如需詳細資訊，請參閱 [VPC 中的 DNS 支援](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-dns.html#vpc-dns-support)與[更新 VPC 的 DNS 支援](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-dns.html#vpc-dns-updating)。

## 步驟 1：在 VPC 中為 API Gateway 建立 VPC 端點
<a name="apigateway-private-api-create-interface-vpc-endpoint"></a>

下列程序顯示如何為 API Gateway 建立 VPC 端點。若要為 API Gateway 建立 VPC 端點，請為建立私有 API AWS 區域 的 指定`execute-api`網域。用於執行 API 的 API Gateway 元件服務的是 `execute-api` 網域。

當您為 API Gateway 建立 VPC 端點時，可以指定 DNS 設定。如果關閉私有 DNS，您只能使用公有 DNS 存取您的 API。如需詳細資訊，請參閱[問題：我無法從 API Gateway VPC 端點連線至我的公有 API](#apigateway-private-api-troubleshooting-public-access)。

------
#### [ AWS 管理主控台 ]

**為 API Gateway 建立介面 VPC 端點**

1. 登入 AWS 管理主控台 ，並在 [https://console.aws.amazon.com/vpc/](https://console.aws.amazon.com/vpc/)：// 開啟 Amazon VPC 主控台。

1. 在導覽窗格中的**虛擬私有雲端**下，選擇**端點**。

1. 選擇**建立端點**。

1. (選用) 針對**名稱標籤**輸入名稱，以協助識別 VPC 端點。

1. 在 **Service category** (服務類別) 中，選擇​ **AWS services**。

1. 在**服務**下方搜尋列中輸入 **execute-api**。然後，在您要建立 API AWS 區域 的 中選擇 API Gateway 服務端點。服務名稱應該看起來像 `com.amazonaws.us-east-1.execute-api`，**類型**應該看起來像**介面**。

1. 針對 **VPC**，選擇要在其中建立端點的 VPC。

1. (選用) 若要關閉**啟用私有 DNS 名稱**，請選擇**其他設定**，然後清除**啟用私有 DNS 名稱**。

1. 對於**子網路**，請選擇要建立端點網路介面的可用區域。為了提升 API 可用性，請選擇多個子網路。

1. 對於 **Security group (安全群組)**，請選擇要與 VPC 端點網路界面建立關聯的安全群組。

   您選擇的安全群組，必須設為允許從 VPC 的 IP 範圍或另一個安全群組的 TCP 連接埠 443 傳入 HTTPS 流量。

1. 對於**政策**，執行下列其中一項操作：
   + 如果您尚未建立私有 API，或不想要設定自訂 VPC 端點政策，請選擇**完整存取**。
   + 如果您已建立私有 API，並想要設定自訂 VPC 端點政策，則可以輸入自訂 VPC 端點政策。如需詳細資訊，請參閱[在 API Gateway 中使用私有 API 的 VPC 端點政策](apigateway-vpc-endpoint-policies.md)。

   您可以在建立 VPC 端點後更新 VPC 端點政策。如需詳細資訊，請參閱[更新 VPC 端點政策](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-access.html#update-vpc-endpoint-policy)。

1. 選擇**建立端點**。

1. 複製產生的 VPC 端點 ID，因為您可能會在後續步驟中使用該識別碼。

------
#### [ AWS CLI ]

以下 [create-vpc-endpoint](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-vpc-endpoint.html) 命令會建立 VPC 端點：

```
aws ec2 create-vpc-endpoint \
    --vpc-id vpc-1a2b3c4d \
    --vpc-endpoint-type Interface \
    --service-name com.amazonaws.us-east-1.execute-api \
    --subnet-ids subnet-7b16de0c \
    --security-group-id sg-1a2b3c4d
```

複製產生的 VPC 端點 ID，因為您可能會在後續步驟中使用該識別碼。

------

## 步驟 2：建立私有 API
<a name="apigateway-private-api-create-using-console"></a>

建立 VPC 端點後，您會建立私有 REST API。下列程序顯示如何建立私有 API。

------
#### [ AWS 管理主控台 ]

**建立私有 API**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇 **Create API (建立 API)**。

1. 在 **REST API** 下方，選擇 **Build (組建)**。

1. 針對**名稱**，輸入名稱。

1.  在**描述**，請輸入描述。

1. 針對 **API 端點類型**，選取**私有**。

1. (選用) 對於 **VPC 端點 ID**，請輸入 VPC 端點 ID。

   如果您為 VPC 端點 ID 與私有 API 建立關聯，您可以從 VPC 內調用 API，而不必覆寫 `Host` 標頭或傳遞 `x-apigw-api-id header`。如需詳細資訊，請參閱 [(選用) 關聯或取消關聯 VPC 端點與私有 REST API](#associate-private-api-with-vpc-endpoint)。

1. 對於 **IP 位址類型**，請選擇 **Dualstack**。

1. 選擇**建立 API**。

 完成先前的步驟後，您可以遵循 [開始使用 REST API 主控台](getting-started-rest-new-console.md) 中的指示來設定此 API 的方法和整合，但無法部署 API。若要部署您的 API，請遵循步驟 3，並將資源政策連接至您的 API。

------
#### [ AWS CLI ]

以下 [create-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-rest-api.html) 命令會建立私有 API：

```
aws apigateway create-rest-api \
        --name 'Simple PetStore (AWS CLI, Private)' \
        --description 'Simple private PetStore API' \
        --region us-west-2 \
        --endpoint-configuration '{ "types": ["PRIVATE"], "ipAddressType": "dualstack" }'
```

成功的呼叫會傳回類似如下的輸出：

```
{
    "createdDate": "2017-10-13T18:41:39Z",
    "description": "Simple private PetStore API",
    "endpointConfiguration": {
        "types": [
            "PRIVATE"
        ],
        "ipAddressType": "dualstack"
    },
    "id": "0qzs2sy7bh",
    "name": "Simple PetStore (AWS CLI, Private)"
}
```

 完成先前的步驟後，您可以遵循 [教學課程：使用 AWS SDKs或 建立 REST API AWS CLI](api-gateway-create-api-cli-sdk.md) 中的指示來設定此 API 的方法和整合，但無法部署 API。若要部署您的 API，請遵循步驟 3，並將資源政策連接至您的 API。

------
#### [ SDK JavaScript v3 ]

下列範例示範如何使用適用於 JavaScript 的 AWS SDK v3 建立私有 API：

```
import {APIGatewayClient, CreateRestApiCommand} from "@aws-sdk/client-api-gateway";
const apig = new APIGatewayClient({region:"us-east-1"});

const input = { // CreateRestApiRequest
  name: "Simple PetStore (JavaScript v3 SDK, private)", // required
  description: "Demo private API created using the AWS SDK for JavaScript v3",
  version: "0.00.001",
  endpointConfiguration: { // EndpointConfiguration
    types: [ "PRIVATE"],
  },  
};

export const handler = async (event) => {
const command = new CreateRestApiCommand(input);
try {
  const result = await apig.send(command);
  console.log(result);
} catch (err){
  console.error(err)
 }
};
```

成功的呼叫會傳回類似如下的輸出：

```
{
  apiKeySource: 'HEADER',
  createdDate: 2024-04-03T17:56:36.000Z,
  description: 'Demo private API created using the AWS SDK for JavaScript v3',
  disableExecuteApiEndpoint: false,
  endpointConfiguration: { types: [ 'PRIVATE' ] },
  id: 'abcd1234',
  name: 'Simple PetStore (JavaScript v3 SDK, private)',
  rootResourceId: 'efg567',
  version: '0.00.001'
}
```

 完成先前的步驟後，您可以遵循 [教學課程：使用 AWS SDKs或 建立 REST API AWS CLI](api-gateway-create-api-cli-sdk.md) 中的指示來設定此 API 的方法和整合，但無法部署 API。若要部署您的 API，請遵循步驟 3，並將資源政策連接至您的 API。

------
#### [ Python SDK ]

下列範例示範如何使用適用於 Python 的 AWS SDK 建立私有 API：

```
import json
import boto3
import logging

logger = logging.getLogger()
apig = boto3.client('apigateway')

def lambda_handler(event, context):
    try:
      result = apig.create_rest_api(
      name='Simple PetStore (Python SDK, private)',
      description='Demo private API created using the AWS SDK for Python',
      version='0.00.001',
      endpointConfiguration={
          'types': [
             'PRIVATE',
          ],
      },
      )
    except botocore.exceptions.ClientError as error:
            logger.exception("Couldn't create private API %s.", error)
            raise
    attribute=["id", "name", "description", "createdDate", "version", "apiKeySource", "endpointConfiguration"]
    filtered_data ={key:result[key] for key in attribute}
    result = json.dumps(filtered_data, default=str, sort_keys='true')
    return result
```

成功的呼叫會傳回類似如下的輸出：

```
"{\"apiKeySource\": \"HEADER\", \"createdDate\": \"2024-04-03 17:27:05+00:00\", \"description\": \"Demo private API created using the AWS SDK for \", \"endpointConfiguration\": {\"types\": [\"PRIVATE\"]}, \"id\": \"abcd1234\", \"name\": \"Simple PetStore (Python SDK, private)\", \"version\": \"0.00.001\"}"
```

 完成先前的步驟後，您可以遵循 [教學課程：使用 AWS SDKs或 建立 REST API AWS CLI](api-gateway-create-api-cli-sdk.md) 中的指示來設定此 API 的方法和整合，但無法部署 API。若要部署您的 API，請遵循步驟 3，並將資源政策連接至您的 API。

------

## 步驟 3：為私有 API 設定資源政策
<a name="apigateway-private-api-set-up-resource-policy"></a>

所有 VPC 都無法存取您目前的私有 API。使用資源政策，授予私有 API 的 VPC 和 VPC 端點存取權。您可以授予任何 AWS 帳戶中 VPC 端點的存取權。

您的資源政策應包含 `aws:SourceVpc` 或 `aws:SourceVpce` 條件來限制存取。建議您識別特定 VPC 和 VPC 端點，不要建立允許存取所有 VPC 和 VPC 端點的資源政策。

下列程序顯示如何將資源政策連接至您的 API。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇 REST API。

1. 在主導覽窗格中，選擇**資源政策**。

1. 選擇**建立政策**。

1. 選擇**選取來源**，然後選擇**來源 VPC**。

1. 將 `{{vpcID}}` (包括大括號) 取代為您的 VPC ID。

1. 選擇**儲存變更**。

------
#### [ AWS CLI ]

以下 [update-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html) 命令會將資源政策附加至現有的 API：

```
aws apigateway update-rest-api \
    --rest-api-id a1b2c3 \
    --patch-operations op=replace,path=/policy,value='"{\"jsonEscapedPolicyDocument\"}"'
```

------

您也可以控制哪些資源可以存取您的 VPC 端點。若要控制哪些資源具有 VPC 端點的存取權，可將 VPC 端點政策連接到您的 VPC 端點。如需詳細資訊，請參閱[在 API Gateway 中使用私有 API 的 VPC 端點政策](apigateway-vpc-endpoint-policies.md)。

## (選用) 關聯或取消關聯 VPC 端點與私有 REST API
<a name="associate-private-api-with-vpc-endpoint"></a>

建立 VPC 端點與私有 API 的關聯後，API Gateway 會產生新的 Route 53 別名 DNS 記錄。您可以使用此記錄調用私有 API，就像您可以執行公有 API，而無需覆寫 `Host` 標頭或傳遞 `x-apigw-api-id` 標頭。

產生的基本 URL 格式如下：

```
https://{rest-api-id}-{vpce-id}.execute-api.{region}.amazonaws.com/{stage}
```

------
#### [ Associate a VPC endpoint (AWS 管理主控台) ]

您可以在建立 VPC 端點時或建立 VPC 端點之後，為其建立與私有 API 的關聯。下列程序顯示如何為 VPC 端點與先前建立的 API 建立關聯。

**為其他 VPC 端點與私有 API 建立關聯**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇您的私有 API。

1. 在主導覽窗格中，選擇**資源政策**。

1. 編輯您的資源政策以允許來自其他 VPC 端點的呼叫。

1. 在主導覽窗格中，選擇 **API 設定**。

1. 在 **API 詳細資訊**區段中，選擇**編輯**。

1. 對於 **VPC 端點 ID**，選取其他 VPC 端點 ID。

1. 選擇**儲存**。

1. 重新部署 API 以使變更生效。

------
#### [ Dissociate a VPC endpoint (AWS 管理主控台) ]

**將 VPC 端點與私有 REST API 取消關聯**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇您的私有 API。

1. 在主導覽窗格中，選擇**資源政策**。

1. 編輯您的資源政策，以移除所提及要與私有 API 取消關聯的 VPC 端點。

1. 在主導覽窗格中，選擇 **API 設定**。

1. 在 **API 詳細資訊**區段中，選擇**編輯**。

1. 對於 **VPC 端點 ID**，選擇 **X** 以將 VPC 端點取消關聯。

1. 選擇**儲存**。

1. 重新部署 API 以使變更生效。

------
#### [ Associate a VPC endpoint (AWS CLI) ]

以下 [create-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-rest-api.html) 命令會在建立 API 時與 VPC 端點建立關聯：

```
aws apigateway create-rest-api \
    --name Petstore \
    --endpoint-configuration '{ "types": ["PRIVATE"], "vpcEndpointIds" : ["vpce-0212a4ababd5b8c3e", "vpce-0393a628149c867ee"] }' \
    --region us-west-2
```

輸出將如下所示：

```
{
    "apiKeySource": "HEADER",
    "endpointConfiguration": {
        "types": [
            "PRIVATE"
        ],
        "vpcEndpointIds": [
            "vpce-0212a4ababd5b8c3e",
            "vpce-0393a628149c867ee"
        ]
    },
    "id": "u67n3ov968",
    "createdDate": 1565718256,
    "name": "Petstore"
}
```

以下 [update-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html) 命令會將 VPC 端點與您已建立的 API 建立關聯：

```
aws apigateway update-rest-api \
    --rest-api-id u67n3ov968 \
    --patch-operations "op='add',path='/endpointConfiguration/vpcEndpointIds',value='vpce-01d622316a7df47f9'" \
    --region us-west-2
```

輸出將如下所示：

```
{
    "name": "Petstore",
    "apiKeySource": "1565718256",
    "tags": {},
    "createdDate": 1565718256,
    "endpointConfiguration": {
        "vpcEndpointIds": [
            "vpce-0212a4ababd5b8c3e",
            "vpce-0393a628149c867ee",
            "vpce-01d622316a7df47f9"
        ],
        "types": [
            "PRIVATE"
        ]
    },
    "id": "u67n3ov968"
}
```

重新部署 API 以使變更生效。

------
#### [ Disassociate a VPC endpoint (AWS CLI) ]

以下 [update-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html) 命令會取消 VPC 端點與私有 API 的關聯：

```
aws apigateway update-rest-api \
    --rest-api-id u67n3ov968 \
    --patch-operations "op='remove',path='/endpointConfiguration/vpcEndpointIds',value='vpce-0393a628149c867ee'" \
    --region us-west-2
```

輸出將如下所示：

```
{
    "name": "Petstore",
    "apiKeySource": "1565718256",
    "tags": {},
    "createdDate": 1565718256,
    "endpointConfiguration": {
        "vpcEndpointIds": [
            "vpce-0212a4ababd5b8c3e",
            "vpce-01d622316a7df47f9"
        ],
        "types": [
            "PRIVATE"
        ]
    },
    "id": "u67n3ov968"
}
```

重新部署 API 以使變更生效。

------

## 步驟 4：部署私有 API
<a name="apigateway-private-api-deploy-using-console"></a>

若要部署您的 API，請建立 API 部署，並為其建立與階段的關聯。下列程序顯示如何部署您的私有 API。

------
#### [ AWS 管理主控台 ]

**部署私有 API**

1. 選擇您的 API。

1. 選擇**部署 API**。

1. 針對**階段**，選取**新階段**。

1. 針對**階段名稱**，輸入階段名稱。

1. 在**描述**，請輸入描述。

1. 選擇**部署**。

------
#### [ AWS CLI ]

以下 [create-deployment](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-deployment.html) 命令會部署私有 API：

```
aws apigateway create-deployment --rest-api-id a1b2c3 \ 
  --stage-name test \
  --stage-description 'Private API test stage' \
  --description 'First deployment'
```

------

## 針對私有 API 進行疑難排解
<a name="apigateway-private-api-troubleshooting"></a>

以下建議說明如何針對在建立私有 API 時可能會遇到的錯誤和問題，進行疑難排解。

### 問題：我無法從 API Gateway VPC 端點連線至我的公有 API
<a name="apigateway-private-api-troubleshooting-public-access"></a>

建立 VPC 時，您可以設定 DNS 設定。建議您為 VPC 開啟私有 DNS。如果選擇關閉私有 DNS，您將僅能透過公有 DNS 存取您的 API。

如果啟用私有 DNS，則您無法從 VPC 端點存取公有 API Gateway API 的預設端點。您可以使用自訂網域名稱存取 API。

如果您建立區域性自訂網域名稱，請使用 A 型別名記錄，如果建立邊緣最佳化的自訂網域名稱，則記錄類型沒有限制。您可以在啟用私有 DNS 的情況下存取這些公有 API。如需詳細資訊，請參閱[問題：我從 API Gateway VPC 端點連線至我的公有 API](https://repost.aws/knowledge-center/api-gateway-vpc-connections)。

### 問題：我的 API 傳回 `{"Message":"User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-east-1:********/****/****/"}`
<a name="apigateway-private-api-troubleshooting-principal"></a>

在您的資源政策中，如果您將主體設定為 AWS 委託人，如下所示：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::111122223333:role/developer",
                    "arn:aws:iam::111122223333:role/Admin"
                ]
            },
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/stage/GET/pets"
            ]
        }
    ]
}
```

------

您必須對 API 中的每個方法使用 `AWS_IAM` 授權，否則您的 API 會傳回先前的錯誤訊息。如需有關如何為方法開啟 `AWS_IAM` 授權的詳細資訊，請參閱 [API Gateway 中 REST API 的方法](how-to-method-settings.md)。

### 問題：我無法判斷我的 VPC 端點是否與我的 API 相關聯
<a name="apigateway-private-api-troubleshooting-associate-wait-time"></a>

如果您為 VPC 端點與您的私有 API 建立關聯，或取消它們的關聯，則需要重新部署 API。由於 DNS 傳播之故，更新操作可能需要幾分鐘時間才能完成。在這段期間，您的 API 將可供使用，但新產生的 DNS URL 的 DNS 傳播可能仍在進行中。如果幾分鐘後，您的新 URL 未在 DNS 中解析，建議您重新部署 API。