Learn the Basics of Ethereum JSON API in 5 Minutes

·

When faced with a Python environment where web3.py couldn't function, I discovered the power of Ethereum's JSON-RPC API—the foundation of all web3 libraries. Here's how you can master it in just 5 minutes.


Initial Setup

Start by configuring your connection variables:

import requests
import json
session = requests.Session()
url = "https://ropsten.infura.io/v3/YOUR_INFURA_KEY"
headers = {'Content-type': 'application/json'}

Pro Tip: Get your Infura API key here to connect to the Ethereum Ropsten Testnet.


Making Your First Request

Fetch the current gas price with a simple call:

data = {"jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id":1}
response = session.post(url, json=data, headers=headers)
if response.ok:
    gasPriceHex = response.json().get("result")
    gasPriceDecimal = int(gasPriceHex, 16)
else:
    print("Error occurred")

Key Insight: Method names and parameters align with Ethereum’s official documentation.


Fetching the Latest Block

Retrieve block data and examine transactions:

params = ["latest", False]  # False returns transaction hashes only
data = {"jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": params, "id": 1}
response = session.post(url, json=data, headers=headers)
if response.ok:
    block = response.json().get("result")
    transactions = block.get("transactions")

Note: Set fullTrx=True to get full transaction details.


Sending Transactions

Step 1: Create an Account

from web3 import Web3
w3 = Web3()
account = w3.eth.account.create('your_phrase_here')
address = account.address
pKey = account.privateKey

Step 2: Get Nonce

params = [address, "latest"]
data = {"jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": params, "id": 3}
response = session.post(url, json=data, headers=headers)
nonce = response.json().get("result") if response.ok else None

Step 3: Sign and Send Transaction

signed_txn = w3.eth.account.signTransaction({
    'to': '0x687422eEA2cB73B5d3e242bA5456b782919AFc85',
    'nonce': nonce,
    'gasPrice': gasPriceHex,
    'gas': 100000,
    'value': w3.toWei(0.5, 'ether'),
    'chainId': 3,  # Ropsten Network
}, pKey)

params = [signed_txn.rawTransaction.hex()]
data = {"jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": params, "id": 4}
session.post(url, json=data, headers=headers)

👉 Explore more Ethereum APIs for advanced use cases.


FAQs

1. What’s the difference between JSON-RPC and web3 libraries?

2. How do I handle errors in API responses?

3. Can I use this for mainnet transactions?


Key Takeaways

Full code available on GitHub.

👉 Master Ethereum development with curated tutorials and tools.