🤖Tutorial: Querying the subgraph programatically

The previous tutorial covered the process of *constructing* a query that provides useful data, but what if you want to actually use it in a program?

This tutorial will cover what it looks like to take a query from the user-friendly tooling and use it directly in your application.

The following query (taken from the previous tutorial) will be used, and will display the most recent 100 liquidations within the protocol:

query queryLiquidations {
  liquidationEvents(orderBy: blockNumber, orderDirection: desc) {
    id
    underlyingSymbol
    underlyingRepayAmount
    to
    from
    cTokenSymbol
    blockNumber
    amount
    blockTime
  }
}

Interacting programmatically

To actually send requests you'll need to use the following URL (subgraphURL below):

https://api.thegraph.com/subgraphs/name/moonwell-fi/moonwell-moonbeam

Below are some reference implementations that should be helpful, if you'd like to see a language not listed here come request it in the discord!

// Query GraphQL from Javascript using the Axios library

const axios = require("axios")

const subgraphURL = 'https://api.thegraph.com/subgraphs/name/moonwell-fi/moonwell-moonbeam'
const query = `
  query queryLiquidations {
    liquidationEvents(orderBy: blockNumber, orderDirection: desc) {
      id
      underlyingSymbol
      underlyingRepayAmount
      to
      from
      cTokenSymbol
      blockNumber
      amount
      blockTime
    }
  }
`

async function fetchResults(){
  const result = await axios.post(
    subgraphURL,
    { "query": query }
  )
  // Do something with `result.data.liquidationEvents` here
  console.log(result.data)
}

// Kick off the fetchResults async function
fetchResults().then(() => {
  console.log("Done!")
})

Last updated