A blockchain API abstracts network interaction, providing HTTP methods to read state or submit transactions. Instead of running a full node (CPU/disk intensive), you make RPC calls to a hosted node. Trade-off: convenience vs. trust (you depend on the API provider).
Types of Blockchain APIs
Full node RPC (JSON-RPC)
Direct access to a blockchain node. Providers: Infura, Alchemy, QuickNode, AWS Blockchain.
Supported networks: Ethereum, Polygon, Arbitrum, Optimism, Solana, etc.
Example (Ethereum):
| // Get latest block POST https://mainnet.infura.io/v3/YOUR_API_KEY Content-Type: application/json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } Response: { "jsonrpc": "2.0", "result": "0x123abc", "id": 1 } |
Allows direct contract calls, transaction submission, and state queries.
Indexing APIs (REST)
Providers: Alchemy, The Graph, Etherscan. Pre-index and cache blockchain data for efficient querying.
Example (Alchemy Transfers API):
| GET https://eth-mainnet.g.alchemy.com/v2/demo?method=alchemy_getAssetTransfers&address=0x...&category=external Response: { "transfers": [ { "from": "0xabc...", "to": "0xdef...", "value": 1.5, "hash": "0x...", "blockNum": "0x123abc" } ] } |
Faster for complex queries (e.g., all transfers from an address) vs. raw JSON-RPC.
Specialized APIs
- NFT APIs: Alchemy, OpenSea. Query NFT ownership, metadata, floor prices.
- Token APIs: CoinGecko, CoinMarketCap. Historical prices, market cap, volume.
- ENS APIs: Resolve domain names (vitalik.eth) to addresses.
- Gas APIs: Estimate gas prices before submitting transactions.
Common Use Cases
Reading data
Get account balance:
| const { ethers } = require('ethers'); const provider = new ethers.providers.JsonRpcProvider( 'https://mainnet.infura.io/v3/YOUR_API_KEY' ); const balance = await provider.getBalance('0x1234...'); console.log(ethers.utils.formatEther(balance)); // Convert wei to ETH |
Call a smart contract:
| // ERC20 balanceOf const contract = new ethers.Contract( tokenAddress, ['function balanceOf(address) view returns (uint256)'], provider ); const balance = await contract.balanceOf('0x1234...'); console.log(balance.toString()); |
Writing data (submitting transactions)
Send Ether:
| const signer = new ethers.Wallet(privateKey, provider); const tx = await signer.sendTransaction({ to: '0xrecipient...', value: ethers.utils.parseEther('1.0') // 1 ETH }); const receipt = await tx.wait(); // Wait for confirmation console.log(receipt.hash); // Transaction hash |
Approve a token (delegate spending):
| const contract = new ethers.Contract( tokenAddress, ['function approve(address spender, uint256 amount) returns (bool)'], signer ); const tx = await contract.approve( spenderAddress, // DEX, contract, etc. ethers.utils.parseUnits('1000', 18) ); await tx.wait(); |
Complex interactions
Swap tokens via Uniswap (approve + swap):
| // 1. Approve Uniswap to spend your tokens const approveTx = await tokenContract.approve(uniswapRouter, amountIn); await approveTx.wait(); // 2. Submit swap transaction const swapTx = await router.swapExactTokensForTokens( amountIn, minAmountOut, // Slippage protection [tokenIn, tokenOut], // Token path recipientAddress, deadline ); await swapTx.wait(); |
Provider Comparison
| Provider | Networks | Free Tier | Rate Limits | Best For |
|---|---|---|---|---|
| Infura | Ethereum, Polygon, Arbitrum | 100k requests/day | Strict | Established projects, good uptime |
| Alchemy | Ethereum, Polygon, Arbitrum, Optimism, Solana | 300M compute units/month | Generous | Indexed queries, best developer experience |
| QuickNode | 20+ chains | 50M units/month | Per-chain | Multi-chain apps, competitive pricing |
| Etherscan API | Ethereum (and testnets) | Free (5 calls/sec) | 5 calls/sec | Block explorers, one-off queries |
Error Handling
Common errors:
- "Rate limit exceeded": Too many requests in short time. Implement exponential backoff (retry after 1s, 2s, 4s...).
- "Invalid API key": Check credentials.
- "Execution reverted": Smart contract failed (insufficient balance, invalid state). Check contract logic.
- "Out of gas": Gas estimate was low. Increase gasLimit.
Example with retry logic:
| async function fetchWithRetry(url, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { const response = await fetch(url); if (!response.ok) throw new Error(response.statusText); return await response.json(); } catch (error) { if (i < maxRetries - 1) { const delay = Math.pow(2, i) * 1000; // Exponential backoff await new Promise(resolve => setTimeout(resolve, delay)); } else { throw error; } } } } const data = await fetchWithRetry( 'https://api.example.com/data' ); |
Gas Estimation and Pricing
Before submitting a transaction, estimate gas cost to avoid overpaying or running out of gas.
| // Estimate gas for a transaction const gasEstimate = await provider.estimateGas({ to: contractAddress, data: contract.interface.encodeFunctionData('transfer', [recipientAddress, amount]) }); console.log(`Estimated gas: ${gasEstimate.toString()}`); // Get current gas price const feeData = await provider.getFeeData(); console.log(`Gas price (gwei): ${ethers.utils.formatUnits(feeData.gasPrice, 'gwei')}`); // Calculate total cost const cost = gasEstimate.mul(feeData.gasPrice); console.log(`Total cost (ETH): ${ethers.utils.formatEther(cost)}`); |
For Ethereum post-London (EIP-1559), use maxFeePerGas and maxPriorityFeePerGas instead of gasPrice for better fee control.
Security Best Practices
- Never expose private keys: Store in environment variables or hardware wallet. Never commit to Git.
- Use HTTPS only: Intercept HTTPS to inject malicious transactions.
- Validate contract addresses: Copy from official sources or ENS. Typos lead to loss of funds.
- Set slippage limits: In swaps, specify minAmountOut to avoid sandwich attacks (MEV).
- Monitor transaction status: Check confirmation count before considering a transaction final (101 blocks for safety).
Rate Limits and Optimization
Batch requests: Instead of 100 sequential API calls, batch into 10 calls with multi-call contracts (Multicall3 on most chains).
| // Multicall3 example: query 3 token balances in one call const multicall3 = new ethers.Contract( '0xcA11bde05977b3631167028862bE2a173976CA11', // Multicall3 address ['function aggregate3(tuple[](address,bytes) calls) returns (uint256,bytes[])'] ); const calls = [ { target: token1, callData: token1.interface.encodeFunctionData('balanceOf', [user]) }, { target: token2, callData: token2.interface.encodeFunctionData('balanceOf', [user]) }, { target: token3, callData: token3.interface.encodeFunctionData('balanceOf', [user]) } ]; const [, results] = await multicall3.aggregate3(calls); // All balances fetched in 1 API call |
Production Deployment Considerations
- Redundancy: Use multiple providers as fallback (Infura + Alchemy). If one goes down, switch to the other.
- Monitoring: Log API calls, errors, gas prices. Alert on anomalies.
- Caching: Cache read-only queries (account balance, past events). Only query when data is expected to change.
- Rate limit budget: Calculate daily/monthly API usage. Choose provider tier accordingly.
Summary
Blockchain APIs remove the need to run full nodes. Use JSON-RPC for direct access, indexing APIs for complex queries, and specialized APIs for specific data (NFTs, prices). Handle rate limits with exponential backoff. Estimate gas before submitting transactions. Protect private keys and validate all external data. For production, use multiple providers for redundancy.
Yes, Blockchain APIs are versatile and can be applied to various non-financial use cases, such as supply chain management and identity verification.
Ensure that API keys are securely stored and transmitted, and consider using authentication methods like OAuth for added security.
Yes, legal considerations may apply, especially regarding data privacy and compliance with local regulations. Consult legal experts to ensure compliance.
A Blockchain Wallet API is a set of tools and protocols that enable developers to interact with and manage blockchain wallets programmatically. It allows for tasks like creating wallets, sending and receiving cryptocurrencies, and accessing wallet balances through code.
Some examples of blockchain APIs include Coinbase for cryptocurrency transactions, EtherScan for accessing Ethereum blockchain data, and BlockCypher for building blockchain applications across multiple cryptocurrencies like Bitcoin and Ethereum

