

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

# 使用 HTTP 解析程式 in AWS AppSync
<a name="tutorial-http-resolvers"></a>

**注意**  
我們現在主要支援 APPSYNC\$1JS 執行期及其文件。請考慮[在此處](https://docs.aws.amazon.com/appsync/latest/devguide/tutorials-js.html)使用 APPSYNC\$1JS 執行期及其指南。

AWS AppSync 可讓您使用支援的資料來源 （即 Amazon DynamoDB AWS Lambda、Amazon OpenSearch Service 或 Amazon Aurora) 來執行各種操作，以及任何任意 HTTP 端點來解析 GraphQL 欄位。在您的 HTTP 端點可供使用之後，您可以使用資料來源連線到這些端點。然後，您可以在結構描述中設定解析程式以執行 GraphQL 操作，例如查詢、變動和訂閱。本教學將逐步說明一些常見的範例。

在本教學課程中，您將 REST API （使用 Amazon API Gateway 和 Lambda 建立） 與 AWS AppSync GraphQL 端點搭配使用。

## 一鍵設定
<a name="one-click-setup"></a>

如果您想要在設定 HTTP 端點的情況下自動設定 GraphQL 端點 in AWS AppSync （使用 Amazon API Gateway 和 Lambda)，您可以使用下列 AWS CloudFormation 範本：

[https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/http/http-full.yaml](https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/http/http-full.yaml)

## 建立 REST API
<a name="creating-a-rest-api"></a>

您可以使用下列 AWS CloudFormation 範本來設定適用於本教學課程的 REST 端點：

[https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/http/http-api-gw.yaml](https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/http/http-api-gw.yaml)

 AWS CloudFormation 堆疊會執行下列步驟：

1. 設定 Lambda 函數，其中包含您微服務的商業邏輯。

1. 使用下列endpoint/method/content類型組合來設定 API Gateway REST API：


****  

| API 資源路徑 | HTTP 方法 | 已支援的內容類型 | 
| --- | --- | --- | 
|  /v1/users  |  POST  |  application/json  | 
|  /v1/users  |  GET  |  application/json  | 
|  /v1/users/1  |  GET  |  application/json  | 
|  /v1/users/1  |  PUT  |  application/json  | 
|  /v1/users/1  |  DELETE  |  application/json  | 

## 建立 GraphQL API
<a name="creating-your-graphql-api"></a>

若要在 AWS AppSync 中建立 GraphQL API：
+ 開啟 AWS AppSync 主控台，然後選擇**建立 API**。
+ 針對 API 名稱，輸入 `UserData`。
+ 選擇 **Custom schema (自訂結構描述)**。
+ 選擇**建立**。

 AWS AppSync 主控台會使用 API 金鑰身分驗證模式為您建立新的 GraphQL API。您可以使用主控台來設定 GraphQL API 的其餘部分，並在本教學的其餘部分中對其執行查詢。

## 建立 GraphQL 結構描述
<a name="creating-a-graphql-schema"></a>

現在您有一個 GraphQL API，讓我們來建立 GraphQL 結構描述吧。從 AWS AppSync 主控台中的結構描述編輯器，請確定您的結構描述符合下列結構描述：

```
schema {
    query: Query
    mutation: Mutation
}

type Mutation {
    addUser(userInput: UserInput!): User
    deleteUser(id: ID!): User
}

type Query {
    getUser(id: ID): User
    listUser: [User!]!
}

type User {
    id: ID!
    username: String!
    firstname: String
    lastname: String
    phone: String
    email: String
}

input UserInput {
    id: ID!
    username: String!
    firstname: String
    lastname: String
    phone: String
    email: String
}
```

## 設定您的 HTTP 資料來源
<a name="configure-your-http-data-source"></a>

