SDKs overview
The Graph facilitates the querying of blockchain data through a decentralized network and hosted services, primarily using GraphQL. To streamline developer interaction with this data, The Graph ecosystem provides several Software Development Kits (SDKs) and libraries. These tools abstract away the complexities of direct blockchain interaction and GraphQL query construction, allowing developers to integrate subgraph data into their applications more efficiently. The official SDKs focus on common programming environments, while the broader community contributes additional language bindings and utilities.
Developers typically use these SDKs to send GraphQL queries to a subgraph endpoint, receive structured data, and process it within their application logic. Subgraphs themselves define the data schema and indexing logic for specific smart contracts or blockchain protocols, providing a tailored API for on-chain data. The SDKs simplify this client-side consumption. For a comprehensive understanding of subgraph development, consult the official The Graph subgraph development guide.
Official SDKs by language
The Graph offers official support for SDKs that integrate seamlessly with its GraphQL endpoints. These SDKs are maintained by The Graph development team and are designed to provide stable and efficient access to subgraph data. The primary official SDKs cater to JavaScript/TypeScript and Python environments, reflecting their prevalence in web3 development.
The following table summarizes the key official SDKs:
| Language | Package/Integration | Typical Installation Command | Maturity & Focus |
|---|---|---|---|
| JavaScript/TypeScript | ethers.js (for contract interaction) and GraphQL clients (e.g., @apollo/client) |
npm install ethers @apollo/client graphql or yarn add ethers @apollo/client graphql |
Mature, widely used for frontend dApp development and backend services. Integrates with various GraphQL clients. |
| Python | web3.py (for contract interaction) combined with GraphQL request libraries (e.g., requests) |
pip install web3 requests |
Stable, suitable for backend services, scripting, and data analysis in Python environments. |
While ethers.js and web3.py are primarily for interacting with Ethereum smart contracts, they are often used in conjunction with a generic GraphQL client to query subgraphs. This modular approach allows developers to choose their preferred GraphQL client library (e.g., Apollo Client for JavaScript, requests for Python) while relying on these established libraries for any direct contract calls or wallet interactions necessary for their dApp.
Installation
Installation for The Graph's SDK ecosystem typically involves installing a GraphQL client library in your chosen programming language, alongside any blockchain interaction libraries if required. The specific commands vary based on the language and package manager.
JavaScript/TypeScript
For JavaScript and TypeScript projects, the most common approach involves using a GraphQL client like Apollo Client. This client handles sending GraphQL queries and managing the data cache.
npm install @apollo/client graphql # Using npm
# or
yarn add @apollo/client graphql # Using Yarn
If your application also needs to interact directly with smart contracts or wallets, you would typically install a library like ethers.js:
npm install ethers # Using npm
# or
yarn add ethers # Using Yarn
Python
For Python, a simple HTTP request library like requests can be used to send GraphQL queries. For direct blockchain interactions, web3.py is the standard.
pip install requests # For sending HTTP requests, including GraphQL
pip install web3 # For direct EVM smart contract interaction
Quickstart example
This quickstart demonstrates how to query a public subgraph endpoint (e.g., Uniswap v2) using both JavaScript/TypeScript and Python. The example retrieves recent token swaps, illustrating the basic pattern of constructing and sending a GraphQL query to a subgraph.
JavaScript/TypeScript Example (using Fetch API and Apollo Client)
This example shows how to set up an Apollo Client to query the Uniswap V2 Subgraph. Apollo Client provides advanced features like caching and normalized stores, making it suitable for complex frontend applications. For a more detailed guide on integrating Apollo Client, refer to the Apollo Client getting started documentation.
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2',
cache: new InMemoryCache(),
});
async function getRecentSwaps() {
const { data } = await client.query({
query: gql`
query {
swaps(first: 5, orderBy: timestamp, orderDirection: desc) {
id
timestamp
amount0In
amount0Out
amount1In
amount1Out
pair {
token0 {
symbol
}
token1 {
symbol
}
}
transaction {
id
}
}
}
`,
});
console.log('Recent Uniswap V2 Swaps:', data.swaps);
}
getRecentSwaps().catch(console.error);
This code initializes an Apollo Client pointing to the Uniswap V2 subgraph's hosted service endpoint. It then defines a GraphQL query to retrieve the 5 most recent swap events, ordered by timestamp in descending order. The results, including swap details and token symbols, are logged to the console. This pattern is adaptable for any public or private subgraph by changing the uri and the query string.
Python Example (using requests library)
This example demonstrates a direct HTTP POST request to the Uniswap V2 Subgraph using Python's requests library. This approach is suitable for scripts, backend services, or situations where a full-fledged GraphQL client is not necessary.
import requests
import json
SUBGRAPH_URL = 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2'
query = """
query {
swaps(first: 5, orderBy: timestamp, orderDirection: desc) {
id
timestamp
amount0In
amount0Out
amount1In
amount1Out
pair {
token0 {
symbol
}
token1 {
symbol
}
}
transaction {
id
}
}
}
"""
def get_recent_swaps():
headers = {'Content-Type': 'application/json'}
payload = {'query': query}
response = requests.post(SUBGRAPH_URL, headers=headers, data=json.dumps(payload))
if response.status_code == 200:
data = response.json()
print("Recent Uniswap V2 Swaps:")
for swap in data['data']['swaps']:
print(json.dumps(swap, indent=2))
else:
print(f"Error: {response.status_code} - {response.text}")
if __name__ == "__main__":
get_recent_swaps()
The Python script sends a JSON-encoded GraphQL query to the subgraph endpoint. It then parses the JSON response and prints the details of the recent swaps. This method offers flexibility for developers who prefer direct HTTP communication or need to integrate with existing Python-based systems. For detailed information on GraphQL query structure, refer to the official GraphQL documentation.
Community libraries
Beyond the officially supported SDKs, the broader developer community has created various libraries and tools that enhance interaction with The Graph. These community-driven projects often address specific use cases, provide language bindings for less common programming languages, or offer higher-level abstractions and utilities for subgraph development and consumption.
Examples of community contributions include:
- Subgraph event indexing tools: Libraries that help developers parse and index blockchain events into subgraphs more efficiently, sometimes providing alternative data source templates.
- Frontend integration helpers: Specialized React hooks or Vue components that simplify integrating subgraph data into user interfaces, often building on top of existing GraphQL clients.
- Code generators: Tools that automatically generate TypeScript types or data access methods from a subgraph's GraphQL schema, improving type safety and developer experience.
- Alternative language wrappers: While not officially supported, developers occasionally create wrappers or examples for languages like Go, Ruby, or Rust, demonstrating how to construct and send GraphQL queries to The Graph's endpoints. These typically involve using generic HTTP clients combined with JSON parsing.
- Testing utilities: Libraries that assist in testing subgraph mappings or client-side data consumption, enabling more robust dApp development.
Developers exploring community libraries should verify their maintenance status, compatibility with the latest Graph Network protocols, and adherence to security best practices. The official Graph documentation portal and community forums are good starting points for discovering and evaluating these additional resources.