Web3.py overview

Adding web3.py

Note: We need Python version >=3.5.3 and install web3.py using pip3 install web3.

Python and other library versions cause common installation problems. So if you face any problems, try setting up a virtual environment and troubleshooting the installation of web3.py.

Using web3.py

We will use web3.py to get the last Ethereum block number. To do this we will use the code below.

from web3 import Web3
watchdata_url = 'YOUR_ETHEREUM_NODE_URL'
w3 = Web3(Web3.HTTPProvider(watchdata_url))
last_block_number = w3.eth.block_number
print(f'last block number in eth = {last_block_number}')

So go ahead and replace `YOUR_ETHEREUM_NODE_URL` with the http provider from the instructions above.

In this code snippet, we import the web3.py library, declare a watchdata_url variable to which we assign the URL of our watchdata node in Ethereum. And then we create an instance of the web3 class with our watchdata_url.

In this code snippet, we retrieve the last Ethereum block number using the w3.eth.blockNumber API and display it.

That’s it, you are connected via the Ethereum network using Python. You can also learn more about the web3.py APIs for building complicated applications on Ethereum.

Last updated