若要設定您的 HTTP 資料來源，請執行以下作業：
+ 在 **DataSources** 標籤中，選擇 **New (新增)**，然後輸入易記的資料來源名稱 (例如，`HTTP`)。
+ 在 **Data source type (資料來源類型)** 中選擇 **HTTP**。
+ 將端點設定為建立的 API Gateway 端點。請確定您沒有在端點中包含階段名稱。

 **注意：**目前 AWS AppSync 僅支援公有端點。

 **注意：**如需認證授權機構的詳細資訊， AWS AppSync 請參閱 [AWS AppSync HTTPS 端點的認證授權機構 (CA)](http-cert-authorities.md#aws-appsync-http-certificate-authorities)。

## 設定解析程式
<a name="configuring-resolvers"></a>

在此步驟中，您會將 http 資料來源連線到 **getUser** 查詢。

設定解析程式：
+ 選擇 **Schema (結構描述)** 標籤。
+ 在**查詢**類型下右側的**資料類型**窗格中，尋找 **getUser** 欄位，然後選擇**連接**。
+ 在 **Data source name (資料來源名稱)** 中，選擇 **HTTP**。
+ 將以下內容貼到 **Configure the request mapping template (設定請求映射範本)** 區段：

```
{
    "version": "2018-05-29",
    "method": "GET",
    "params": {
        "headers": {
            "Content-Type": "application/json"
        }
    },
    "resourcePath": $util.toJson("/v1/users/${ctx.args.id}")
}
```
+ 將以下內容貼到 **Configure the response mapping template (設定回應映射範本)** 區段：

```
## return the body
#if($ctx.result.statusCode == 200)
    ##if response is 200
    $ctx.result.body
#else
    ##if response is not 200, append the response to error block.
    $utils.appendError($ctx.result.body, "$ctx.result.statusCode")
#end
```
+ 選擇 **Query (查詢)** 標籤，然後執行以下查詢：

```
query GetUser{
    getUser(id:1){
        id
        username
    }
}
```

這應該會傳回以下回應：

```
{
    "data": {
        "getUser": {
            "id": "1",
            "username": "nadia"
        }
    }
}
```
+ 選擇 **Schema (結構描述)** 標籤。
+ 在 **Mutation** 下右側的**資料類型**窗格中，尋找 **addUser** 欄位，然後選擇**連接**。
+ 在 **Data source name (資料來源名稱)** 中，選擇 **HTTP**。
+ 將以下內容貼到 **Configure the request mapping template (設定請求映射範本)** 區段：

```
{
    "version": "2018-05-29",
    "method": "POST",
    "resourcePath": "/v1/users",
    "params":{
      "headers":{
        "Content-Type": "application/json",
      },
      "body": $util.toJson($ctx.args.userInput)
    }
}
```
+ 將以下內容貼到 **Configure the response mapping template (設定回應映射範本)** 區段：

```
## Raise a GraphQL field error in case of a datasource invocation error
#if($ctx.error)
    $util.error($ctx.error.message, $ctx.error.type)
#end
## if the response status code is not 200, then return an error. Else return the body **
#if($ctx.result.statusCode == 200)
    ## If response is 200, return the body.
    $ctx.result.body
#else
    ## If response is not 200, append the response to error block.
    $utils.appendError($ctx.result.body, "$ctx.result.statusCode")
#end
```
+ 選擇 **Query (查詢)** 標籤，然後執行以下查詢：

```
mutation addUser{
    addUser(userInput:{
        id:"2",
        username:"shaggy"
    }){
        id
        username
    }
}
```

這應該會傳回以下回應：

```
{
    "data": {
        "getUser": {
        "id": "2",
        "username": "shaggy"
        }
    }
}
```

## 叫用 AWS 服務
<a name="invoking-aws-services"></a>

您可以使用 HTTP 解析程式來設定 AWS 服務的 GraphQL API 介面。對 的 HTTP 請求 AWS 必須使用 [Signature 第 4 版程序](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html)簽署，以便 AWS 可以識別傳送這些請求的人員。當您將 IAM 角色與 HTTP 資料來源建立關聯時， AWS AppSync 會代表您計算簽章。

您提供兩個額外的元件，以使用 HTTP 解析程式叫用 AWS 服務：
+ 具有呼叫 AWS 服務 APIs 許可的 IAM 角色
+ 資料來源中的簽署組態

例如，如果您想要使用 HTTP 解析程式呼叫 [ListGraphqlApis 操作](https://docs.aws.amazon.com/appsync/latest/APIReference/API_ListGraphqlApis.html)，請先[建立 AppSync 擔任並連接下列政策的 IAM 角色](attaching-a-data-source.md#aws-appsync-getting-started-build-a-schema-from-scratch)： AWS AppSync 

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "appsync:ListGraphqlApis"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
```

------

接著，建立 HTTP 資料來源 for AWS AppSync。在此範例中，您在美國西部 （奧勒岡） 區域呼叫 AWS AppSync。在名為 `http.json` 的檔案中設定以下 HTTP 組態，包含簽署區域和服務名稱：

```
{
    "endpoint": "https://appsync.us-west-2.amazonaws.com/",
    "authorizationConfig": {
        "authorizationType": "AWS_IAM",
        "awsIamConfig": {
            "signingRegion": "us-west-2",
            "signingServiceName": "appsync"
        }
    }
}
```

然後，使用 AWS CLI 建立具有關聯角色的資料來源，如下所示：

```
aws appsync create-data-source --api-id <API-ID> \
                               --name AWSAppSync \
                               --type HTTP \
                               --http-config file:///http.json \
                               --service-role-arn <ROLE-ARN>
```

當您將解析程式連接至結構描述中的 欄位時，請使用下列請求映射範本來 call AWS AppSync：

```
{
    "version": "2018-05-29",
    "method": "GET",
    "resourcePath": "/v1/apis"
}
```

當您對此資料來源執行 GraphQL 查詢時， AWS AppSync 會使用您提供的角色簽署請求，並在請求中包含簽章。查詢會傳回您帳戶中該 AWS 區域的 AWS AppSync GraphQL APIs清單。