Blockchain development has become increasingly accessible thanks to powerful tools like web3.py, a Python library that enables seamless interaction with Ethereum nodes. Whether you're building decentralized applications (dApps), automating blockchain tasks, or exploring smart contract interactions, understanding how to use web3.py is essential. This guide walks you through practical operations such as checking ETH balances, sending transactions, and retrieving block and transaction data—using real code examples and best practices.
Setting Up web3.py
Before diving into blockchain interactions, ensure your environment is ready. Install the web3 Python package using pip:
pip install web3Once installed, import the necessary modules in your Python script:
from web3 import Web3, HTTPProviderNext, create a Web3 instance connected to an Ethereum node. For local development, you can connect to a private chain running on your machine:
node_url = 'http://127.0.0.1:8545'
web3_client = Web3(HTTPProvider(node_url))With this setup complete, you're ready to perform core blockchain operations.
Retrieve Transaction Details with getTransaction()
One of the most common tasks in Ethereum development is inspecting transaction data. The getTransaction() method allows you to fetch detailed information about a specific transaction using its hash.
trade_hash = '0x........' # Replace with actual transaction hash
transaction = web3_client.eth.getTransaction(trade_hash)
print(transaction)This returns a dictionary containing key details such as:
from: Sender addressto: Recipient addressvalue: Amount transferred (in Wei)gas: Gas limitinput: Data field (useful for smart contract calls)
👉 Learn how to monitor Ethereum transactions in real time using advanced tools.
Fetch Block Information Using getBlock()
Blocks are the building blocks of the Ethereum blockchain. You can retrieve block data by block number or hash using getBlock().
block_number = 10 # Replace with desired block number
block = web3_client.eth.getBlock(block_number)
print(block)The returned object includes:
timestamp: When the block was minedtransactions: List of transaction hashes in the blockminer: Address of the block producergasUsed: Total gas consumed by transactions in the block
You can also pass 'latest' to get the most recent block:
latest_block = web3_client.eth.getBlock('latest')This functionality is invaluable for analytics, auditing, and dApp debugging.
Check ETH Balance with getBalance()
To check the ETH balance of an account, use the getBalance() method. However, there's an important rule: all Ethereum addresses must be checksummed before being passed into web3.py functions.
address = '0x....................' # Your Ethereum address
checksum_address = Web3.toChecksumAddress(address)
balance_wei = web3_client.eth.getBalance(checksum_address)
balance_eth = web3_client.fromWei(balance_wei, 'ether')
print(f"Balance: {balance_eth} ETH")🔍 Note: Balances are returned in Wei. Use fromWei() to convert to Ether for readability.This step ensures security and compatibility across Ethereum tools and networks.
👉 Discover secure ways to manage Ethereum wallets and balances.
Send ETH Between Addresses with sendTransaction()
Transferring ETH programmatically is a fundamental feature in blockchain automation. While sendTransaction() exists, it requires the sender’s account to be unlocked—which poses security risks.
A safer alternative is using personal.sendTransaction(), which unlocks the account only for the duration of the call.
Required Parameters:
from: Sender’s checksummed addressto: Recipient’s checksummed addressvalue: Amount in Wei- Private key for signing (handled internally)
Here's a complete example:
from_address = '0x................'
to_address = '0x.................'
private_secret = '0x............' # Never hardcode in production!
import math
value_in_eth = 0.123
value_in_wei = int(value_in_eth * math.pow(10, 18))
tx_hash = web3_client.geth.personal.sendTransaction({
"from": Web3.toChecksumAddress(from_address),
"to": Web3.toChecksumAddress(to_address),
"value": value_in_wei
}, private_secret)
print(f"Transaction sent: {tx_hash}")⚠️ Security Tip: In production environments, never store private keys in code. Use environment variables or secure key management systems.
Core Keywords for SEO and Search Intent
To align with search engine optimization best practices and user intent, here are the core keywords naturally integrated throughout this article:
- web3.py
- check ETH balance
- send ETH transaction
- retrieve Ethereum block
- getTransaction web3.py
- Ethereum Python tutorial
- blockchain development with Python
- interact with Ethereum node
These terms reflect common queries from developers learning blockchain programming and help improve visibility in search results.
Frequently Asked Questions (FAQ)
Q: Can I use web3.py with public Ethereum networks like Mainnet or Sepolia?
Yes. Instead of a local node URL, connect to a public RPC endpoint from services like Infura or Alchemy:
node_url = 'https://mainnet.infura.io/v3/YOUR_PROJECT_ID'
web3_client = Web3(HTTPProvider(node_url))Ensure you have proper access credentials and rate limits in mind.
Q: Why do I need to checksum Ethereum addresses?
Ethereum uses EIP-55 checksums to prevent errors when entering addresses. Checksumming adds case sensitivity as a validation layer, reducing the risk of sending funds to invalid addresses.
Use Web3.toChecksumAddress(address) consistently.
Q: Is it safe to use personal.sendTransaction()?
It’s safer than globally unlocking accounts, but still carries risks if private keys are exposed. Always avoid hardcoding secrets in scripts. For higher security, consider using signed transactions offline (signTransaction) and broadcasting them separately.
Q: How do I handle asynchronous operations with web3.py?
While web3.py is primarily synchronous, you can integrate it with async frameworks like asyncio using threading or third-party wrappers like web3.py with trio. Alternatively, consider using ethers.py for more modern async support.
Q: What units does getBalance() return?
getBalance() returns values in Wei. To convert to Ether or other units:
eth_value = web3_client.fromWei(balance_in_wei, 'ether')
gwei_value = web3_client.fromWei(balance_in_wei, 'gwei')Common units include wei, kwei, mwei, gwei, szabo, finney, and ether.
Q: Can I interact with smart contracts using web3.py?
Absolutely. After deploying a contract, use web3.eth.contract(address=address, abi=abi) to create a contract instance and call its methods—both view functions and state-changing transactions.
Final Thoughts
Mastering web3.py opens the door to powerful Ethereum automation and development capabilities. From checking balances and sending transactions to retrieving blocks and parsing transaction data, this library provides all the tools you need to build robust blockchain applications in Python.
Whether you're a beginner or an experienced developer, practicing these foundational skills will strengthen your understanding of decentralized systems.
👉 Start exploring Ethereum development with powerful APIs and developer tools.