SECTION 1: LEARNING OBJECTIVES

By the end of this lesson, you will be able to:

  • Define blockchain APIs and their role in application development.

  • Explain different API types (RPC, REST, WebSocket, GraphQL).

  • Understand the JSON-RPC specification and common methods.

  • Describe SDKs and libraries for blockchain interaction.

  • Differentiate between node APIs and provider APIs.

  • Identify integration patterns for blockchain applications.

  • Implement a blockchain API client simulation in Python.

  • Develop a framework for API selection and integration.


SECTION 2: WHAT ARE BLOCKCHAIN APIS?

2.1 Definition

Blockchain APIs are interfaces that allow applications to interact with blockchain networks. They provide standardised methods for querying blockchain data, submitting transactions, and managing accounts. APIs abstract the complexity of direct node communication, making blockchain development accessible to a wider range of developers.

2.2 Why APIs Matter

 
 
Reason Description
Abstraction Hide complexity of direct node communication.
Standardisation Provide consistent interfaces across different chains.
Accessibility Enable developers without deep blockchain expertise.
Reliability Managed infrastructure with high uptime guarantees.
Scalability Handle high volumes of requests efficiently.
Security Built-in authentication and rate limiting.

SECTION 3: TYPES OF BLOCKCHAIN APIS

3.1 JSON-RPC

JSON-RPC is the most common API protocol for blockchain interaction. It uses JSON for data encoding and supports remote procedure calls over HTTP or WebSocket.

Key JSON-RPC Methods (Ethereum):

 
 
Method Purpose Example
eth_blockNumber Get current block number {"method": "eth_blockNumber"}
eth_getBalance Get account balance {"method": "eth_getBalance", "params": ["0x...", "latest"]}
eth_sendTransaction Send a transaction {"method": "eth_sendTransaction", "params": [{...}]}
eth_call Execute a contract call {"method": "eth_call", "params": [{...}]}
eth_getLogs Get event logs {"method": "eth_getLogs", "params": [{...}]}
eth_gasPrice Get current gas price {"method": "eth_gasPrice"}

Example Request:

json
{
    "jsonrpc": "2.0",
    "method": "eth_getBalance",
    "params": ["0x742d35Cc6634C0532925a3b844Bc454e4438f44e", "latest"],
    "id": 1
}

3.2 REST APIs

Some blockchain services provide REST-style APIs for easier integration with traditional web applications.

REST API Benefits:

  • Familiar to most web developers

  • Simple authentication mechanisms

  • Stateless operations

  • Easy integration with existing systems

Example REST Endpoint:

text
GET /api/v2/address/0x742d35.../balance

3.3 WebSocket APIs

WebSocket APIs enable real-time, bidirectional communication between applications and blockchain nodes. They are essential for:

  • Real-time transaction monitoring

  • Event listening and notifications

  • Live price feeds

  • Streaming blockchain data

Use Cases:

  • DApp frontends updating in real-time

  • Trading applications with live data

  • Monitoring systems for transaction confirmations

3.4 GraphQL

GraphQL provides a flexible query language for blockchain data, allowing clients to request exactly the data they need.

Advantages:

  • Query exactly what you need (no over-fetching)

  • Single endpoint for all queries

  • Strongly typed schema

  • Real-time capabilities with subscriptions

3.5 API Comparison

 
 
API Type Protocol Use Case Real-time Complexity
JSON-RPC HTTP/WebSocket Core blockchain operations Yes Medium
REST HTTP Traditional web integration No Low
WebSocket WebSocket Real-time data streaming Yes Medium
GraphQL HTTP Flexible data queries Yes Medium-High

SECTION 4: SDKS AND LIBRARIES

4.1 Popular SDKs

 
 
SDK Language Chain Support Key Features
Web3.js JavaScript Ethereum, EVM chains Most popular, mature
Ethers.js JavaScript/TypeScript Ethereum, EVM chains Modern, TypeScript-first
Web3.py Python Ethereum, EVM chains Python integration
Viem TypeScript Ethereum, EVM chains Newer, modular
Solana Web3 JavaScript Solana Solana-specific
Cosmos SDK Go Cosmos ecosystem App-specific chains
Polkadot.js JavaScript Polkadot, Substrate Full Polkadot ecosystem

4.2 SDK Capabilities

Core Functions:

  • Account and key management

  • Transaction building and signing

  • Contract interaction (ABI encoding/decoding)

  • Querying blockchain state

  • Event listening

  • Wallet integration

Example (Conceptual):

javascript
// Web3.js example
const balance = await web3.eth.getBalance('0x742d35...');
console.log(`Balance: ${web3.utils.fromWei(balance, 'ether')} ETH`);

// Ethers.js example
const balance = await provider.getBalance('0x742d35...');
console.log(`Balance: ${ethers.formatEther(balance)} ETH`);

4.3 Provider Services

 
 
Provider Description Key Features
Infura Node-as-a-Service High reliability, archival data
Alchemy Developer platform Enhanced APIs, analytics
QuickNode High-performance nodes Low latency, custom builds
Chainstack Enterprise blockchain Multi-chain, compliance
Cloudflare Blockchain gateway Distributed, fast

