Web3.py is a Python library that allows developers to interact with Ethereum and other EVM-compatible blockchains. It helps developers retrieve blockchain data, check wallet balances, read smart contracts, and build blockchain applications using Python.
For Python developers interested in Web3 development, Web3.py provides a practical starting point.
1. What Is Web3.py?
Web3.py is a Python library for communicating with Ethereum nodes through JSON-RPC.
With Web3.py, developers can:
- Connect Python applications to Ethereum networks.
- Retrieve blockchain data and block information.
- Check ETH balances for public wallet addresses.
- Read data from deployed smart contracts.
- Build and sign blockchain transactions.
- Develop tools for decentralized applications (dApps).
2. Install Web3.py
Create a Python virtual environment:
python -m venv .venv
Activate it on Windows:
.venv\Scripts\activate
On Linux or macOS:
source .venv/bin/activate
Install Web3.py:
pip install web3
Verify the installation:
python -c "import web3; print(web3.__version__)"
3. Connect Python to Ethereum
You need an Ethereum node RPC endpoint to communicate with the blockchain. For learning, you can use an RPC endpoint connected to the Sepolia testnet.
Store your endpoint in an environment variable named SEPOLIA_RPC_URL.
import os
from web3 import Web3
rpc_url = os.environ.get("SEPOLIA_RPC_URL")
if not rpc_url:
raise ValueError("Please configure SEPOLIA_RPC_URL")
w3 = Web3(Web3.HTTPProvider(rpc_url))
if not w3.is_connected():
raise ConnectionError("Could not connect to Ethereum")
print("Connected successfully")
print("Chain ID:", w3.eth.chain_id)
The Sepolia testnet chain ID is 11155111. Checking the chain ID helps verify that you are connected to the intended network.
4. Retrieve the Latest Block
After connecting, you can retrieve the latest block number.
latest_block = w3.eth.block_number
print("Latest block:", latest_block)
To retrieve more information about the latest block:
block = w3.eth.get_block("latest")
print("Block number:", block["number"])
print("Block hash:", block["hash"].hex())
print("Timestamp:", block["timestamp"])
print("Transactions:", len(block["transactions"]))
This is useful for building blockchain explorers, monitoring tools, and blockchain analytics applications.
5. Check an Ethereum Wallet Balance
Web3.py can retrieve the ETH balance of any public wallet address without requiring its private key.
from web3 import Web3
address = Web3.to_checksum_address(
"0x0000000000000000000000000000000000000000"
)
balance_wei = w3.eth.get_balance(address)
balance_eth = w3.from_wei(balance_wei, "ether")
print("ETH balance:", balance_eth)
The example uses Ethereum's special zero address. Replace it with a valid public address to check another wallet.
Ethereum balances are returned in wei, the smallest denomination of ETH. The from_wei() method converts the balance into ETH.
Security tip: Never share your private key or recovery phrase. They are not needed to check a public wallet balance.
6. Read Data from a Smart Contract
Web3.py can interact with deployed smart contracts using an Application Binary Interface (ABI).
An ABI describes the functions exposed by a smart contract.
For example, if a deployed contract has a public name() function that returns a string, you can read it as follows:
from web3 import Web3
contract_address = Web3.to_checksum_address(
"YOUR_DEPLOYED_CONTRACT_ADDRESS"
)
contract_abi = [
{
"inputs": [],
"name": "name",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
]
contract = w3.eth.contract(
address=contract_address,
abi=contract_abi
)
contract_name = contract.functions.name().call()
print("Contract name:", contract_name)
Replace the placeholder address with a deployed contract that supports the specified function.
The .call() method reads contract data without broadcasting a transaction or requiring a private key.
7. Web3.py Project Ideas
Here are some beginner-friendly projects you can build using Web3.py.
Ethereum Wallet Balance Checker
Accept a public wallet address and display its ETH balance.
Blockchain Explorer
Display block numbers, hashes, timestamps, and transaction counts.
Smart Contract Reader
Retrieve public data from a deployed smart contract.
Transaction Tracker
Accept a transaction hash and display its status and details.
Token Information Dashboard
Read token metadata and balances from compatible ERC-20 contracts.
Start with read-only applications before experimenting with transactions that modify blockchain state.
8. Common Problems and Solutions
Connection errors: Verify the RPC endpoint, network connectivity, and provider limits.
Invalid address errors: Check the address format and use Web3.to_checksum_address().
Contract call failures: Confirm that the contract exists on the connected network and that the ABI matches the deployed contract.
Incorrect network: Check w3.eth.chain_id before interacting with contracts.
Unexpected transaction costs: Use a testnet while learning and understand gas fees before sending transactions on a production network.
Conclusion
Web3.py makes it possible to combine Python programming with Ethereum blockchain functionality. By learning to connect to an RPC endpoint, retrieve blocks, check wallet balances, and read smart contract data, developers can build a strong foundation for advanced Web3 applications.
A good next step is to create a command-line application that accepts an Ethereum address and displays its ETH balance and the latest block number.
For further learning, visit the official Web3.py documentation: