Interrogation à partir d'une application
Reading time: 4 min
Learn how to query The Graph from your application.
Once a subgraph is deployed to or , you will be given the endpoint for your GraphQL API that should look something like this:
https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>
https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>
With your GraphQL endpoint, you can use various GraphQL Client libraries to query the subgraph and populate your app with data indexed by the subgraph.
The Graph is providing its own GraphQL client, graph-client
that supports unique features such as:
- Gestion des subgraphs inter-chaînes : interrogation à partir de plusieurs subgraphs en une seule requête
- Résultat entièrement typé
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.
Let's look at how to fetch data from a subgraph with graph-client
:
Install The Graph Client CLI in your project:
yarn add -D @graphprotocol/client-cli# or, with NPM:npm install --save-dev @graphprotocol/client-cli
Définissez votre requête dans un fichier .graphql
(ou dans votre fichier .js
ou .ts
) :
query ExampleQuery {# celle-ci provient de compound-v2markets(first: 7) {borrowRatecashcollateralFactor}# celle-ci provient de uniswap-v2pair(id: "0x00004ee988665cdda9a1080d5792cecd16dc1220") {idtoken0 {idsymbolname}token1 {idsymbolname}}}
Create a configuration file (called .graphclientrc.yml
) and point to your GraphQL endpoints provided by The Graph, for example:
# .graphclientrc.ymlsources:- name: uniswapv2handler:graphql:endpoint: https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2- name: compoundv2handler:graphql:endpoint: https://api.thegraph.com/subgraphs/name/graphprotocol/compound-v2documents:- ./src/example-query.graphql
Run the following The Graph Client CLI command to generate typed and ready to use JavaScript code:
graphclient build
Update your .ts
file to use the generated typed GraphQL documents:
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>)}
Important Note: graph-client
is perfectly integrated with other GraphQL clients such as Apollo client, URQL, or React Query; you can . 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.
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
Let's look at how to fetch data from a subgraph with Apollo client:
Install @apollo/client
and graphql
:
npm install @apollo/client graphql
Query the API with the following code:
import { ApolloClient, InMemoryCache, gql } from '@apollo/client'const APIURL = 'https://api.studio.thegraph.com/query//<SUBGRAPH_NAME>/'const tokensQuery = `query {tokens {idtokenIDcontentURImetadataURI}}`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)})
Pour utiliser des variables, vous pouvez transmettre un argument variables
à la requête :
const tokensQuery = `query($first: Int, $orderBy: BigInt, $orderDirection: String) {tokens(first: $first, orderBy: $orderBy, orderDirection: $orderDirection) {idtokenIDcontentURImetadataURI}}`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)})
is available within Node.js, React/Preact, Vue, and Svelte environments, with some more advanced features:
- Système de cache flexible
- Conception extensible (facilitant l’ajout de nouvelles fonctionnalités par-dessus)
- Offre légère (~ 5 fois plus légère que Apollo Client)
- Prise en charge des téléchargements de fichiers et du mode hors ligne
Let's look at how to fetch data from a subgraph with URQL:
Install urql
and graphql
:
npm install urql graphql
Query the API with the following code:
import { createClient } from 'urql'const APIURL = 'https://api.thegraph.com/subgraphs/name/username/subgraphname'const tokensQuery = `query {tokens {idtokenIDcontentURImetadataURI}}`const client = createClient({url: APIURL,})const data = await client.query(tokensQuery).toPromise()