Before you go, check out these stories!

0
Hackernoon logoLearn the Basics of the Ethereum JSON API in 5 Minutes by@nschapeler

Learn the Basics of the Ethereum JSON API in 5 Minutes

Author profile picture

@nschapelerNicolas Schapeler

The other day I got myself in a situation where I needed to communicate with the Ethereum network using python in an environment where getting web3.py to work seemed pretty much impossible. Since I still needed to talk to the network, I resorted to using the JSON-RPC API provided by Ethereum, which all web3 libraries are built on top of. Turns out, it’s pretty interesting! So, let’s get started! 

Basic setup

First things first — let’s declare a few variables that will be helpful when sending requests later:

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

To keep things simple, we use an Infura Node to connect to the Ethereum Ropsten Testnet. You can get an API Key for that here

Your first Request

Let’s get our feet wet by fetching the current gas price of the network. We can do this by simply doing:

# Prepare the data we will send
data = {"jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id":1}
response = session.post(url, json=data, headers=headers)

# Check if response is valid
if response.ok:
    # Get result of the request and decode it to decimal
    gasPriceHex = response.json().get("result")
    gasPriceDecimal = int(gasPriceHex, 16)
else:
    # Handle Error
    print("Error occured")

How did I know what method to use and what parameters to send? It can all be found in the official Ethereum docs.


Getting the latest Block

Let’s try something a bit more interesting — let’s fetch the latest block and see what we can read from there!

# Set params and prepare data
blockNumber = "latest"
# Boolean indicating if we want the full transactions (True) or just their hashes (false)
fullTrx = False
params = [ blockNumber, fullTrx]
data = {"jsonrpc": "2.0", "method": "eth_getBlockByNumber","params": params, "id": 1}

response = session.post(url, json=data, headers=headers)

# Check if response is valid
if response.ok:
    # Get the block
    block = response.json().get("result")
    # Get the transactions contained in the block
    transactions = block.get("transactions")
else:
    # Handle Error

Let’s have a closer look at one of the transactions:

params = [transactions[0]]

data = {"jsonrpc": "2.0", "method": "eth_getTransactionByHash","params": params, "id": 3}

response = session.post(url, json=data, headers=headers)

if response.ok:
    transaction = response.json().get("result")
else:
    # Handle Error
    print("Error occured")

You’re probably starting to get the pattern of how these calls work, so let’s try something a little more advanced: 


Sending Transactions

First, let’s create a new account using the web3.py library and load it with some Ropsten ether. I like to use this faucet.

import web3
w3 = web3.Web3()
account = w3.eth.account.create('put any phrase here')
address = account.address
pKey = account.privateKey

To send create a transaction, we need the nonce. This too we can fetch with the RPC JSON API using the same pattern as above:

# Get the nonce at the latest block
params = [address, "latest"]

data = {"jsonrpc": "2.0", "method": "eth_getTransactionCount","params": params, "id": 3}

response = session.post(url, json=data, headers=headers)

if response.ok:
    nonce = response.json().get("result")
else:
    # Handle Error
    print("Error occured")

Next, we create and sign our transaction and send it off using the JSON RPC API once more:

# Create our transaction
signed_txn = w3.eth.account.signTransaction({
    # Faucet address
    'to': '0x687422eEA2cB73B5d3e242bA5456b782919AFc85',
    'nonce': nonce,
    'gasPrice': gasPriceHex, 
    'gas': 100000,
    'value': w3.toWei(0.5,'ether'),
    # 3 Because we are on Ropsten
    'chainId':3,
    },
  pKey)

If you’re testing on a different Ethereum (Test)net, make sure to set the chain Id accordingly.

params = [signed_txn.rawTransaction.hex()]

data = {"jsonrpc": "2.0", "method": "eth_sendRawTransaction","params": params, "id": 4}

response = session.post(url, json=data, headers=headers)

if response.ok:
    receipt = response.json().get("result")
else:
    # Handle Error
    print("Error occured")

Notice how we were able to reuse the gas price which we fetched at the beginning.


Conclusion

And that’s all! You just learned the basics of interacting with the most influential blockchain in the world using the JSON RPC Ethereum API! You can find the code for all this here.

Thanks for following along!

Nicolas

If you liked this, give this story a couple of reactions so more people can see it!

If you LOVED this, buy me a coffee :)

  • Ethereum: 0x190d71ba3738f43dc6075f5561e58ac9d4e3dfc2
  • Bitcoin: 1BRucWzs2vnrkfmbfss14ZQErW74A1H1KE
  • Litecoin: LbNfoJfTFVCj7GFaAUtWqhitHJcJ3m8y3V
  • Tags

    The Noonification banner

    Subscribe to get your daily round-up of top tech stories!