Web3.py: A Guide to Ethereum Blockchain Development with Python

By Vladyslav Deryhin
September 29, 2022
14 min read
Web3.py: A Guide to Ethereum Blockchain Development with Python | RPC Fast
Table of Contents

Today we will learn the basics of Web 3.0 and methods of interacting with it. We will explain how to do all operations with an Ethereum Blockchain and Web3.py, a software that allows working with Ethereum using Python.

And, of course, we will explain how to operate with an Ethereum Blockchain and set it up. This guide will provide you with the most useful information if you are familiar with the following tips and skills:

  • at least a basic understanding & practice of Python;
  • basic knowledge of how to use the console;
  • understanding of smart contracts, and blockchain-based applications;
  • basic understanding of the Solidity language, which is necessary for smart-contracts running.

Now we can start our Python Web3 guide!

What is Web 3.0?

The term of 'Web 3.0' was used by Gavin Wood, Ethereum co-founder, soon after Ethereum was born in 2014. He mentioned that the previous versions of Web demanded too much from the users in the terms of trust and security and we have to move forward to solve this things. While previous concepts focused on human-machine interactions, this one talks more about system-to-system interaction where human just harvests the results of such an interaction.

Web 3.0 helps to eliminate data ownership problems. While the 2.0 information is centralized and controllable, the new era is more about independence. It stands on the idea of a decentralized, safe, and simply verifiable web. Creators expect to achieve that by removing a third party, which is not always trusted enough, and relying on system-to-system data exchange. It requires developing highly interoperable algorithms and ecosystems.

As a result, we get a large platform for a fair and independent user experience. It becomes possible with algorithms for verifying data and building applications in a completely new way. With the new technologies, users can control the amount of information they give and receive. It leads us closer to the concept of an open web, where developers can create safe, decentralized apps with upgraded security.

Secure transactions allow users to own and work with their data, while networking becomes just data connectors. The data connection is available in a decentralized way with protocols running on smart contracts. 

Main Definitions of Blockchain

  • Nodes are data storages that allow us to send queries to them, find out about blockchain state, and receive the data we need.
  • Block is a complex or the net of interconnected united nodes. For example, the Ethereum Blockchain consists of a complex of nodes.
  • Blockchain is a large network of many blocks. There is a genesis block that has started the system. However, there are no central blocks. All blocks refer to a previous one, have the same importance level, and keep the system developing and working.
  • Transactions are a kind of instructions sent between different accounts and responsible for changes in the blockchain statement. The security level is reliably supported by cryptography technologies.

The full terminology is available on the Web3 Foundation website.

What is Web3.py?

It is a library that allows Ethereum Python interactions. It developed from Web3.js but was soon recomposed due to the higher popularity of Python compared to JavaScript among developers.

This might be useful: on the Ethereum website, there is a large list of active web3 Python tools & instruments. Check it for resources you can apply in your development.

Web3.py allows a creation of decentralized apps (DApps). The library is full of tools for sending transactions, smart contract interactions, reading block data, and performing other tasks.

How to Start Applying Web3.py on the Ethereum Blockchain

Today we will show basic actions and templates for interacting with the Ethereum Blockchain by applying Web3.py. With these functions, you will be able to build DApps further. 

Check out this guide on DApp development for intermediate developers. This technology is still evolving, and developers discover its possibilities in solving different tasks. On the Ethereum website, you can always find freshly made DAapps that might inspire your development.

Connecting to an Ethereum node: Why Do I Need It?

Ethereum is much more than a blockchain today, thanks to inventive community that developed and widened its possibilities since 2014. One of thousands of complement technologies, Web3.py becomes a library for connecting to nodes but it does not provide a node itself. 

That is why you have to consider a data storage additionally. Your node will constantly update and exchange data with other nodes, so this information will require space to be stored. A node is your key to current state of the blockchain, and without it not much of the net will be useful.

Local vs. Hosted nodes: How to Choose One?

The choice of a node depends on your personal preferences and possible needs. While choosing, remember two main types of nodes.

  • Local nodes allow you to verify transactions individually on your machine. The main reason why developers choose it—they need to manage a node individually and need the highest level of protection. However, you still trust all information on the node to software. Also, you must prepare a lot of disk space for using it because operations will run on your computer.
  • Hosted nodes, on the other hand, belong to someone else, and operations will run on remote servers. It is a much faster option compared to local ones. You must choose them wisely because malicious software can provide you with the wrong data or cause other problems.

The second type is preferable for ones who have just come to an Ethereum blockchain and still don’t have serious plans for applying it. We recommend choosing hosted notes for the first time on Python Ethereum. In the Web3.py documentation, you will find recommendations on working with both local and hosted nodes.

Applying a Blockchain API

