

# Using HTTP resolvers in Amazon AppSync
<a name="tutorial-http-resolvers-js"></a>

Amazon AppSync enables you to use supported data sources (that is, Amazon Lambda, Amazon DynamoDB, Amazon OpenSearch Service, or Amazon Aurora) to perform various operations, in addition to any arbitrary HTTP endpoints to resolve GraphQL fields. After your HTTP endpoints are available, you can connect to them using a data source. Then, you can configure a resolver in the schema to perform GraphQL operations such as queries, mutations, and subscriptions. This tutorial walks you through some common examples.

In this tutorial you use a REST API (created using Amazon API Gateway and Lambda) with an Amazon AppSync GraphQL endpoint.

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

You can use the following Amazon CloudFormation template to set up a REST endpoint that works for this tutorial:

[https://console.amazonaws.cn/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.amazonaws.cn/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/http/http-api-gw.yaml)

The Amazon CloudFormation stack performs the following steps:

1. Sets up a Lambda function that contains your business logic for your microservice.

1. Sets up an API Gateway REST API with the following endpoint/method/content type combination:


****  

| API Resource Path | HTTP Method | Supported Content Type | 
| --- | --- | --- | 
| /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 | 

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

To create the GraphQL API in Amazon AppSync:

1. Open the Amazon AppSync console and choose **Create API**.

1. Choose **GraphQL APIs** and then choose **Design from scratch**. Choose **Next**.

1. For the API name, type `UserData`. Choose **Next**.

1. Choose `Create GraphQL resources later`. Choose **Next**.

1. Review your inputs and choose **Create API**.

The Amazon AppSync console creates a new GraphQL API for you using the API key authentication mode. You can use the console to further configure your GraphQL API and run requests.

## Creating a GraphQL schema
<a name="creating-a-graphql-schema"></a>

Now that you have a GraphQL API, let’s create a GraphQL schema. In the **Schema** editor in the Amazon AppSync console, use the snippet below:

```
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
}
```

## Configure your HTTP data source
<a name="configure-your-http-data-source"></a>

To configure your HTTP data source, do the following:

1. In the **Data sources** page in your Amazon AppSync GraphQL API, choose **Create data source**.

1. Enter a name for the data source like `HTTP_Example`.

1. In **Data source type**, choose **HTTP endpoint**.

1. Set the endpoint to the API Gateway endpoint that was created at the beginning of the tutorial. You can find your stack-generated endpoint if you navigate to the Lambda console and find your application under **Applications**. Inside of your application's settings, you should see an **API endpoint** which will be your endpoint in Amazon AppSync. Make sure you don’t include the stage name as part of the endpoint. For instance, if your endpoint were `https://aaabbbcccd.execute-api.us-east-1.amazonaws.com/v1`, you would type in `https://aaabbbcccd.execute-api.us-east-1.amazonaws.com`.

**Note**  
At this time, only public endpoints are supported by Amazon AppSync.  
For more information about the certifying authorities that are recognized by the Amazon AppSync service, see [Certificate Authorities (CA) Recognized by Amazon AppSync for HTTPS Endpoints](http-cert-authorities.md#aws-appsync-http-certificate-authorities).

## Configuring resolvers
<a name="configuring-resolvers"></a>

In this step, you will connect the HTTP data source to the `getUser` and `addUser` queries.

To set up the `getUser` resolver:

1. In your Amazon AppSync GraphQL API, choose the **Schema** tab.

1. To the right of the **Schema** editor, in the **Resolvers** pane and under the **Query** type, find the `getUser` field and choose **Attach**.

1. Keep the resolver type to `Unit` and the runtime to `APPSYNC_JS`.

1. In **Data source name**, choose the HTTP endpoint you made earlier.

1. Choose **Create**.

1. In the **Resolver** code editor, add the following snippet as your request handler:

   ```
   import { util } from '@aws-appsync/utils'
   
   export function request(ctx) {
   	return {
   		version: '2018-05-29',
   		method: 'GET',
   		params: {
   			headers: {
   				'Content-Type': 'application/json',
   			},
   		},
   		resourcePath: `/v1/users/${ctx.args.id}`,
   	}
   }
   ```

1. Add the following snippet as your response handler:

   ```
   export function response(ctx) {
   	const { statusCode, body } = ctx.result
   	// if response is 200, return the response
   	if (statusCode === 200) {
   		return JSON.parse(body)
   	}
   	// if response is not 200, append the response to error block.
   	util.appendError(body, statusCode)
   }
   ```

1. Choose the **Query** tab, and then run the following query:

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

   This should return the following response:

   ```
   {
       "data": {
           "getUser": {
               "id": "1",
               "username": "nadia"
           }
       }
   }
   ```

To set up the `addUser` resolver:

1. Choose the **Schema** tab.

1. To the right of the **Schema** editor, in the **Resolvers** pane and under the **Query** type, find the `addUser` field and choose **Attach**.

1. Keep the resolver type to `Unit` and the runtime to `APPSYNC_JS`.

1. In **Data source name**, choose the HTTP endpoint you made earlier.

1. Choose **Create**.

1. In the **Resolver** code editor, add the following snippet as your request handler:

   ```
   export function request(ctx) {
       return {
           "version": "2018-05-29",
           "method": "POST",
           "resourcePath": "/v1/users",
           "params":{
               "headers":{
                   "Content-Type": "application/json"
               },
           "body": ctx.args.userInput
           }
       }
   }
   ```

1. Add the following snippet as your response handler:

   ```
   export function response(ctx) {
       if(ctx.error) {
           return util.error(ctx.error.message, ctx.error.type)
       }
       if (ctx.result.statusCode == 200) {
           return ctx.result.body
       } else {
           return util.appendError(ctx.result.body, "ctx.result.statusCode")
       }
   }
   ```

1. Choose the **Query** tab, and then run the following query:

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

   If you run the `getUser` query again, it should return the following response:

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

## Invoking Amazon Services
<a name="invoking-aws-services-js"></a>

You can use HTTP resolvers to set up a GraphQL API interface for Amazon services. HTTP requests to Amazon must be signed with the [Signature Version 4 process](https://docs.amazonaws.cn/general/latest/gr/signature-version-4.html) so that Amazon can identify who sent them. Amazon AppSync calculates the signature on your behalf when you associate an IAM role with the HTTP data source.

You provide two additional components to invoke Amazon services with HTTP resolvers:
+ An IAM role with permissions to call the Amazon service APIs
+ Signing configuration in the data source

For example, if you want to call the [ListGraphqlApis operation](https://docs.amazonaws.cn/appsync/latest/APIReference/API_ListGraphqlApis.html) with HTTP resolvers, you first [create an IAM role](attaching-a-data-source.md#aws-appsync-getting-started-build-a-schema-from-scratch) that Amazon AppSync assumes with the following policy attached:

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

****  

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

------

Next, create the HTTP data source for Amazon AppSync. In this example, you call Amazon AppSync in the US West (Oregon) Region. Set up the following HTTP configuration in a file named `http.json`, which includes the signing region and service name:

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

Then, use the Amazon CLI to create the data source with an associated role as follows:

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

When you attach a resolver to the field in the schema, use the following request mapping template to call Amazon AppSync:

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

When you run a GraphQL query for this data source, Amazon AppSync signs the request using the role you provided and includes the signature in the request. The query returns a list of Amazon AppSync GraphQL APIs in your account in that Amazon Region.