How to connect to the Ethereum network using Web3.py
March 10th, 2022

You can create Ethereum Applications in different programming languages. In this article, we will connect to the Ethereum network using Python.

Preinstalled

  • You have Python (version >=3.5.3) and Pip3 installed on your system.
  • Install web3.py (A Python wrapper for Ethereum node APIs).
  • A text editor

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.

Get API Key WatchData

To create an API key, you need to do the following steps:
On the Dashboard.watchdata.io tab, click Create API key.

Your API key will be automatically created.

Once you have created the API key, copy it and combine it with the HTTP provider's endpoint in this format:

https://ethereum.api.watchdata.io/node/jsonrpc?api_key=YOUR_API_KEY_HERE

For example:

https://ethereum.api.watchdata.io/node/jsonrpc?api_key=83ab245b-ae08-43a4-97db-85903d35652f

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 = 'https://ethereum.api.watchdata.io/node/jsonrpc?api_key=83ab245b-ae08-43a4-97db-85903d35652f'
w3 = Web3(Web3.HTTPProvider(watchdata_url))
last_block_number = w3.eth.block_number
print(f'last block number in eth = {last_block_number}')

Let's take a closer look at the code:

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.

At the moment, only sets of methods described in Ethereum API documentation are available from API interfaces, when working through WatchData node, and we are actively working on adding new methods.


  1. Join to our Discord server
  2. Please leave your feedback in the #feedback channel. If you have any problems or you think that some functionality is not working correctly, we are waiting for your feedback.
  3. Want a new feature or you miss some functionality, tell us about it in the #general channel. We are always open to your ideas!
Subscribe to WatchData
Receive the latest updates directly to your inbox.
Verification
This entry has been permanently stored onchain and signed by its creator.
More from WatchData

Skeleton

Skeleton

Skeleton