Docs
Search⌘ K
  • Home
  • About The Graph
  • Supported Networks
  • Protocol Contracts
  • Subgraphs
    • Substreams
      • Indexer Software
        • Gateway Software
          • Data Services
            • AI Tooling
            • Resources
              Subgraphs > Querying

              5 minutes

              Querying from an Application

              This guide covers how to query The Graph from your application.

              Getting GraphQL Endpoints

              Your application sends queries to a gateway endpoint. Each Gateway Operator has its own endpoint format and issues its own API keys. While examples on this page use The Graph Foundation’s Gateway, multiple Gateway Operators can serve every published Subgraph, so you can query through any of them without republishing.

              Production Endpoint

              After you publish your Subgraph, query it through a gateway. For The Graph Foundation’s Gateway, the endpoint looks like this, with an API key from Subgraph Studio:

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

              You can use this endpoint with the GraphQL client libraries below. With another Gateway Operator, use that operator’s endpoint and API key with the same Subgraph ID.

              Subgraph Studio Development Endpoint

              Before you publish, you can test against a staging endpoint. For example, after you deploy a Subgraph to Subgraph Studio, you get an endpoint like this:

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

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

              For other ways to test before publishing, see Testing and Staging.

              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⁠
              • Automatic Pagination⁠
              • 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:

              1yarn add -D @graphprotocol/client-cli2# or, with NPM:3npm install --save-dev @graphprotocol/client-cli

              Step 2

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

              1query ExampleQuery {2  # this one is coming from compound-v23  markets(first: 7) {4    borrowRate5    cash6    collateralFactor7  }8  # this one is coming from uniswap-v29  pair(id: "0x00004ee988665cdda9a1080d5792cecd16dc1220") {10    id11    token0 {12      id13      symbol14      name15    }16    token1 {17      id18      symbol19      name20    }21  }22}

              Step 3

              Create a configuration file (called .graphclientrc.yml) and point to your Subgraphs’ gateway endpoints. This example uses The Graph Foundation’s Gateway:

              1# .graphclientrc.yml2sources:3  - name: uniswapv24    handler:5      graphql:6        endpoint: https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>7  - name: compoundv28    handler:9      graphql:10        endpoint: https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>1112documents:13  - ./src/example-query.graphql

              Step 4

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

              1graphclient build

              Step 5

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

              1import React, { useEffect } from 'react'2// ...3// we import types and typed-graphql document from the generated code (`..graphclient/`)4import { ExampleQueryDocument, ExampleQueryQuery, execute } from '../.graphclient'56function App() {7  const [data, setData] = React.useState<ExampleQueryQuery>()89  useEffect(() => {10    execute(ExampleQueryDocument, {}).then((result) => {11      setData(result?.data)12    })13  }, [setData])14  return (15    <div className="App">16      <header className="App-header">17        <img src={logo} className="App-logo" alt="logo" />18        <p>Graph Client Example</p>19        <fieldset>20          {data && (21            <form>22              <label>Data</label>23              <br />24              <textarea value={JSON.stringify(data, null, 2)} readOnly rows={25} />25            </form>26          )}27        </fieldset>28      </header>29    </div>30  )31}3233export 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⁠. 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⁠ 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:

              1npm install @apollo/client graphql

              Step 2

              Query the API with the following code:

              1import { ApolloClient, InMemoryCache, gql } from '@apollo/client'23const APIURL = 'https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>'45const tokensQuery = `6  query {7    tokens {8      id9      tokenID10      contentURI11      metadataURI12    }13  }14`1516const client = new ApolloClient({17  uri: APIURL,18  cache: new InMemoryCache(),19})2021client22  .query({23    query: gql(tokensQuery),24  })25  .then((data) => console.log('Subgraph data: ', data))26  .catch((err) => {27    console.log('Error fetching data: ', err)28  })

              Step 3

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

              1const tokensQuery = `2  query($first: Int, $orderBy: BigInt, $orderDirection: String) {3    tokens(4      first: $first, orderBy: $orderBy, orderDirection: $orderDirection5    ) {6      id7      tokenID8      contentURI9      metadataURI10    }11  }12`1314client15  .query({16    query: gql(tokensQuery),17    variables: {18      first: 10,19      orderBy: 'createdAtTimestamp',20      orderDirection: 'desc',21    },22  })23  .then((data) => console.log('Subgraph data: ', data))24  .catch((err) => {25    console.log('Error fetching data: ', err)26  })

              URQL Overview

              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:

              1npm install urql graphql

              Step 2

              Query the API with the following code:

              1import { createClient } from 'urql'23const APIURL = 'https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>'45const tokensQuery = `6  query {7    tokens {8      id9      tokenID10      contentURI11      metadataURI12    }13  }14`1516const client = createClient({17  url: APIURL,18})1920const data = await client.query(tokensQuery).toPromise()
              ⁠Edit on GitHub⁠

              Querying Best PracticesSubgraph vs Deployment IDs
              On this page
              • Getting GraphQL Endpoints
              • Production Endpoint
              • Subgraph Studio Development Endpoint
              • Using Popular GraphQL Clients
              • Graph Client
              • Fetch Data with Graph Client
              • Apollo Client
              • Fetch Data with Apollo Client
              • URQL Overview
              • Fetch data with URQL
              The GraphStatusTestnetBrand AssetsForumSecurityPrivacy PolicyTerms of Service