接入教程
1. 访问The Graph官网注册账户
2. 使用Graph Studio创建子图定义数据索引规则
3. 部署子图到去中心化网络开始索引数据
4. 通过GraphQL端点查询已索引的区块链数据
5. 在DApp中集成API端点调用数据
使用Python查询The Graph数据
import requests
import json
# The Graph API端点 (示例)
url = 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2'
# GraphQL查询
query = """
{
pairs(first: ofive) {
id
token0 {
symbol
}
token1 {
symbol
}
}
}
"""
headers = {
'Content-Type': 'application/json',
}
payload = {
'query': query
}
# 发送请求
response = requests.post(url, headers=headers, data=json.dumps(payload))
data = response.json()
print(json.dumps(data, indent=2))
使用PHP集成The Graph API
<?php
// The Graph API端点 (示例)
$url = 'https://api.thegraph.com/subgraphs/name/aave/protocol-v2';
// GraphQL查询
$query = '{
borrows(first: 5) {
id
amount
timestamp
}
}';
$data = array('query' => $query);
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => json_encode($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo "请求失败";
} else {
$response = json_decode($result, true);
print_r($response);
}
?>
使用JavaScript从The Graph获取数据
// The Graph API端点 (示例)
const endpoint = 'https://api.thegraph.com/subgraphs/name/compound-finance/compound-v2';
// GraphQL查询
const query = `
{
markets(first: 5) {
id
symbol
totalSupply
}
}
`;
// 使用fetch发送请求
fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: query
})
})
.then(response => response.json())
.then(data => {
console.log('查询结果:', data);
})
.catch(error => {
console.error('请求错误:', error);
});
常见问题
The Graph API是否需要API密钥?
The Graph的公开子图查询通常不需要API密钥,可以直接访问其GraphQL端点。但对于需要更高查询频率或访问私有子图的情况,可能需要使用The Graph的去中心化服务并支付查询费用。
The Graph支持哪些区块链网络?
The Graph主要支持以太坊及其Layer 2解决方案(如Arbitrum、Optimism、Polygon),同时也支持其他EVM兼容链(如Avalanche、BNB Chain)以及非EVM链(如NEAR、Cosmos)。具体支持的网络可在其官方文档中查看。
如何创建自己的子图?
创建子图需要定义数据模式(Schema)、编写映射(Mapping)脚本来处理链上事件,并将子图部署到The Graph网络。建议从The Graph官方文档的教程开始,使用Graph CLI工具进行开发和测试。
Aitishiku.com