This guide shows how to query the Kadindexer GraphQL API from a Node.js script.
You’ll send GraphQL over HTTP using fetch
and authenticate with the x-api-key
header.
You can also subscribe to real-time data using WebSockets.
Use the HTTP endpoint for queries and mutations:
Network | API Endpoint |
---|---|
Mainnet | https://api.mainnet.kadindexer.io/v1 |
Testnet | https://api.testnet.kadindexer.io/v1 |
mkdir kadindexer-node && cd kadindexer-node
npm init -y
npm i dotenv
Create a .env
file:
KADINDEXER_HTTP=https://api.mainnet.kadindexer.io/v1
KADINDEXER_API_KEY=YOUR_API_KEY_HERE
Node v18+ is recommended (it includes native
fetch
).
Create index.js
:
require('dotenv').config();
/**
* Minimal GraphQL request using native fetch (Node 18+).
* @param {string} query
* @param {object} [variables]
*/
async function graphqlRequest(query, variables = {}) {
const res = await fetch(process.env.KADINDEXER_HTTP, {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-api-key': process.env.KADINDEXER_API_KEY,
},
body: JSON.stringify({ query, variables }),
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
const json = await res.json();
if (json.errors) {
throw new Error(`GraphQL errors: ${json.errors.map(e => e.message).join('; ')}`);
}
return json.data;
}
async function main() {
// Example 1: Simple query
const LAST_BLOCK_HEIGHT = `
query {
lastBlockHeight
}
`;
const heightData = await graphqlRequest(LAST_BLOCK_HEIGHT);
console.log('lastBlockHeight:', heightData.lastBlockHeight);
// Example 2: Query with variables (adjust to your schema)
const BLOCK_BY_HEIGHT = `
query BlockByHeight($height: Int!, $chainId: Int!) {
block(height: $height, chainId: $chainId) {
height
hash
chainId
timestamp
}
}
`;
const blockData = await graphqlRequest(BLOCK_BY_HEIGHT, {
height: heightData.lastBlockHeight,
chainId: 0,
});
console.log('block:', blockData.block);
}
main().catch(err => {
console.error(err);
process.exit(1);
});
Run it:
node index.js
To receive real-time updates from the indexer (like new blocks or events), you can use GraphQL subscriptions with WebSockets.
Here are the WebSocket endpoints for each network:
Network | WebSocket Endpoint |
---|---|
Mainnet | wss://mainnet01.kadindexer.io/graphql |
Testnet | wss://testnet04.kadindexer.io/graphql |
Install the required dependencies:
npm i graphql-ws ws
Create a file called subscribe.js
:
require('dotenv').config();
const { createClient } = require('graphql-ws');
const WebSocket = require('ws');
const client = createClient({
url: 'wss://mainnet01.kadindexer.io/graphql', // or use the testnet endpoint above
webSocketImpl: WebSocket,
connectionParams: {
headers: { 'x-api-key': process.env.KADINDEXER_API_KEY },
},
});
// Replace with a real subscription from your schema
const SUBSCRIPTION = `
subscription {
newBlock {
height
hash
}
}
`;
const dispose = client.subscribe(
{ query: SUBSCRIPTION },
{
next: (data) => console.log('event:', JSON.stringify(data)),
error: (err) => console.error('subscription error:', err),
complete: () => console.log('completed'),
}
);
// Stop after 60 seconds (optional)
setTimeout(() => dispose(), 60_000);
Run the subscription script:
node subscribe.js