Integrations
GraphQL integrations are widely supported in popular programming languages and frameworks. Here we present some guidance for getting started with integrating your subgraph into a range of popular languages.
NET (C#)
NuGet Packages: GraphQL.Client for .NET can be used to send queries to any GraphQL endpoint.
Sample C# code.
using GraphQL;
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;
public async Task QuerySubgraph()
{
var graphQLClient = new GraphQLHttpClient("https://YOUR_SUBGRAPH_ENDPOINT",
new NewtonsoftJsonSerializer());
var request = new GraphQLRequest
{
Query = @"
query {
users(first: 10) {
id
stakes {
id
amount
}
transactions {
id
hash
}
}
}"
};
var response = await graphQLClient.SendQueryAsync<dynamic>(request);
var data = response.Data;
// Process `data` as needed
}
Python
Recommended Libraries:
requests (simple HTTP library)
gql (GraphQL client for Python)
Sample Python Code (with requests):
import requests
def query_subgraph():
url = "https://YOUR_SUBGRAPH_ENDPOINT"
query = """
query {
dlp(id: "6") {
id
name
totals {
id
stakeCount
fileContributions
}
}
}
"""
response = requests.post(url, json={'query': query})
data = response.json()
print(data)
Rust
Recommended Crates:
Sample Rust Code:
use graphql_client::{GraphQLQuery, Response};
use reqwest;
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "schema.graphql",
query_path = "query_file.graphql",
response_derives = "Debug"
)]
struct GetUsers;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let variables = get_users::Variables {};
let client = reqwest::Client::new();
let res = client
.post("https://YOUR_SUBGRAPH_ENDPOINT")
.json(&GetUsers::build_query(variables))
.send()
.await?
.json::<Response<get_users::ResponseData>>()
.await?;
if let Some(data) = res.data {
println!("{:?}", data);
}
Ok(())
}
(You would need to create a corresponding query_file.graphql and schema.graphql for compile-time generation, or just do a raw HTTP POST similarly to Python.)
Java (or Kotlin)
Recommended Libraries:
Apollo Kotlin (works well on both JVM and Android).
OkHttp with manual JSON handling for a simpler approach.
Sample Java (OkHttp) Code:
import okhttp3.*;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
String query = "{ users(first: 10) { id stakes { id amount } } }";
JSONObject json = new JSONObject();
json.put("query", query);
RequestBody body = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
);
Request request = new Request.Builder()
.url("https://YOUR_SUBGRAPH_ENDPOINT")
.post(body)
.build();
Response response = client.newCall(request).execute();
JSONObject data = new JSONObject(response.body().string());
System.out.println(data.toString(2));
}
}
Go
Recommended Libraries:
machinebox/graphql
Or just use the standard net/http and encoding/json libraries.
Sample Go Code:
package main
import (
"context"
"fmt"
"github.com/machinebox/graphql"
)
func main() {
client := graphql.NewClient("https://YOUR_SUBGRAPH_ENDPOINT")
req := graphql.NewRequest(`
query {
exampleEntities(first: 5, orderBy: value, orderDirection: desc) {
id
value
timestamp
}
}
`)
// Set headers if needed (e.g., auth tokens)
// req.Header.Set("Authorization", "Bearer YOUR_TOKEN")
ctx := context.Background()
var respData map[string]interface{}
if err := client.Run(ctx, req, &respData); err != nil {
panic(err)
}
fmt.Printf("%+v\n", respData)
}
JavaScript
Using fetch (Browser or Node.js)
Sample Javascript Code:
async function querySubgraph() {
const url = 'https://YOUR_SUBGRAPH_ENDPOINT';
const query = `
query {
users(first: 10) {
id
stakes {
id
amount
}
transactions {
id
hash
}
}
}
`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query }),
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log('Subgraph response:', data);
}
// Run the function (Node.js example, ensuring you have a fetch polyfill if needed)
querySubgraph().catch(console.error);
Updated 18 days ago