Introduction
In order to build a decentralized application, we need to connect to the Ethereum (or other) blockchain. In this tutorial, we are going to learn how to connect to the Ethereum blockchain using Python and Web3.
Prerequisite
- Ethereum test net node ( we’ll use Infura.io for same)
- Python version >=3.5.3 and Pip3
- Web3.py installed
Make sure you have python and pip installed and configured properly.
Connect to the Ethereum Blockchain using Node
First, let’s create a new account on Infura.io. Infura is a blockchain as a service platform and provides us a testnet and mainnet nodes of Ethereum, IPFS, etc.
Create a new account on Infura (it’s free) and create a new Ethereum project. Once the project is created, go to the Settings tab and choose testnet endpoint. For our tutorial, we are going to use Ropsten testnet.
Let’s create a new python project. Create a new folder and switch to it using the Terminal or command prompt. Install the web3 module required for the project using the following command.
Create a new file and paste the code shown below.
w3 = Web3(HTTPProvider('https://rinkeby.infura.io/v3/YOUR_PROJECT_ID'))
print ("Latest Ethereum block number" , w3.eth.blockNumber)
Replace the project ID with the Infura.io project ID.
Run the code to check the output.
You should see output similar to this.
Awesome. You have just made a connection to the Ethereum blockchain using Python and Web3.