---
title: Querying from an Application
sidebarTitle: Querying from an App
---

Learn how to query The Graph from your application.

## Getting GraphQL Endpoints

During the development process, you will receive a GraphQL API endpoint at two different stages: one for testing in Subgraph Studio, and another for making queries to The Graph Network in production.

### Subgraph Studio Endpoint

After deploying your Subgraph to [Subgraph Studio](/subgraphs/developing/deploying-publishing/using-subgraph-studio/), you will receive an endpoint that looks like this:

```
https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>
```

> This endpoint is intended for testing purposes **only** and is rate-limited.

### The Graph Network Endpoint

After publishing your Subgraph to the network, you will receive an endpoint that looks like this: :

```
https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>
```

> This endpoint is intended for active use on the network. It allows you to use various GraphQL client libraries to query the Subgraph and populate your application with indexed data.

## Using Popular GraphQL Clients

### Graph Client

The Graph is providing its own GraphQL client, `graph-client` that supports unique features such as:

- Cross-chain Subgraph Handling: Querying from multiple Subgraphs in a single query
- [Automatic Block Tracking](https://github.com/graphprotocol/graph-client/blob/main/packages/block-tracking/README.md)
- [Automatic Pagination](https://github.com/graphprotocol/graph-client/blob/main/packages/auto-pagination/README.md)
- Fully typed result

> Note: `graph-client` is integrated with other popular GraphQL clients such as Apollo and URQL, which are compatible with environments such as React, Angular, Node.js, and React Native. As a result, using `graph-client` will provide you with an enhanced experience for working with The Graph.

### Fetch Data with Graph Client

Let's look at how to fetch data from a Subgraph with `graph-client`:

#### Step 1

Install The Graph Client CLI in your project:

```sh
yarn add -D @graphprotocol/client-cli
# or, with NPM:
npm install --save-dev @graphprotocol/client-cli
```

#### Step 2

Define your query in a `.graphql` file (or inlined in your `.js` or `.ts` file):

```graphql
query ExampleQuery {
  # this one is coming from compound-v2
  markets(first: 7) {
    borrowRate
    cash
    collateralFactor
  }
  # this one is coming from uniswap-v2
  pair(id: "0x00004ee988665cdda9a1080d5792cecd16dc1220") {
    id
    token0 {
      id
      symbol
      name
    }
    token1 {
      id
      symbol
      name
    }
  }
}
```

#### Step 3

Create a configuration file (called `.graphclientrc.yml`) and point to your GraphQL endpoints provided by The Graph, for example:

```yaml
# .graphclientrc.yml
sources:
  - name: uniswapv2
    handler:
      graphql:
        endpoint: https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>
  - name: compoundv2
    handler:
      graphql:
        endpoint: https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>

documents:
  - ./src/example-query.graphql
```

#### Step 4

Run the following The Graph Client CLI command to generate typed and ready to use JavaScript code:

```sh
graphclient build
```

#### Step 5

Update your `.ts` file to use the generated typed GraphQL documents:

```tsx
import React, { useEffect } from 'react'
// ...
// we import types and typed-graphql document from the generated code (`..graphclient/`)
import { ExampleQueryDocument, ExampleQueryQuery, execute } from '../.graphclient'

function App() {
  const [data, setData] = React.useState<ExampleQueryQuery>()

  useEffect(() => {
    execute(ExampleQueryDocument, {}).then((result) => {
      setData(result?.data)
    })
  }, [setData])
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>Graph Client Example</p>
        <fieldset>
          {data && (
            <form>
              <label>Data</label>
              <br />
              <textarea value={JSON.stringify(data, null, 2)} readOnly rows={25} />
            </form>
          )}
        </fieldset>
      </header>
    </div>
  )
}

export default App
```

> **Important Note:** `graph-client` is perfectly integrated with other GraphQL clients such as Apollo client, URQL, or React Query; you can [find examples in the official repository](https://github.com/graphprotocol/graph-client/tree/main/examples). However, if you choose to go with another client, keep in mind that **you won't be able to use Cross-chain Subgraph Handling or Automatic Pagination, which are core features for querying The Graph**.

### Apollo Client

[Apollo client](https://www.apollographql.com/docs/) is a common GraphQL client on front-end ecosystems. It's available for React, Angular, Vue, Ember, iOS, and Android.

Although it's the heaviest client, it has many features to build advanced UI on top of GraphQL:

- Advanced error handling
- Pagination
- Data prefetching
- Optimistic UI
- Local state management

### Fetch Data with Apollo Client

Let's look at how to fetch data from a Subgraph with Apollo client:

#### Step 1

Install `@apollo/client` and `graphql`:

```sh
npm install @apollo/client graphql
```

#### Step 2

Query the API with the following code:

```javascript
import { ApolloClient, InMemoryCache, gql } from '@apollo/client'

const APIURL = 'https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>'

const tokensQuery = `
  query {
    tokens {
      id
      tokenID
      contentURI
      metadataURI
    }
  }
`

const client = new ApolloClient({
  uri: APIURL,
  cache: new InMemoryCache(),
})

client
  .query({
    query: gql(tokensQuery),
  })
  .then((data) => console.log('Subgraph data: ', data))
  .catch((err) => {
    console.log('Error fetching data: ', err)
  })
```

#### Step 3

To use variables, you can pass in a `variables` argument to the query:

```javascript
const tokensQuery = `
  query($first: Int, $orderBy: BigInt, $orderDirection: String) {
    tokens(
      first: $first, orderBy: $orderBy, orderDirection: $orderDirection
    ) {
      id
      tokenID
      contentURI
      metadataURI
    }
  }
`

client
  .query({
    query: gql(tokensQuery),
    variables: {
      first: 10,
      orderBy: 'createdAtTimestamp',
      orderDirection: 'desc',
    },
  })
  .then((data) => console.log('Subgraph data: ', data))
  .catch((err) => {
    console.log('Error fetching data: ', err)
  })
```

### URQL Overview

[URQL](https://formidable.com/open-source/urql/) is available within Node.js, React/Preact, Vue, and Svelte environments, with some more advanced features:

- Flexible cache system
- Extensible design (easing adding new capabilities on top of it)
- Lightweight bundle (~5x lighter than Apollo Client)
- Support for file uploads and offline mode

### Fetch data with URQL

Let's look at how to fetch data from a Subgraph with URQL:

#### Step 1

Install `urql` and `graphql`:

```sh
npm install urql graphql
```

#### Step 2

Query the API with the following code:

```javascript
import { createClient } from 'urql'

const APIURL = 'https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>'

const tokensQuery = `
  query {
    tokens {
      id
      tokenID
      contentURI
      metadataURI
    }
  }
`

const client = createClient({
  url: APIURL,
})

const data = await client.query(tokensQuery).toPromise()
```
