:2026-03-01 14:42 点击:3
以太坊作为全球领先的智能合约平台和去中心化应用(DApps)的底层基础设施,其强大的功能离不开与外部世界的交互,而以太坊API(应用程序编程接口)正是实现这种交互的关键桥梁,它允许开发者通过编程方式访问以太坊网络的数据(如账户余额、交易历史、智能合约状态)和发送交易(如转账、调用合约函数),本文将为你提供一个清晰、实用的以太坊API使用教程,帮助你快速上手。
在开始之前,我们需要了解以太坊API的几种主要类型,它们各有优劣,适用于不同的场景:
JSON-RPC API:
WebSocket API:
第三方API服务 (如Infura, Alchemy, QuickNode):
在开始调用API之前,你需要准备以下几样东西:
以太坊节点访问:
--http 和 --http.addr "0.0.0.0" --http.port "8545" 参数)。http://localhost:8545。API调用工具:
web3.js 或 ethers.js,Python的 web3.py,这些库封装了底层API调用,使开发更便捷。以太坊钱包(可选,用于发送交易):
如果你需要发送交易(如转账),你需要一个包含ETH的钱包(如MetaMask),并导出私钥或助记词(注意:私钥极度敏感,切勿泄露!)。
我们以第三方服务(如Infura)为例,使用cURL命令来演示几个常用的JSON-RPC API调用。
假设你的Infura HTTP API端点是 https://mainnet.infura.io/v3/YOUR_PROJECT_ID。
获取最新区块号:
{
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": 1
}
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' https://mainnet.infura.io/v3/YOUR_PROJECT_ID
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x1a3f2e" // 十六进制区块号
}
获取指定地址的ETH余额:
{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": ["0x742d35Cc6634C0532925a3b844Bc454e4438f44e", "latest"],
"id": 1
}
params[0]:要查询的以太坊地址。params[1]:区块号或 "latest"(最新区块)、"pending"(待处理区块)。curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x742d35Cc6634C0532925a3b844Bc454e4438f44e","latest"],"id":1}' https://mainnet.infura.io/v3/YOUR_PROJECT_ID
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x1a05f200" // 十六进制余额,单位为Wei
}
发送交易(转账):
from, to, value, gas, gasPrice, nonce等参数的交易对象,并用发送者的私钥进行签名。eth_getTransactionCounteth_estimateGaseth_sendRawTransactioncurl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_sendRawTransaction","params":["0xSignedTransactionData..."],"id":1}' https://mainnet.infura.io/v3/YOUR_PROJECT_ID
手动构造JSON-RPC请求比较繁琐,使用Web3.js这样的库可以大大简化开发。
安装Web3.js:
npm install web3
示例代码:
const Web3 = require('web3');
// 连接到以太坊节点(使用Infura)
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_PROJECT_ID');
// 获取最新区块号
async function getLatestBlockNumber() {
try {
const blockNumber = await web3.eth.getBlockNumber();
console.log('Latest block number:', blockNumber);
} catch (error) {
console.error('Error fetching block number:', error);
}
}
// 获取地址余额
async function getBalance(address) {
try {
const balance = await web3.eth.getBalance(address);
console.log(`Balance of ${address}:`, web3.utils.fromWei(balance, 'ether'), 'ETH');
} catch (error) {
console.error('Error fetching balance:', error);
}
}
// 调用函数
getLatestBlockNumber();
getBalance('0x742d35Cc6634C0532925a3b844Bc454e
本文由用户投稿上传,若侵权请提供版权资料并联系删除!