Python Web3 Development Tutorial: Getting Started
Web3.py is the primary Python library for Ethereum development. This tutorial covers installation, connecting to networks via providers like Infura, reading blockchain data, sending transactions, and interacting with smart contracts using ABIs. You will learn both read-only queries and write operations.
Introduction
Python is an excellent language for Web3 development, particularly for backend services, data analysis, and automation. The web3.py library provides everything you need to interact with Ethereum and EVM-compatible blockchains.
This tutorial takes you from installation to production-ready code, covering reading blockchain data, sending transactions, and smart contract interaction.
Prerequisites
- Python 3.8 or higher
- Basic Python knowledge
- Understanding of blockchain fundamentals
Installation
Install web3.py using pip. You will also want python-dotenv for managing API keys securely.
Create a virtual environment to keep dependencies isolated.
How Do You Connect to Ethereum with Python?
Using a Provider
You need a provider to communicate with the Ethereum network; web3.py's quickstart calls a remote node provider the quickest route. Options include:
Infura: Most popular, generous free tier
Alchemy: Good developer tools, free tier
Local node: Full decentralization, requires resources
Sign up for Infura or Alchemy to get an API key. Once you outgrow a free tier, our RPC node provider comparison shows what each charges per million calls.
Connection Code
Create a Web3 instance with your provider URL. Verify the connection by checking if the client is connected.
You can connect to different networks:
- Mainnet for production
- Sepolia for testing (Goerli is no longer maintained; ethereum.org lists Sepolia and Hoodi as the maintained public testnets)
- Local networks like Hardhat or Anvil for development
Reading Blockchain Data
Reading data from Ethereum is free and requires no wallet.
Get Current Block Number
The block number indicates how many blocks have been mined since genesis.
Get ETH Balance
Query the balance of any Ethereum address. Balances are returned in Wei (smallest unit). Convert to Ether for human-readable format.
Get Block Information
Retrieve details about any block including timestamp, transactions, and miner.
Get Transaction Details
Look up any transaction by its hash to see sender, recipient, value, and status.
Sending Transactions
Writing to the blockchain requires:
- A wallet with private key
- ETH for gas fees
- A signed transaction
Create a Wallet
For development, you can use a test wallet. In production, use secure key management.
Security Warning: Never hardcode private keys. Use environment variables or secure key management services.
Build and Send Transaction
Create a transaction dictionary with:
- nonce: Transaction count for this address
- to: Recipient address
- value: Amount in Wei
- gas: Gas limit
- gasPrice or maxFeePerGas: Gas price settings
Sign the transaction with your private key and broadcast to the network.
Wait for Confirmation
After sending, wait for the transaction to be mined. Check the receipt for success status.
Interacting with Smart Contracts
Smart contracts are programs deployed on the blockchain. To interact with them, you need:
- Contract address
- Contract ABI (Application Binary Interface)
Get Contract ABI
The ABI describes the contract functions and their parameters. Get it from:
- Etherscan for verified contracts
- The contract compilation output
- The project documentation
Create Contract Instance
Instantiate a contract object with the address and ABI.
Read Contract Data (Call)
View functions that read data are free to call. For example, calling totalSupply or balanceOf on an ERC-20 token.
Write Contract Data (Transaction)
Functions that modify state require a signed transaction. Build the transaction using the contract function, sign it, and send it.
Working with ERC-20 Tokens
ERC-20 is the standard for fungible tokens. Common operations include:
Check Token Balance
Use the balanceOf function with an address parameter.
Transfer Tokens
Call the transfer function with recipient and amount. Remember to account for token decimals.
Approve and TransferFrom
For DeFi interactions, you often need to approve a contract to spend tokens on your behalf.
Error Handling
Blockchain operations can fail for many reasons:
- Insufficient balance for gas
- Transaction reverted by contract
- Network congestion
- Invalid parameters
Wrap blockchain calls in try-except blocks and handle errors appropriately.
Best Practices
Security
- Never expose private keys in code
- Use environment variables or secrets management
- Validate all user inputs
- Test thoroughly on testnets
Gas Optimization
- Estimate gas before sending transactions
- Set appropriate gas prices using fee data
- Consider EIP-1559 transactions for better fee estimation
Reliability
- Implement retry logic for network failures
- Use websocket connections for real-time data
- Cache data when appropriate
Testing
Always test on testnets first:
- Sepolia: Most popular Ethereum testnet
- Goerli: Retired, not among the currently maintained public testnets
- Local: Hardhat or Anvil for fast iteration
Get testnet ETH from faucets to pay for gas.
Conclusion
Python and web3.py provide a powerful toolkit for Ethereum development. Start with reading data to understand the blockchain, then progress to transactions and smart contract interactions.
For production applications, focus on security, error handling, and proper key management. Use testnets extensively before deploying to mainnet.
The Ethereum ecosystem continues to evolve, so keep up with web3.py updates and new features like improved EIP-1559 support and better type hints.
Sources
The primary sources this article cites, checked in November 2026:
- Quickstart (web3.py documentation) (web3py.readthedocs.io)
- Networks (ethereum.org developer docs) (ethereum.org)
Key Takeaways
- Web3.py is the main library for Python Ethereum development
- Use providers like Infura or Alchemy to connect to Ethereum
- Reading data (balances, blocks) is free and requires no wallet
- Writing data (transactions) requires ETH for gas fees
- Smart contract interaction requires the contract ABI
- Always test on testnets before mainnet deployment
Frequently Asked Questions
Do I need to run my own Ethereum node?
No. Node providers such as Infura, Alchemy, or QuickNode give you API access to Ethereum nodes, and their free tiers are enough for development and small projects. Sign up, get an API key, and pass the provider URL to web3.py. Running your own node only makes sense for high-volume applications or maximum decentralization.
How much does it cost to interact with Ethereum?
Reading data, such as balances, blocks, and view functions on contracts, is free and needs no wallet. Writing data means sending transactions, which require gas fees paid in ETH. Simple transfers cost a few dollars, while smart contract interactions can cost $5-50+ depending on complexity and congestion. Testnets are free for development.
Can I use Python for production Web3 applications?
Yes. Python works well for backend Web3 services, bots, data analysis, and automation. Frontend DApps more commonly use JavaScript or TypeScript with ethers.js, so many projects pair a Python backend with a JavaScript web interface. For production, focus on security, error handling, and key management, and test extensively on testnets before mainnet.
What is a contract ABI and why do you need it?
A contract ABI (Application Binary Interface) describes a smart contract's functions and their parameters. Web3.py needs it, together with the contract address, to create a contract instance and know which methods exist and what inputs they take. You can get the ABI from Etherscan for verified contracts, the compilation output, or project documentation.
Which testnet should I use with web3.py?
Sepolia is the most popular Ethereum testnet. Goerli is no longer among the maintained public testnets, and local networks such as Hardhat or Anvil give fast iteration during development. Get testnet ETH from faucets to pay for gas, and always test there before sending anything to mainnet, since mainnet transactions cost real ETH.
About the Author
Marcus Williams
Blockchain & DeFi Editorial Desk
Blockchain & DeFi Editorial Desk · Web3AIBlog
Marcus Williams is a pen name for our blockchain and DeFi editorial desk. Posts under this byline are written and reviewed by contributors with backgrounds in protocol engineering, on-chain analysis, smart contract auditing, tokenomics, and decentralized finance. The desk covers consensus mechanisms, liquidity protocols, MEV, on-chain forensics, regulatory frameworks across jurisdictions, and the operational realities of running and using DeFi at scale. Our coverage is an editorial synthesis of protocol documentation, on-chain data, and audited primary sources, with every figure verified against a primary source before publication.