SECTION 5: INTEGRATION PATTERNS

5.1 Common Integration Patterns

1. Direct Node Integration:

text
Application → Node API → Blockchain
  • Most control, highest complexity

  • Requires running own node

  • Best for: Enterprises, validators

2. Provider API Integration:

text
Application → Provider API → Provider Infrastructure → Blockchain
  • Simplified development

  • Managed infrastructure

  • Best for: Most DApps, startups

3. Hybrid Integration:

text
Application → Provider API (primary) + Direct Node (failover) → Blockchain
  • Reliability and control

  • Best for: Critical applications

4. SDK-Based Integration:

text
Application → SDK → Provider/Node → Blockchain
  • Abstracted, developer-friendly

  • Best for: Rapid development

5.2 Integration Considerations

 
 
Consideration Description Trade-offs
Latency Response time for requests Provider vs self-hosted
Reliability Uptime and availability Managed service vs own node
Cost API costs vs infrastructure costs Pay-as-you-go vs fixed
Rate Limits Request limitations Free tier vs enterprise
Data Freshness How up-to-date the data is Caching vs real-time
Security Key management, authentication Internal vs external APIs

5.3 Integration Architecture

text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    BLOCKCHAIN INTEGRATION ARCHITECTURE                      │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  User Application (Frontend)                                               │
│       │                                                                     │
│       v                                                                     │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    API GATEWAY / MIDDLEWARE                          │   │
│  │  • Authentication                                                     │   │
│  │  • Rate limiting                                                      │   │
│  │  • Request routing                                                    │   │
│  │  • Caching                                                          │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                    ┌───────────────┼───────────────┐                      │
│                    v               v               v                      │
│  ┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐        │
│  │  JSON-RPC API    │  │  REST API        │  │  WebSocket API   │        │
│  │  (Blockchain     │  │  (Business       │  │  (Real-time      │        │
│  │   Operations)    │  │   Logic)         │  │   Data)          │        │
│  └────────┬─────────┘  └────────┬─────────┘  └────────┬─────────┘        │
│           │                     │                     │                   │
│           v                     v                     v                   │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    BLOCKCHAIN NODE                                   │   │
│  │  • Connect to network                                                │   │
│  │  • Broadcast transactions                                            │   │
│  │  • Sync with peers                                                  │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    BLOCKCHAIN NETWORK                                │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

SECTION 6: IMPLEMENTATION IN PYTHON

python
# ===================================================================
# MODULE 4, LESSON 4: BLOCKCHAIN APIS AND INTEGRATION
# ===================================================================

import json
import hashlib
import time
import random
from typing import Dict, List, Optional, Any
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import warnings
warnings.filterwarnings('ignore')

print("="*70)
print("BLOCKCHAIN APIS AND INTEGRATION")
print("="*70)

# ----------------------------------------------------------------
# PART A: JSON-RPC SIMULATION
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART A: JSON-RPC API Simulation")
print("-"*60)

class JSONRPCNode:
    """
    Simulated JSON-RPC blockchain node.
    """
    def __init__(self):
        self.state = {
            'block_number': 1000000,
            'gas_price': 20000000000,  # 20 Gwei
            'chain_id': 1
        }
        self.accounts: Dict[str, float] = {}
        self.transactions: List[Dict] = []
        self.contracts: Dict[str, Dict] = {}
        self.request_log: List[Dict] = []
    
    def add_account(self, address: str, balance: float):
        self.accounts[address] = balance
    
    def handle_request(self, jsonrpc_request: Dict) -> Dict:
        """
        Handle a JSON-RPC request.
        """
        method = jsonrpc_request.get('method')
        params = jsonrpc_request.get('params', [])
        req_id = jsonrpc_request.get('id', 1)
        
        self.request_log.append({
            'method': method,
            'params': params,
            'timestamp': time.time()
        })
        
        if method == 'eth_blockNumber':
            result = hex(self.state['block_number'])
        
        elif method == 'eth_gasPrice':
            result = hex(self.state['gas_price'])
        
        elif method == 'eth_getBalance':
            address = params[0] if params else None
            balance = self.accounts.get(address, 0)
            result = hex(int(balance * 10**18))  # Convert to Wei
        
        elif method == 'eth_sendTransaction':
            tx = params[0] if params else {}
            tx_hash = hashlib.sha256(json.dumps(tx).encode()).hexdigest()[:16]
            self.transactions.append({
                'hash': tx_hash,
                'from': tx.get('from'),
                'to': tx.get('to'),
                'value': tx.get('value')
            })
            self.state['block_number'] += 1
            result = f"0x{tx_hash}"
        
        elif method == 'eth_call':
            result = "0x"
        
        elif method == 'eth_getLogs':
            result = []
        
        else:
            return {
                'jsonrpc': '2.0',
                'error': {'code': -32601, 'message': 'Method not found'},
                'id': req_id
            }
        
        return {
            'jsonrpc': '2.0',
            'result': result,
            'id': req_id
        }
    
    def get_metrics(self) -> Dict:
        return {
            'block_number': self.state['block_number'],
            'total_transactions': len(self.transactions),
            'total_requests': len(self.request_log)
        }

