4 minutes
Dotazování z aplikace
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, you will receive an endpoint that looks like this:
1https://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: :
1https://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
- Automatic Pagination
- Plně zadaný výsledekv
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
:
Krok 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
Krok 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}
Krok 3
Create a configuration file (called .graphclientrc.yml
) and point to your GraphQL endpoints provided by The Graph, for example:
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
- Stránkování
- 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:
Krok 1
Install @apollo/client
and graphql
:
1npm install @apollo/client graphql
Krok 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 })
Krok 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:
- Flexibilní systém mezipaměti
- Rozšiřitelný design (usnadňuje přidávání nových funkcí)
- Lehký svazek (~5x lehčí než Apollo Client)
- Podpora nahrávání souborů a režimu offline
Fetch data with URQL
Let’s look at how to fetch data from a Subgraph with URQL:
Krok 1
Install urql
and graphql
:
1npm install urql graphql
Krok 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()