Skip to main content
This guide shows how to query GraphQL endpoints using HttpClient from @injectivelabs/utils.

Setup

import { HttpClient } from '@injectivelabs/utils'

const client = new HttpClient('YOUR_GRAPHQL_ENDPOINT')

Authentication

If your GraphQL endpoint requires authentication, set the headers:
client.setConfig({
  headers: { 
    authorization: 'Bearer YOUR_API_KEY' 
  }
})

Making a Query

Structure your GraphQL query as a JSON string with query and optional variables:
const query = JSON.stringify({
  query: `
    query GetData($id: ID!) {
      entity(id: $id) {
        id
        name
        value
      }
    }
  `,
  variables: {
    id: '123'
  }
})

const response = await client.post<string, { data: { data: YourResponseType } }>('', query)

console.log(response.data.data)

Complete Example

import { HttpClient } from '@injectivelabs/utils'

interface Token {
  id: string
  symbol: string
  name: string
}

interface TokensResponse {
  tokens: Token[]
}

const client = new HttpClient('YOUR_GRAPHQL_ENDPOINT')

// Set auth headers if required
client.setConfig({
  headers: { 
    authorization: 'Bearer YOUR_API_KEY' 
  }
})

const query = JSON.stringify({
  query: `
    query GetTokens($first: Int!) {
      tokens(first: $first, orderBy: symbol) {
        id
        symbol
        name
      }
    }
  `,
  variables: {
    first: 10
  }
})

const response = await client.post<string, { data: { data: TokensResponse } }>('', query)

console.log(response.data.data.tokens)

Error Handling

GraphQL responses may contain errors even with a 200 status code. Always check for errors:
interface GraphQLResponse<T> {
  data?: T
  errors?: Array<{ message: string }>
}

const response = await client.post<string, { data: GraphQLResponse<YourResponseType> }>('', query)

if (response.data.errors && response.data.errors.length > 0) {
  throw new Error(response.data.errors[0].message)
}

const data = response.data.data