# Create node
node = JSONRPCNode()

# Add accounts
node.add_account('0xAlice', 100.5)
node.add_account('0xBob', 50.0)
node.add_account('0xCharlie', 200.0)

print("JSON-RPC Node Simulation:")
print(f"Block Number: {node.state['block_number']}")
print(f"Gas Price: {node.state['gas_price']} wei")

# Simulate requests
requests = [
    {'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1},
    {'jsonrpc': '2.0', 'method': 'eth_gasPrice', 'params': [], 'id': 2},
    {'jsonrpc': '2.0', 'method': 'eth_getBalance', 'params': ['0xAlice', 'latest'], 'id': 3},
    {'jsonrpc': '2.0', 'method': 'eth_sendTransaction', 'params': [{'from': '0xAlice', 'to': '0xBob', 'value': '0x1'}]},
    {'jsonrpc': '2.0', 'method': 'eth_getBalance', 'params': ['0xBob', 'latest'], 'id': 4}
]

print("\nProcessing JSON-RPC requests:")
for req in requests:
    response = node.handle_request(req)
    if 'error' in response:
        print(f"  Error: {response['error']['message']}")
    else:
        print(f"  {req['method']}: {response.get('result', 'N/A')}")

# Metrics
metrics = node.get_metrics()
print(f"\nNode Metrics:")
print(f"  Block Number: {metrics['block_number']}")
print(f"  Total Transactions: {metrics['total_transactions']}")
print(f"  Total API Requests: {metrics['total_requests']}")

# ----------------------------------------------------------------
# PART B: API TYPE COMPARISON
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART B: API Type Comparison")
print("-"*60)

api_data = {
    'API Type': ['JSON-RPC', 'REST', 'WebSocket', 'GraphQL'],
    'Protocol': ['HTTP/WS', 'HTTP', 'WebSocket', 'HTTP'],
    'Request Format': ['JSON', 'JSON/XML', 'JSON', 'GraphQL Query'],
    'Real-time': ['Yes (WebSocket)', 'No', 'Yes', 'Yes (Subscriptions)'],
    'Learning Curve': ['Medium', 'Low', 'Medium', 'Medium-High'],
    'Use Case': ['Core operations', 'Web integration', 'Live data', 'Flexible queries']
}

api_df = pd.DataFrame(api_data)
print(api_df.to_string(index=False))

# ----------------------------------------------------------------
# PART C: SDK COMPARISON
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART C: SDK Comparison")
print("-"*60)

sdk_data = {
    'SDK': ['Web3.js', 'Ethers.js', 'Web3.py', 'Viem', 'Solana Web3'],
    'Language': ['JavaScript', 'JavaScript/TS', 'Python', 'TypeScript', 'JavaScript'],
    'Ecosystem': ['Largest', 'Growing', 'Medium', 'Growing', 'Solana'],
    'Type Safety': ['Low', 'High', 'Medium', 'Very High', 'Medium'],
    'Documentation': ['Excellent', 'Excellent', 'Good', 'Good', 'Good']
}

sdk_df = pd.DataFrame(sdk_data)
print(sdk_df.to_string(index=False))

# ----------------------------------------------------------------
# PART D: INTEGRATION PATTERNS
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART D: Integration Pattern Comparison")
print("-"*60)

pattern_data = {
    'Pattern': ['Direct Node', 'Provider API', 'Hybrid', 'SDK-based'],
    'Complexity': ['High', 'Low', 'Medium', 'Low'],
    'Control': ['Full', 'Limited', 'Medium', 'Medium'],
    'Cost': ['High (infra)', 'Medium (API)', 'Medium-High', 'Low-Medium'],
    'Best For': ['Enterprises', 'DApps', 'Critical apps', 'Rapid dev']
}

pattern_df = pd.DataFrame(pattern_data)
print(pattern_df.to_string(index=False))

# ----------------------------------------------------------------
# PART E: SUMMARY AND RECOMMENDATIONS
# ----------------------------------------------------------------

print("\n" + "="*70)
print("PART E: Summary and Recommendations")
print("="*70)

print("""
Blockchain APIs and Integration – Key Takeaways:

1. APIs abstract blockchain complexity and enable application development.
2. API types: JSON-RPC (core ops), REST (web integration), WebSocket (real-time), GraphQL (flexible queries).
3. JSON-RPC is the most common protocol with standardised methods.
4. SDKs (Web3.js, Ethers.js, Web3.py) simplify development with language-native interfaces.
5. Provider services (Infura, Alchemy) offer managed infrastructure.
6. Integration patterns: direct node, provider API, hybrid, SDK-based.
7. Considerations: latency, reliability, cost, rate limits, data freshness.

API Selection Framework:
  - For core blockchain operations: JSON-RPC
  - For web applications: REST APIs
  - For real-time data: WebSocket
  - For flexible data queries: GraphQL
  - For rapid development: SDKs (Ethers.js recommended)
  - For production: Provider services with failover
  - For maximum control: Self-hosted nodes
""")