# Remote data examples

Examples on how to work with Remote Sources, Remote Fields and Top-level Remote Fields.

Follow these examples to configure custom, commercetools, and Commercelayer Remote Sources, remote fields, top-level remote fields, and custom input types.

## Custom remote source and field configuration

In this video, Bryan uses [Federate this](https://www.federatethis.com/) - our collection of mock APIs and information for federated data sources in GraphQL - to show you how to add data from a remote API to your Hygraph project step-by-step.

[Video](https://www.youtube.com/watch?v=mANTy5_OTQo)

### Configure the remote source

Navigate to the **Schema builder** and click on `+Add` next to **Remote sources** to create a new one. Use the following information:

| Field          | Input                              |
| -------------- | ---------------------------------- |
| `Display name` | Third Party APIs                   |
| `Prefix`       | ThirdPartyApIs                     |
| `Type`         | Select `REST`                      |
| `Base URL`     | `https://www.federatethis.com/api` |

**Custom type definition:**

Click `+ Add custom type definition` and we'll paste the product type and products array from [Federate This](https://www.federatethis.com/routes/products/):

```graphql
type Product {
    id: Int
    name: String
    price: Int
    description: String
    image: String
    category: String
    rating: Float
    numReviews: Int
    countInStock: Int
}

type Products {
    data: [Product]
}
```
We'll also add the following under `Products`:

```graphql
type ProductMeta {
  data: Product
}
```
What we just added will have a data field that will bring a singular product.

Click `Add` at the top-right corner of your screen to create the remote source.

Once the remote source is created, you can use it to add a remote field.

### Configure remote field

After configuring our remote source, go to **Schema > Query** and add a top-level remote field, which will allow us to connect our products list as data directly in our API.

To add your remote field, click on `REST` from the right sidebar and use the following information:

| Field           | Input                                                        |
| --------------- | ------------------------------------------------------------ |
| `Display name`  | Products                                                     |
| `API ID`        | products                                                     |
| `Remote source` | `Third Party APIs` is selected by default. Leave it as it is |
| `Method`        | `GET` is selected by default. Leave it as it is              |
| `Return type`   | Use the dropdown to select `ProductMeta`                     |
| `Path`          | `/products`                                                  |

Click `Add` at the bottom of the screen to create your remote field.

**Would you like to check if it works?:**
Go to the API Playground and try out the following query:

  **Query**

```graphql
query MyQuery {
  products {
    data {
      name
      price
      id
    }
  }
}
```

  
  **Response**

```graphql
{
  "data": {
    "products": {
      "data": [
        {
          "name": "Product 1",
          "price": 100,
          "id": 1
        },
        {
          "name": "Product 2",
          "price": 200,
          "id": 2
        },
        {
          "name": "Product 3",
          "price": 300,
          "id": 3
        }
      ]
    }
  }
}
```


If you run the query, it should return information on three sample products.

If we wanted to bring specific information into a **Product** model, we'd have to add a Remote Field into that model.

If you do not have a **Product** model yet, you can go to your Schema and click `+ Add` next to Models and use the following information to create it:

| Field           | Input         |
| --------------- | ------------- |
| `Display name`  | ProductPage   |
| `API ID`        | productPage   |
| `Plural API ID` | productsPages |

Let's also add some fields to this model. We won't be adding price or any other information that is otherwise in out API. We will only add fields that we want to add to our data and that Editors will be able to work with.

We'll start with a `single line text` field that we'll use as a title:

| Field                | Input                |
| -------------------- | -------------------- |
| `Display name`       | Title                |
| `API ID`             | title                |
| `Use as title field` | Select this checkbox |

We'll add a `slug` field:

| Field           | Input                        |
| --------------- | ---------------------------- |
| `Display name ` | Slug                         |
| `API ID`        | slug                         |
| `Lowercase`     | Leave this checkbox selected |

We'll add a `Rich Text` field:

| Field          | Input |
| -------------- | ----- |
| `Display name` | Body  |
| `API ID`       | body  |

We need to associate the data in this model with the data that's in our API, and for that we'll add another `single line text` field, using the following information:

| Field          | Input  |
| -------------- | ------ |
| `Display name` | API ID |
| `API ID`       | apiId  |

At this point we're ready to add our remote field. We'll scroll down the right sidebar and add a `REST` field using the following information:

| Field           | Input                                                        |
| --------------- | ------------------------------------------------------------ |
| `Display name`  | Product data                                                 |
| `API ID`        | productData                                                  |
| `Remote source` | `Third Party APIs` is selected by default. Leave it as it is |
| `Method`        | `GET` is selected by default. Leave it as it is              |
| `Return type`   | Use the dropdown to select `ProductMeta`                     |
| `Path`          | `/product/{{doc.apiId}}`                                     |

Click `Add` to save your remote field.

Let's create an entry for our **ProductPage** model. Navigate to **Content editor > ProductPage** and click `+ Add entry`.

We'll use the following information:

| Field    | Input                                                                                   |
| -------- | --------------------------------------------------------------------------------------- |
| `Title`  | Product 1 with extra data                                                               |
| `Slug`   | product-1                                                                               |
| `Body`   | Use the dropdown tos elect Heading 2 and write "This is a headline".                    |
| `API ID` | This is where we will write the API ID of our product. IN this example we'll write "1". |

We'll click `Save & publish` and go to the API Playground to test this.

Let's run the following query:

  **Query**

```graphql
query MyQuery {
  productPages {
    apiId
    body {
      html
    }
    slug
    title
    productData {
      data {
        price
        rating
        numReviews
        description
        countInStock
      }
    }
  }
}
```

  
  **Response**

```graphql
{
  "data": {
    "productPages": [
      {
        "apiId": "1",
        "body": {
          "html": "<h2>This is a headline</h2><p></p>"
        },
        "slug": "product-1",
        "title": "Product 1 with extra data",
        "productData": {
          "data": {
            "price": 100,
            "rating": 4.5,
            "numReviews": 10,
            "description": "This is product 1",
            "countInStock": 10
          }
        }
      }
    ]
  }
}
```


This query brings all the information we just added in to the content entry that we created, which comes from Hygraph's data, and also includes the productData data, which comes from the API and is associated through the `API ID` field we added earlier.

Now imagine you also want to add your product reviews here. [Federate this](https://www.federatethis.com/routes/reviews/) has sample reviews that we can use to try this. We'll go back into the schema builder and edit our remote source by adding 3 new custom type definitions.

In our remote source, we'll click on `+ Add new custom type definition`. We'll do this three times, to add the following types:

  **Review**

```graphql
type Review {
    id: Int
    product: Int
    productSlug: String
    name: String
    rating: Float
    comment: String
}
```

  
  **Reviews**

```graphql
type Reviews {
    data: [Review]
}
```

  
  **ReviewMeta**

```graphql
type ReviewMeta {
    data: [Review]
}
```


Don't forget to click `Save` at the top-right of your screen to update your remote source.

Next, we're going to add this to our **ProductPage** model as a `REST` remote field. To do this, navigate to **Schema builder > ProductPage**, select the `REST` field from the right sidebar, and use the following information:

| Field           | Input                                                        |
| --------------- | ------------------------------------------------------------ |
| `Display name`  | Product Reviews                                              |
| `API ID`        | productReviews                                               |
| `Remote source` | `Third Party APIs` is selected by default. Leave it as it is |
| `Method`        | `GET` is selected by default. Leave it as it is              |
| `Return type`   | Use the dropdown to select `ReviewtMeta`                     |
| `Path`          | `/reviews/product/{{doc.apiId}}`                             |

Click `Add` to save your remote field.

The way we have set this up allows for the product details and the reviews from that product to pull from a single API ID, which we included in the `API ID` field that we added to our schema earlier and to which we assigned a value in the sample entry we created.

Now we can go back to the API Playground to test this using the following query:

  **Query**

```graphql
query MyQuery {
  productPages {
    apiId
    body {
      html
    }
    slug
    title
    productData {
      data {
        price
        rating
        numReviews
        description
        countInStock
      }
    }
    productReviews {
      data {
        comment
        name
        rating
      }
    }
  }
}
```

  
  **Response**

```graphql
{
  "data": {
    "productPages": [
      {
        "apiId": "1",
        "body": {
          "html": "<h2>This is a headline</h2><p></p>"
        },
        "slug": "product-1",
        "title": "Product 1 with extra data",
        "productData": {
          "data": {
            "price": 100,
            "rating": 4.5,
            "numReviews": 10,
            "description": "This is product 1",
            "countInStock": 10
          }
        },
        "productReviews": {
          "data": [
            {
              "comment": "These shoes are both the mostly comfortable and the most stylish I have ever owned.",
              "name": "Person Personson",
              "rating": 4.5
            },
            {
              "comment": "These would be better if they were red. I suppose they aren't bad, but they aren't good either.",
              "name": "Second Person",
              "rating": 2.5
            },
            {
              "comment": "I've worn these for 3 years and they are still in great shape. I'm going to buy another pair. I think everyone should have a pair of these shoes in their closet.",
              "name": "Another Great Person",
              "rating": 4.5
            }
          ]
        }
      }
    ]
  }
}
```


The response now contains the 3 sample reviews that were included in Federate This.

## Commercetools remote source configuration

**Prerequisite:**
You need to have a [commercetools](https://commercetools.com/) account as well as [have a project set up](https://docs.commercetools.com/learning-model-your-business-structure/organizations-and-projects/projects).

### Get your commercetools keys

Before we start, there is some data we will need from your commercetools account:

Go to **Settings > Developer settings > API clients**. Click `+ Create new API client` to create one from scratch, give it a name and select the scopes you need for your project.

In our example we will select the `Project` scope under **Manage**. Click `Create API client` at the top-right of the screen.

The resulting screen contains the information you will need to configure your remote source. Save it for later, and let's continue with the process.

### Commercetools Remote Source

![Commercetools Remote Source](https://hygraph.com/images/docs/user-guides/remote-sources/commercetools-remote-source.png)

Navigate to the schema builder and click `+Add` next to **Remote Sources**. Use the following information to configure your remote source:

| Field              | Input                                                                                                                                                                                                                                                        |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Remote source type | Select **Commercetools**                                                                                                                                                                                                                                     |
| Authorization URL  | This is the **Auth URL** in the API client details view of your commercetools account. Instead of copying it directly from there, copy the URL on the first line of the cURL below. Paste that in the Authorization URL field of your Hygraph Remote Source. |
| Scopes             | This is the **Scope** in the API client details view of your commercetools account. Copy it and paste it in Hygraph, then click `+ Add scope` to add.                                                                                                        |
| Client ID          | This is the **client_id** key in the API client details view of your commercetools account. Copy it and paste it in Hygraph. This is like a username.                                                                                                        |
| Client Secret      | This is the **secret** key in the API client details view of your commercetools account. Copy it and paste it in Hygraph. This is like a password.                                                                                                           |
| Display name       | This  is the display name of your Remote Source, we will write "Commercetools" here.                                                                                                                                                                         |
| Prefix             | Completing the display name autocompletes the prefix, you can leave it as is.                                                                                                                                                                                |
| Type               | Select `GraphQL`                                                                                                                                                                                                                                             |
| Base URL           | To form the base URL, you will use the **API URL** and the **project_key** from the API client details view of your commercetools account, like this: `https://<COMMERCETOOLS_API_URL>/<PROJECT_KEY>/graphql`.                                               |

Click `Add Remote Source` at the bottom of the screen to save your Remote Source.

## Commercelayer remote source configuration

**Prerequisite:**
You need to have a [Commercelayer](https://dashboard.commercelayer.io/sign_up) account.

### Get your Commercelayer keys

Before we start, there is some data we will need from your Commercelayer account:

Go to **Applications > Add new**. Select a type, for this example we will select `Sales Channel`, give it a name, and click `Get credentials`.

The resulting screen contains the information you will need to configure your remote source. Save it and let's continue with the process.

### Commercelayer Remote Source

![Commercelayer Remote Source](https://hygraph.com/images/docs/user-guides/remote-sources/commercelayer-remote-source.png)

Navigate to the schema builder and click `+Add` next to **Remote Sources**. Use the following information to configure your remote source:

| Field              | Input                                                                                                                                                                               |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Remote source type | Select **Commercelayer**                                                                                                                                                            |
| Authorization URL  | Copy the **Base endpoint** in your Commercelayer credentials screen, paste it in Hygraph, and add `/oauth/token` at the end, like this: `https://<YOUR_BASE_ENDPOINT>/oauth/token`. |
| Scopes             | We won't add anything here for this example.                                                                                                                                        |
| Client ID          | Copy the **Client ID** in your Commercelayer credentials screen and paste it here.                                                                                                  |
| Client Secret      | We won't add anything here for this example.                                                                                                                                        |
| Display name       | This  is the display name of your Remote Source, we will write "Commercelayer" here.                                                                                                |
| Prefix             | Completing the display name autocompletes the prefix, you can leave it as is.                                                                                                       |
| Type               | Select `REST`                                                                                                                                                                       |
| Base URL           | Copy the **Base endpoint** in your Commercelayer credentials screen and paste it here.                                                                                              |

Click `Add Remote Source` at the bottom of the screen to save your Remote Source.

## Working with custom input types

In this example, we will see how we can define and use a custom input type on a Remote Field. We will be using the [Github REST API](https://docs.github.com/en/rest), specifically the `users` [endpoint](https://docs.github.com/en/rest/reference/users#list-users).

### Step 1: Configure Github as Remote Source

We'll first add the Github API as a Remote Source and configure the right custom (input) types.

Set up a new remote source. If you don't know how to do this, please [check out our documentation](https://hygraph.com/docs/developer-guides/remote-data/remote-sources), using `<Link href="https://api.github.com" target="_blank">https://api.github.com</Link>` as the base URL, then add a custom type with the following SDL:

```graphql
type User {
  avatar_url: String
  bio: String
  blog: String
  company: String
  created_at: DateTime
  email: String
  events_url: String
  followers: Int
  followers_url: String
  following: Int
  following_url: String
  gists_url: String
  gravatar_id: String
  hireable: Boolean
  html_url: String
  id: Int
  location: String
  login: String
  name: String
  node_id: String
  organizations_url: String
  public_gists: Int
  public_repos: Int
  received_events_url: String
  repos_url: String
  site_admin: Boolean
  starred_url: String
  subscriptions_url: String
  twitter_username: String
  type: String
  updated_at: DateTime
  url: String
}
```

Also add a custom _input_ type with the following SDL:

```graphql
input githubInput {
  userId: String!
}
```

### Step 2: Set up the Remote Field

In an appropriate model, set up a REST Remote Field. In this example, we will use a model called `Author` and set up the Remote Field with apiId `githubUserDetails`. In the Remote Field config, add an input argument and select the input type to be the previously created `githubInput`. In the example, we will use the auto-generated API ID `githubInput` for the input arguments. We'll also set the field to be required since we will make the path depend on the input value.

![Example - Input argument](https://hygraph.com/images/docs/user-guides/remote-sources/github-example-input-arg.png)

Now configure the Remote Field's path to use the input argument. You can use the autocomplete feature in the handlebars notation for this.

![Example - Remote Field path](https://hygraph.com/images/docs/user-guides/remote-sources/github-example-remote-field-path.png)

### Step 3: Query the field

Make sure there is at least one entry for the selected model, and then head over to the API Playground. The input argument can now be used in a query in the following way:

```graphql
query MyQuery {
  author(where: { id: "<some_id>" }) {
    id
    githubUserDetails(githubInput: { userId: "hygraph" }) {
      name
      bio
    }
  }
}
```

**Pro Tip:**
Please note that since we've made the `userId` parameter required in the custom input type (by adding a `!` at the end), there will be an error if we don't supply the value properly.

## Fetching a product catalog

This example shows a product content entry that fetches the product catalog from a Remote Source.

Besides the data that lives in Hygraph inside a regular model called `Product` - Product name, product description, etc - you can fetch a product catalog from an external API through a remote source that you added to the `Product` model as a Remote Field.

![Remote Field example](https://hygraph.com/images/docs/user-guides/remote-sources/example-remote-field.png)

Requests will return information in Hygraph - `Product` model - as well as information in the Remote Source, called `myCatalogue` in our `Product` model for this example.

  **Query**

```graphql
{
  products {
    id
    myCatalogue {
      id
      name
      slug
    }
  }
}
```

  
  **Response**

```graphql
{
  "data": {
    "products": [
      {
        "id": "clix9xjpu004n0btas02yx2ce",
        "myCatalogue": [
          {
            "id": "cl3jub4i9sl9o0eujar33f9rm",
            "name": "T Shirt",
            "slug": "t-shirt"
          },
          {
            "id": "cl3jub8gkslb90euj2n3ea357",
            "name": "Hoodie",
            "slug": "hoodie"
          }
        ]
      }
    ]
  }
}
```


The frontend could then use this information received through the Hygraph Content API to display the product page enriched with the product catalog.

## Add any REST source

This video tutorial covers adding a remote REST source into Hygraph.

[Video](https://www.youtube.com/watch?v=NpHSqsol3xc)

Tim shows us the two ways to query a REST remote source:

- Adding a global instance for the source, so we can query it from anywhere in our code.
- Using metadata to query from content editing in the CMS.

## Top-level Remote Fields

This example uses Top-level Remote Fields to show us a product information content entry that fetches the product catalogue from an external API, unrelated to Hygraph.

Besides the data that lives in Hygraph inside a regular model called **Product information** - `Slug`, `Title`, `Description` - you can fetch a product catalogue from an external API through a Remote Source that you add to the `Query` model as a Remote Field.

![Top-level Remote Field example](https://hygraph.com/images/docs/user-guides/remote-sources/example-top-level-remote-field.png)

Requests will return information in Hygraph - `Product` model- as well as information in the Remote Source, called `fieldremoteproduct` in our `Query` model for this example.

  **Query**

```graphql
{
  products {
    slug
    description
    title
  }
  fieldremoteproduct {
    slug
    name
  }
}
```

  
  **Response**

```graphql
{
  "data": {
    "products": [
      {
        "slug": "hoodie",
        "description": "Wrap yourself in cozy comfort with this stylish hoodie. Crafted from soft, premium materials, it offers a perfect blend of warmth and casual fashion. The versatile design features a kangaroo pocket for added convenience, while the adjustable drawstring hood adds an extra layer of coziness. Whether you're lounging at home or heading out for a casual outing, this hoodie is a must-have addition to your wardrobe.",
        "title": "Red Hoodie"
      }
    ],
    "fieldremoteproduct": [
      {
        "slug": "t-shirt",
        "name": "T Shirt"
      },
      {
        "slug": "hoodie",
        "name": "Hoodie"
      }
    ]
  }
}
```


The frontend could then use this information received through the Hygraph Content API to display the product page along with a product catalogue sourced from an external API.

## E-commerce platform

This video tutorial covers adding a remote source to Hygraph and creating Top-Level Remote Fields to pull in data from the external e-commerce platform, BigCommerce.

[Video](https://www.youtube.com/watch?v=08vg5eYdsDc)