The third solution is to apply a Blockchain API, like RPC Fast. This SaaS solution gives you freedom from third-party participants and saves time on extra work. As far as creating a local node from scratch is long and complicated, a significantly easier solution was invented.

We suggest you the RPC Fast API as the most versatile and multifunctional one. Remote Procedure Call is a protocol that allows programs to send service requests to other programs without diving deep into the program details. Currently, RPC Fast API operates on the following blockchains:

  • Ethereum;
  • Binance Smart Chain;
  • Polygon.

An API provides you with an endpoint to access the data in the blockchain. The algorithm contains only a couple of actions. RPC API takes an URL and sets it into the app configuration. It lets all processes run fast and without bugs.

The current function range involves:

  • WebSocket endpoint;
  • HTTP endpoint;
  • Public URL Whitelisting;
  • On-time automatic software updates from hard fork support;
  • Domain masking—providing custom domains for endpoints;
  • Client support—for Enterprise clients.

It is a developing solution from Dysnix, a football team-sized DevOps team with huge experience in blockchain. Soon this API will be available for Avalanche, Polkadot, Solano, and other blockchains.

Setting Up a Node

If you decided to do everything by yourself, please check whether you have the last version of Python installed on your computer and that you have a local or hosted node too. If you still want to create a local node from scratch, use trusted Geth or Parity platforms. Look for lessons on creating personal nodes on their websites.

We will give today’s examples on the RPC Fast-hosted node. It is one of the most popular and trusted nodes for Ethereum Python. Register to get a free account. It will be enough to start and test.

You can connect to your node via one of the following methods:

  • HTTP, the most supported option;
  • WebSockets, the fastest variant due to its simplicity;
  • IPC (Inter Process Communications) relies on a local file system for the highest safety level.

To start working, you should create an RPC Fast account and start a new project on the dashboard. On the project tab, you’ll see information about its status, the number of requests, endpoints, and security issues. Then you choose the endpoint, and an URL appears on the dashboard. 

Web3.py comes with a set of basic providers:

  • HTTPProvider for interactions with HTTP/HTTPS JSON-RPC servers;
  • IPCProvider for IPC Socket JSON-RPC actions;
  • WebsocketProvider for Websocket and Windows Sharepoint Services servers.
  • AutoProvider to interact with web3 without any providers (very rare usage).

Also, there are two experimental providers, EthereumTesterProvider and AsyncHTTPProvider. You can find a detailed explanation of their features in web3.py documentation.  A single provider connection is usually enough for a basic case like ours and other scenarios. Still, creating a few examples of connections with multiple providers is available. 

For more information on selecting a node, read a relatable part of Web3.py documentation. Here creators give pros and cons of each kind and examples of appliances.

Set Up Connection

Let’s try some web3 Python Ethereum interactions via the library. During this operation, we will use an HTTP connection. Checking the balance is the easiest activity to start from. Your first action is firing Python up in that way:


$ python

The next step is web3.py import:


from web3 import Web3

Are there any unclear aspects? Check the short YouTube course of explanations by DApp University to see how these operations function in a process.

Check the Balance Account

Ethereum is not just a blockchain developing platform, and it includes a blockchain-based cryptocurrency. With an Ether Wallet, you can pay, get donations, and do other actions. To understand how Web3 Python works, let’s learn some basic operations with wallets.

Now you can check the account balance within a single action. To get it done, we will use the function web3.eth.getBalance. Also, you’ll need the Ether wallet number. Firstly, name the variable:


account = "your_wallet_number"

After that, let’s try checking the balance with the following request:


balance = web3.eth.getBalance ("your_wallet_number")

Finally, you should return a variable to receive an answer to your question. For your comfort, you can convert Wei to Ether. Wei is related to Ether as a penny to dollars but with a greater difference. It will be easier to look up the balance in the usual size:


print(web3.fromWei(balance, "ether"))

Now you know how to do balance check-ups on Python Web3! Other actions with wallets, such as finding transaction receipts, are available in the Web3 Documentation. Read some examples from there to understand the code better. Let’s move on and discover other options.

Interacting with Smart Contracts

Smart contracts are an essential part of Ethereum Blockchain. In general, it is a composition of functions that control the state of data related to a certain address name. Just like the user’s account, a smart contract has an address, which means that it is open for transactions. Unlike a regular user account, a smart contract is programmed, and it will run only according to the program.

Smart contracts can exist under the following conditions:

  • the existence of a decentralized environment (Ethereum, Solana, etc.);
  • the existence of decentralized databases that exclude human factors;
  • the usage of asymmetric encryption;
  • a proven source of digital data.

