# Add remote data to your model

Add Remote Fields and Top-level remote fields to your project to fetch remote data.

## Overview

This document section explains how to add Remote Fields to models in your project. The flow is the same for [Remote Fields](https://hygraph.com/docs/developer-guides/remote-data/remote-field#remote-fields) added to regular models, and [Top-level Remote Fields](https://hygraph.com/docs/developer-guides/remote-data/remote-field#top-level-remote-fields).

**Pro Tip:**
If you don't know the difference between Remote Fields and Top-level Remote Fields, [check out this document](https://hygraph.com/docs/developer-guides/remote-data/remote-field).

## Add Remote Field

After [adding a Remote Source](https://hygraph.com/docs/developer-guides/remote-data/remote-sources), it's now time to add a Remote Field to a model. This is slightly different for RESTful remote sources vs. GraphQL Remote Sources, so we will explain this step for each of them separately.

**Before you add remote data:**
Remote Fields & Top-level Remote Fields can only be added [after at least one Remote Source of the corresponding type - REST or GraphQL - has been configured](https://hygraph.com/docs/developer-guides/remote-data/remote-sources).

### REST

First, select a Remote Field type:
- If you're adding a [Remote Field](https://hygraph.com/docs/developer-guides/remote-data/remote-field#remote-fields) to a regular model: Navigate to the **Schema builder**, select the model that will contain your Remote Field, scroll down the field type list located on the right side of the screen, and select the `REST` field.
- If you're adding a [Top-level Remote Field](https://hygraph.com/docs/developer-guides/remote-data/remote-field#top-level-remote-fields) to the `Query` model: Navigate to the `Query` model in your project schema, then select the `REST` field from the **Add fields** list located on the right side of the screen.

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

Then, follow these instructions:

1. In the **Create Field** dialog, fill in the `Display name`, `API ID`, and optionally add a `Description`.
2. If the remote API for this field returns an array of the chosen custom type instead of a single object, make sure to select the `Allow multiple values` checkbox, under **Field options**. For instance, if you defined your custom type to be `Product`, but the remote API returns an array of `products`, you need to make use of the `Allow multiple values` option, so the request won't return an error.
3. Select a previously configured `Remote Source` and an `HTTP Method` using the dropdowns. For `Return type`, select one of the custom types that you configured for the Remote Source. This custom type needs to (partially) match with the response of the API path that will be requested in this field. You can find detailed information on creating custom types [here](https://hygraph.com/docs/developer-guides/remote-data/remote-sources#create-a-custom-type-definition). Alternatively, it's possible to set the response to be a scalar type (string, Boolean, JSON, etc).

        [Click here to learn how to use a custom type definition.](https://hygraph.com/docs/developer-guides/remote-data/remote-content#how-to-use-a-custom-type-definition)

        **Remember:**
        Adding a [Remote Source](https://hygraph.com/docs/developer-guides/remote-data/remote-sources) to your project is a prerequisite in order to add a remote field to a model.

        [Defining your custom types](https://hygraph.com/docs/developer-guides/remote-data/remote-sources#create-a-custom-type-definition) is the step of remote source configuration where you specify the shape of the response coming from a `REST` API. It's what allows you to query the `REST` API as if it were native `GraphQL`. These Custom Type Definitions use `GraphQL SDL` (Schema Definition Language).
        
4. You can optionally add `Input arguments`. You can add an input argument by selecting a custom input type for the Remote Source and providing an `API ID` for the inputs, which can be used in the configuration of the `URL Path`. Multiple input arguments can be added by clicking `+Add`.

        [Click here to learn how to use a custom input type definition.](https://hygraph.com/docs/developer-guides/remote-data/remote-content#how-to-use-a-custom-input-type-definition)

        **Would you like to know more?:**
        [Here's an example of working with custom input types.](https://hygraph.com/docs/developer-guides/remote-data/remote-data-examples#working-with-custom-input-types)
        [Defining your custom types](https://hygraph.com/docs/developer-guides/remote-data/remote-sources#create-a-custom-type-definition) is the step of remote source configuration where you specify the shape of the response coming from a `REST` API. It's what allows you to query the `REST` API as if it were native `GraphQL`. These Custom Type Definitions use `GraphQL SDL` (Schema Definition Language).
        
5. Configure the `Path` that will be queried for this Remote Field. This path will be added to the Remote Source base path to get a resulting endpoint. In the path definition, you can use handlebars notation (start by typing a `{`) to use fields from the document or from the input arguments, if defined. This way, you can dynamically build a URL path using field values from the same content model or from an input parameter value. As an example, if the model has a field called `userId` , it's possible to build a path that looks like this: `/users/{{doc.userId}}/`repos.

**Pro Tip:**
You can make it possible for Editors to select the input arguments.

Imagine you've just configured a REST remote source where you added an input type definition called "articles", and want your Editors to be able to select the content entries of a specific user. What you'd do here, is add a single line field field, let's call it `username`, and then add your REST remote field, which we'll call `articles` for this example.

We'd follow the same steps that we explained above for the `Remote source`, `Method` and `Return type`.

We won't add an `Input argument` here. Instead we'll go to `Path`, and at the end of the URL path that we type in, we'll write `doc` to indicate that we're referencing the document we're editing, and select `{{doc.username}}`, where `username` corresponds to the field that we added before as an input.

What we just did is add a REST Remote Field to our model in a way it can use metadata from a document to query it.

In this example, what Editors would do is simply input a `username` in the content entry, and this would result in only `articles` from that `username` being fetched in a query.

Would you like to see this more in depth? [Check out Tim's video](https://hygraph.com/docs/developer-guides/remote-data/remote-data-examples#add-any-rest-source).

### GraphQL

**Feature availability:**
At the moment, **Hygraph Studio** does not support this feature.

First, select a Remote Field type:
- If you're adding a [Remote Field](https://hygraph.com/docs/developer-guides/remote-data/remote-field#remote-fields) to a regular model: Navigate to the **Schema builder**, select the model that will contain your Remote Field, scroll down the field type list located on the right side of the screen, and select the `REST` field.
- If you're adding a [Top-level Remote Field](https://hygraph.com/docs/developer-guides/remote-data/remote-field#top-level-remote-fields) to the `Query` model: Navigate to the `Query` model in your project schema, then select the `REST` field from the **Add fields** list located on the right side of the screen.

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

Then, follow these instructions:

1. In the `Create Field` dialog, fill in `Display name`, `API ID`, and optionally add a `Description`.
2. Select a previously configured `Remote Source` and an HTTP `Method`.
3. You can **optionally** add `Input arguments`. You can add an input argument by selecting a `custom input type` for the remote source, and providing an `API ID` for the inputs, which can be used in the configuration of the URL `Path`. Multiple input arguments can be added by clicking on `+Add`.

        [Click here to learn how to use a custom input type definition](https://hygraph.com/docs/developer-guides/remote-data/remote-content#how-to-use-a-custom-input-type-definition).

        **Would you like to know more?:**
        [Here's an example on working with custom input types](https://hygraph.com/docs/developer-guides/remote-data/remote-data-examples#working-with-custom-input-types).

4. Now select the `Query` that will be the entry point into the remote schema from the tree that is shown at the bottom of the `Create Field` dialog. This tree is populated using introspection, and will show all available queries in the Remote Source.

        - When selecting a query, the tree unfolds to show all `arguments` for that query (in purple), available `sub-queries` (enabled and showing type in blue), and available `fields` or `scalars` (disabled and showing with type in grey). It's important to note that the selected (sub)query will determine which data from the remote source can be queried through Hygraph. **All arguments, scalars, and subqueries in the Remote Source that are below the selected query will be queryable**. Other values and queries in the tree will _not_ be queryable unless they are part of another Remote Field.
        - Arguments that are required show a purple asterisk (\*) next to their ID, although there is no validation on the value done inside Hygraph. It's possible to use handlebars notation inside a parameter field. Start by typing `{`, which will bring up suggestions based on the fields on your model.

            ![GraphQL query selection](https://hygraph.com/images/docs/user-guides/remote-sources/graphql-query-selection.png)

        - For queries that return a single value, it's also possible to select a sub-query as the entry point. **Note that this means that only fields inside the selected sub-query are available to be queried through Hygraph.**

## How to use a custom type definition

[After successfully defining the custom type for your remote source](https://hygraph.com/docs/developer-guides/remote-data/remote-sources#create-a-custom-type-definition), it can be used on your Remote Field (REST).

1. Open any of your models and either create a new Remote Field (REST) from the right hand field picker or edit an existing Remote Field (REST). On that Remote Field, select the just created custom type under Return type.

    ![Using a custom type definition](https://hygraph.com/images/docs/user-guides/remote-sources/using-custom-type-definition.png)

2. When querying your Remote Field, you will now have a sub-selection of the fields you defined. In this case, the Remote Field is called `githubInfo`

   ```graphql
   {
     authors {
       id
       name
       githubInfo {
         id
         name
         url
       }
     }
   }
   ```

## How to use a custom input type definition

1. On your Remote Field, you can now select the [custom input type you defined for your remote source](https://hygraph.com/docs/developer-guides/remote-data/remote-sources#create-a-custom-input-type-definition) as an `Input Argument`. For this, open one of your models and add a new Remote Field or edit an existing one.
2. Click on `+Add` under `Input arguments`, select the input type you just created, and give it an API ID.

   ![Using a custom input type definition](https://hygraph.com/images/docs/user-guides/remote-sources/using-custom-input.png)

3. After saving the field, you can head into the API Playground and test the just created input argument, which will work like this:

    ```graphql
    {
      pages {
        id
        product(product: { productId: "123" }) {
          name
          slug
          price
        }
      }
    }
    ```

## Advanced settings (Cache)

**Note:**
Advanced settings apply to both types of Remote Fields.

1. Although `HTTP` headers can be configured on a **Remote Source** - meaning on all requests for all fields that use this remote source - it's also possible to add additional `HTTP` headers on a specific **Remote Field**. The headers are additive, but if you configure the same header both on the field and on the remote source, the value from the Remote Field will take precedence. Additionally, it's possible to have all client headers to Hygraph forwarded to the Remote Source. This can be useful to forward user context to the remote server, for example.
2. By default, Hygraph caches queries that include Remote Fields using a TTL cache with a value of 15 minutes. The TTL can be overridden in the Remote Field settings dialog (minimum TTL value is 60 seconds). However, please note that if the Remote Source sends a cache-control response header, this will override the cache configuration in Hygraph.
3. Optionally set field visibility. For the default setting of `read-only`, the Remote Field is displayed in the content form with a link to the API playground. If the field visibility is set to `API only`, the Remote Field is not displayed in the content form but is still available to query through the API.

## Query remote data

### Query Remote Fields

After configuring the Remote Field, it's added to the Hygraph schema and immediately queryable through the API. Press `CTRL/CMD+Space` or open the Explorer view to see the available sub-fields inside the Remote Field.

**Note:**
Note that the Remote Source prefix is added in front of the type for easy identification.

Below screenshots demonstrate what this looks like for the User endpoint of the Github API:

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

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

The following example fetches information from within a model:

  **Query**

```graphql
{
  products {
    slug
    fieldremoteproducts {
      id
      slug
    }
  }
}
```

  
  **Response**

```graphql
{
  "data": {
    "products": [
      {
        "slug": "hoodie",
        "fieldremoteproducts": {
          "id": "cl3jub8gkslb90euj2n3ea357",
          "slug": "hoodie"
        }
      }
    ]
  }
}
```


In this case, the Remote Field is related to the `Products` model, and it only fetches data related to it.

### Query Top Level Remote Fields

Top Level Remote Fields can be queried outside the context of a model.

In the following example, `product` is not a model, but a Top Level Remote Fields, completely unrelated to Hygraph content.

  **Query**

```graphql
{
  products {
    id
    slug
  }
}
```

  
  **Response**

```graphql
{
  "data": {
    "products": [
      {
        "id": "clilfku1s007r0bvoci5ho12i",
        "slug": "hoodie"
      }
    ]
  }
}
```


Instead of just enriching content that is in Hygraph, you can use the Hygraph API as a passthrough layer, where your frontend makes requests to APIs that don't relate to Hygraph.

With this [Content Federation](https://hygraph.com/docs/core-concepts/content-federation) feature, you can use Hygraph to pipe everything through to your frontend without the need of making two separate requests.

Let's compare this to fetching information from within a model:

  **Query**

```graphql
{
  products {
    slug
    fieldremoteproducts {
      id
      slug
    }
  }
}
```

  
  **Response**

```graphql
{
  "data": {
    "products": [
      {
        "slug": "hoodie",
        "fieldremoteproducts": {
          "id": "cl3jub8gkslb90euj2n3ea357",
          "slug": "hoodie"
        }
      }
    ]
  }
}
```


In this case, the Remote Field is related to the `Products` model, and it only fetches data related to it.
