Test your connection to the Ethereum blockchain using Web3.py and Python

In Python you can use the Web3.py library to interact with the Ethereum blockchain. To read about Web3.py click here. This library can be used to retrieve information on the Ethereum blockchain or to send the blockchain a transaction. Remember this is just a library not a node to connect to so do not confuse the two. The Web3.py library can be installed in Python using:

pip install web3

Now that you installed Web3.py you need an end point to connect to an Ethereum node. One of the easiest ways to connect to an Ethereum node is to setup an account at Infura. Once you setup an account they will provide you with an Infura url to use in your code.

Once Web3.py is installed and you have an Infura url you are ready to test out your connection.

The Python code below will print your connection status and the current block number on the Ethereum blockchain. Lets run a this script to test your connection. Remember since we are reading data from the blockchain there is no gas fee.

  • Insert your Infura url
from web3 import Web3

infura_url = 'INSERTYOURINFRAURLHERE'
web3 = Web3(Web3.HTTPProvider(infura_url))

isConnected = web3.isConnected()
blocknumber = web3.eth.blockNumber

The code below takes it one step further and allows you to enter an Ethereum address to read a balance on the blockchain.

  • Insert your Infura url
  • Insert an address to read
from web3 import Web3

infura_url = 'INSERTYOURINFRAURLHERE'
web3 = Web3(Web3.HTTPProvider(infura_url))

isConnected = web3.isConnected()
blocknumber = web3.eth.blockNumber

balance = web3.eth.getBalance('ENTERANADDRESSHERE')

print('Connected: ', isConnected, 'BlockNumber: ', blocknumber, 'Account Balance: ', (web3.fromWei(balance, 'Ether')))

Next Review – How to get a smart contracts ABI for use in Web3.py and Python

2 thoughts on “Test your connection to the Ethereum blockchain using Web3.py and Python

Leave a Reply