Usually, you pay some money to create a smart contract because it requires storage and calculations. Many instruments allow interaction with contracts, such as Remix or Hardhat. We won’t use them today and apply only to the contract’s address. It will be enough to see how function inputs operate.

Reading Data

To start with, let’s try recalling data from a contract. For any interaction, we will need to know the abstract binary interface (ABI) and the address of a smart contract. In this operation, we won’t create a new contract, as it is a long and complicated process. You can look up useful information in the Python Ethereum and Web3 tutorials.

Let’s find out about the contract’s statement and start with defining variables:


address = 'YOUR_CONTRACT_ADDRESS'
abi = 'YOUR_CONTRACT_ABI'

To recall the total supply of a contract, type function totalSupply(). Results will appear in the following way:


contract_instance = w3.eth.contract(address=address, abi=abi)
result = contract_instance.functions.totalSupply().call()
print(result)

It is not the only way to perform this operation. You can also use public methods and functions described in the documentation. When you dive deeper into this topic, you’ll learn about creating, deploying, and compiling contracts.

If you want to go further: check out Ape, a tool for operating with smart contracts. ApeWorx deals with Data Science and web3 Python-based problems and provides users with an Ethereum framework.

Proceeding Transactions on the Ethereum

Now we proceed with transactions, the main operation on Python Web3. You can assign them, send messages, and do other operations with your private keys. The easiest way to receive them is to use a Metamask wallet. It provides users with access to their Ether wallet with a simple browser extension. You should export it and use a local private key to assign and send transactions.

There are different ways of sending transactions:

  • sending Ether from one account to another;
  • calling out a smart contract function;
  • deploying a new smart contract.

The point of action stays the same in each case: you write some data and then update and check its state. We’ll try some interactions to understand these mechanisms better. For stronger security measures, use a personal blockchain, such as Ganache. It allows you to run tests and check commands and the state of the net without showing your private keys.

You can start with building a dictionary to operate with during a transaction. It can look the following way:


nonce = web3.eth.getTransactionCount(account_1)

tx = {
       'nonce': nonce,
       'to': account_2,
       'value': web3.toWei(1, 'ether'),
       'gas': 2000000,
       'gasPrice': web3.toWei('50', 'gwei'),
}

Look at a few explanations:

  • a field ‘nonce’ is necessary to prevent doubled requests;
  • the body of an operation is the transaction object;
  • in the ‘to’ field we specify the direction of the transaction;
  • further, we define the amount of currency sent to an account;
  • finally, we specify the price.

The finishing step is to sign a transaction, and here is the place to use your private keys.  They verify the sending, here is why no one except you should know them. After assigning, a transaction must be sent to the network in the following way:


tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
print(web3.toHex(tx_hash))

This action will return the hash of the transaction. Further, you can convert the transaction results into Hex format and print them. This is how Ether can be sent from one account to another via the Web3 py library.

If you are familiar with Python quite well, have a look at Vyper. It is a programming language, quite similar to the Python web3 type, composed especially for smart contracts development.

Checking Blocks Via Web3.py

This is a necessary function while we are building history analysis. The result of this type of function input can look the following way:

Blocks Via Web3.py

There are certain functions allowing you to receive the necessary data:

  • get the latest block number via .blockNumber;
  • receive the data for the last block via .getBlock('latest').

Let’s use the ‘for’ cycle to build the block history function. Every time we take the latest block and count 10 back. It will look like that:


# get latest block number
print(web3.eth.blockNumber)

# get latest block
print (web3.eth.getBlock('latest'))

# get latest 10 blocks
latest = web3.eth.blockNumber
for i in range(0, 10):
       print (web3.eth.getBlock(latest - i))

Another great ability we receive is a transaction checkup via the block number. This is how it goes:


hash = 'YOUR_WALLET_NUMBER'
print(web3.eth.getTransactionByBlock(hash, 2))
Conclusion

We have given an overview of some basic operations with the Web3 Python library. You can get a complete understanding by reading the documentation of this library, their coding guides, and developers’ advice on choosing software. Also, you can move to more complicated operations, such as calling smart contract functions via explaining articles. There are many programs and operations to choose from, giving you great freedom. At the exact moment, you take up the risk of entrusting your data to someone else. However, Python Web3 blockchain technologies minimize the chance of data stealth.

Does it still look difficult, or take too much time to set up? If you want to minimize your work, then apply a Blockchain API. Most problems here are already solved, and the URL is already set into the configuration. You don’t have to set up essential functions every time and deeply understand those algorithms. Take a close look at the RPC Fast solution from Dysnix and continue developing DApps with ease.

Start building your Ethereum-based DApps with our geo-distributed and high-available Blockchain API
Start now for free
More articles
No items found.
We use cookies to personalize your experience
Copied to Clipboard
Paste it wherever you like