Introduction to web3.py
web3.py is a Python library that allows interaction with the Ethereum blockchain. It provides tools for checking balances, transferring ETH, fetching block data, and retrieving transaction details. This guide will walk you through these essential operations.
Installation
Before you begin, install the web3 library using pip:
pip install web3Connecting to an Ethereum Node
To interact with the blockchain, you'll need to connect to an Ethereum node. Here's how to set up the connection:
from web3 import Web3, HTTPProvider
# Replace with your node URL (e.g., local private chain)
node_url = 'http://127.0.0.1:8545'
web3_client = Web3(HTTPProvider(node_url))Core Operations
1. Retrieving Transaction Details
Fetch details of a specific transaction using its hash:
trade_hash = '0x........' # Replace with your transaction ID
transaction_details = web3_client.eth.getTransaction(trade_hash)Key Notes:
- Transaction hashes are unique identifiers for on-chain transfers.
- Use this method to verify transaction status or inspect gas fees.
2. Fetching Block Data
Get information about a block by its number:
block_number = 10 # Replace with your block number
block_data = web3_client.eth.getBlock(block_number)What’s Included:
- Block timestamp
- Transaction list
- Miner address
- Gas used
3. Checking Account Balance
Query the ETH balance of an address (converted to checksum format):
address = '0x....................' # Your ETH address
checksum_address = Web3.toChecksumAddress(address)
balance_wei = web3_client.eth.getBalance(checksum_address)
balance_eth = Web3.fromWei(balance_wei, 'ether')Security Tip:
- Always use
toChecksumAddress()to prevent address formatting errors.
4. Transferring ETH Between Addresses
Send ETH securely using personal.sendTransaction:
from_address = '0x................' # Sender address
to_address = '0x.................' # Recipient address
private_secret = '0x............' # Sender’s private key (handle securely!)
import math
value_wei = int(0.123 * 10**18) # Convert ETH to wei
tx_hash = web3_client.geth.personal.sendTransaction({
"from": Web3.toChecksumAddress(from_address),
"to": Web3.toChecksumAddress(to_address),
"value": value_wei
}, private_secret)Critical Considerations:
- Private keys should never be hardcoded in production scripts.
- Use environment variables or secure vaults for key management.
Best Practices for Security
- Key Management: Store private keys offline or use hardware wallets.
- Gas Fees: Always estimate gas costs before transactions.
- Checksum Addresses: Validate addresses to avoid failed transactions.
👉 Explore advanced Ethereum development
FAQ Section
Q1: Why use toChecksumAddress()?
A1: Ethereum addresses are case-insensitive but checksum formatting prevents typos and ensures compatibility with tools like MetaMask.
Q2: How do I estimate gas fees?
A2: Use web3_client.eth.estimateGas() before sending transactions.
Q3: What’s the difference between wei and ether?
A3: 1 ETH = 10¹⁸ wei. Wei is the smallest denomination for precise calculations.
Q4: Is web3.py suitable for mainnet operations?
A4: Yes, but ensure you handle keys securely and monitor gas price fluctuations.
Q5: Can I use Infura instead of a local node?
A5: Absolutely! Replace the node URL with Infura’s HTTPS endpoint.
Conclusion
web3.py simplifies Ethereum interactions for developers. Whether you're checking balances, analyzing blocks, or sending transactions, this library provides the tools needed for robust blockchain applications.
Next Steps:
- Experiment with smart contract interactions.
- Explore event logs for decentralized app (DApp) development.
For further reading, visit our comprehensive Ethereum guide.