Using Subgraphs

Last modified:

Quick Start

  1. Create an API key in The Graph Studio
  2. Pick a deployment ID from Subgraph Overview
  3. Query with:
https://gateway.thegraph.com/api/<YOUR_API_KEY>/subgraphs/id/<SUBGRAPH_ID>

Minimal Query (curl)

curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"query":"{ factory(id:\"0x1F98431c8aD98523631AE4a59f267346ea31F984\"){ poolCount txCount totalVolumeUSD } }"}' \
  "https://gateway.thegraph.com/api/<YOUR_API_KEY>/subgraphs/id/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV"

JavaScript Example

const endpoint =
  'https://gateway.thegraph.com/api/<YOUR_API_KEY>/subgraphs/id/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV'
 
const query = `
  query TopPools {
    pools(first: 5, orderBy: totalValueLockedUSD, orderDirection: desc) {
      id
      feeTier
      token0 { symbol }
      token1 { symbol }
      totalValueLockedUSD
    }
  }
`
 
const res = await fetch(endpoint, {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ query }),
})
 
const { data, errors } = await res.json()
if (errors) throw new Error(JSON.stringify(errors))
console.log(data.pools)

Query Patterns That Matter

  • Pagination: use first + skip (max first is 1000)
  • Historical snapshots: pass block: { number: <block> }
  • Time series: query daily/hourly entities (poolDayDatas, poolHourDatas, tokenDayDatas)
  • Address handling: lowercase IDs in filters for consistent results

Production Notes

  • Public deployments can change; pin your exact subgraph ID in config.
  • Validate schema changes before deploys to avoid runtime query failures.
  • Prefer persisted queries or shared query documents in your app for consistency.
  • For high-reliability workloads, run your own deployment strategy and monitor indexing health.

Next Reading