How to Connect to the Ethereum Network using Python and Web3

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.

Infura service

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.

How to Connect to the Ethereum Blockchain using Node

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.

pip install web3

Create a new file and paste the code shown below.

from web3 import Web3, HTTPProvider
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.

python app.py

You should see output similar to this.

Latest Ethereum block number 8462434

Awesome. You have just made a connection to the Ethereum blockchain using Python and Web3.

Pankaj Kumar
Pankaj Kumar
Articles: 206