Quickstart
All code starting with a $ is meant to run on your terminal. All code starting with a >>> is meant to run in a python interpreter, like ipython.
Installation
web3.py can be installed (preferably in a virtualenv ) using pip as follows:
If you run into problems during installation, you might have a broken environment. See the troubleshooting guide to setting up a clean environment .
Using Web3
This library depends on a connection to an Ethereum node. We call these connections Providers and there are several ways to configure them. The full details can be found in the Providers documentation. This Quickstart guide will highlight a couple of the most common use cases.
Test Provider
If you’re just learning the ropes or doing some quick prototyping, you can use a test provider, eth-tester. This provider includes some accounts prepopulated with test ether and instantly includes each transaction into a block. web3.py makes this test provider available via EthereumTesterProvider .
The EthereumTesterProvider requires additional dependencies. Install them via pip install "web3[tester]" , then import and instantiate the provider as seen below.
Local Providers
The hardware requirements are steep, but the safest way to interact with Ethereum is to run an Ethereum client on your own hardware. For locally run nodes, an IPC connection is the most secure option, but HTTP and websocket configurations are also available. By default, the popular Geth client exposes port 8545 to serve HTTP requests and 8546 for websocket requests. Connecting to this local node can be done as follows:
Remote Providers
The quickest way to interact with the Ethereum blockchain is to use a remote node provider. You can connect to a remote node by specifying the endpoint, just like the previous local node example:
This endpoint is provided by the remote node service, typically after you create an account.
Getting Blockchain Info
It’s time to start using web3.py! Once properly configured, the w3 instance will allow you to interact with the Ethereum blockchain. Try getting all the information about the latest block:
web3.py can help you read block data, sign and send transactions, deploy and interact with contracts, and a number of other features.
A few suggestions from here:
The Overview page provides a summary of web3.py’s features.
The w3.eth API contains the most frequently used methods.
A guide to Contracts includes deployment and usage examples.
The nuances of Sending Transactions are explained in another guide.
For other inspiration, see the Examples .
It is recommended that your development environment have the PYTHONWARNINGS=default environment variable set. Some deprecation warnings will not show up without this variable being set.
How to install web3 on vscode without having all these issues?
here is the code I’m trying to run (from Patric’s course), please consider that this is my first time into coding and it has been two weeks trying to solve this issue !
from solcx import compile_standard from web3 import Web3 import json
with open("./SimpleStorage.sol", "r") as file: simple_storage_file = file.read()
Solidity source code compiled_sol = compile_standard(
with open("compiled_code.json", "w") as file: json.dump(compiled_sol, file)
get bytecode bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][
get abi abi = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"]
connecting to ganach w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:7545")) chaind_id = 5777
my_address = "0xa1d2a440E4E75bcA442107162DE8C276D637a0eF" ‘private_key = os.getenv("0x170ab1d384e1d218ccd8ec332dfa334f8e9980f008043ff04e99a8154322bf06")
cteating the contract in python SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode) print(SimpleStorage)
I tried all the solution I found; installed cyphon, installed legacy but nothing changed. and this is was I see on the terminator:
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
cooganb/web3py-tutorial
Name already in use
- Local
- Codespaces
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more about the CLI.
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Sending Money Using Python — Web3.py tutorial
Trigger warning: The following tutorial contains elements of explicit cryptography, peer-to-peer financial services and other transgressive behaviors. The examples are meant only to illustrate the power and ease of blockchain for Python.
Hey all yall Pythoners out there!
I’m really into the Python community. Like so many, Python was my first programming language. The Python hackathon and meet-ups are awesome. And, as a bonus point, I love Monty Python!
I thought I’d join all these loves together with my current job: showing developers how powerful blockchain programming can be, and how easy the skills are to pick up.
This will be a tutorial walking Python developers through the basics of Web3.py, a blockchain (Ethereum) library. We’ll do a lot of this from the Python interpreter. (In the next tutorial, we’ll setup a proper directory but we’re keeping things easy for now!)
Note: For security reasons, we’ll be sending our money over a test network. All of these same techniques can be used on the main Ethereum network.
Table of Contents
Installation
We’re gonna use pip to install web3.py from our command line
For people with both Python 2 and 3 installed, you should check to see which version pip command invokes. Some default to 2.7:
Also, if you’re using virtualenv, here’s some documentation about setting up a clean environment for Web3.py
Great! We’re on our way.
Setting up our Connection
Blockchain systems are decentralized networks made up of people running individual dedicated P2P software or “nodes”. It’s similar to a torrent network: To interact with the network, you either have to host a node or use a service that hosts one for you.
Since this is a basic tutorial, we’ll use a service. The most popular one is Infura. You can setup your own account (instructions here) or you can use the Product ID below. It’s crucial you get a Project ID and API endpoint — it will be our API endpoint to the blockchain.

Copy the Endpoint and be sure to prepend https:// to the address.
Once you have that, you’re ready to connect to the blockchain using Python!
Initialization
Let’s fire up our Python interpreter. This can vary depending on your Python installation, but is usually accomplished with running whatever keyword you typically put before a python file. For me on my Mac iTerm with both Pyton 2 and 3 installed, it’s:
To check that all our setup is correct, please run your python interpreter and the following commands:
The above command imports some of the main methods from web3.py we’re going to use to connect to the blockchain as well as the ever-faithful, native json library.
Next, we’ll create an object, w3 , which we initialize with our Infura API endpoint ( prepended with https:// ). It will become the main way web3.py works with the blockchain throughout the rest of the tutorial.
Note: You need to add HTTPS:// in front of your Infura API address, otherwise you’ll get an error!
We also need to add in some middleware to help us work with Infura and the Rinkeby testnet:
Now, to see if all’s gone well, we run:
If you get True , congratulations! You’re connected to the blockchain!
If you get False , a few things you can check:
- If you’ve had to restart the interpreter, you have to re-import the libraries and re-initialize the variables
- Have you copied the Infura API key correctly?
- Have you installed web3.py and installed and imported Web3 and HTTPProvider library?
- Have you prepended the API key with https:// ?
Create an Account
If we’d like to send money on the blockchain, we’ll need an Ethereum account. Ethereum accounts are the main unit of identity on the Ethereum blockchain — an account’s address is how the user is identified on the network. Underpinning the account system is a decentralized identity protocol based on public key cryptography. Essentially, identity on a blockchain network is confirmed by authentication of digital signatures from a single private key (held in secret by a single user) by its public address counterpart (held by the entire network). While it has significant user experience hurdles, it does provide a fast, peer-to-peer authentication protocol.
Generating an account to use on the Ethereum network is super easy with web3.py.
Note: In the next few steps, I’m going to break a few rules of cryptography and security. 1) I’m going to generate a private key with inadequate entropy (randomness) and 2) I’m going to post a private key online. I’m not going to use this key beyond this tutorial—it’s just for educational purposes. You should always use proper private key management, like Geth or MetaMask, and never share your private key publicly.
The above command uses the string input to generate the my_account object, which contains a private key ( my_account._private_key ) and its associated Ethereum address ( my_account._address ) . However, since this has been posted publicly, someone could generate and use the same private key. (Luckily, I’m just using it for this tutorial and only on a test blockchain network.)
For this reason, users typically delegate private key creation and management to software called clients (like Geth) or wallets (like MetaMask). These projects provide an incredibly secure way to generate and handle private keys for blockchain interactions.
ENS Accounts
Ethereum addresses are long hexadecimal numbers. They’re nearly impossible to type or remember, so the Ethereum community created the Ethereum Name System (ENS). It serves the same benefit of the Domain Name System, which replaces website server numbers (216.58.194.46) to human-readable names (google.com). Rather than a .com domain, most ENS names use a .eth domain.
For example, I have an Ethererum account at 0x4d3dd8471a289E820Aa9E2Dc5f437C1b2E22F598 but I’ve used ENS to map the more readable name coogan.eth to the address. If you type those into apps or projects that support ENS (such as web3.py !), it will substitute in the Ethereum hexadecimal address. Unfortunately, we won’t be able to use it for this tutorial as .eth domain names only work on mainnet. but maybe in the next tutorial!
Send Money
For this last section, we’re going to send some money from the account we just created to another Ethereum account. All from the python interpreter!
A reasonable response to sending money is, “Isn’t this just internet funny money that’s always fluctuating with a downward trajectory?” And, yes, cryptocurrency USD prices are extremely volatile. This has caused hesitation from businesses — why would you accept a currency with an uncertain price?
However, there’s a novel workaround built within the Ethereum ecosystem. Ethereum is called “the World Computer” because it’s a distributed system that allows developers to upload and execute their own code. Code uploaded to Ethereum in this way is called a smart contract. Once it’s uploaded to the network, it becomes a standalone entity, with its own address, memory storage and network access. Smart contracts have given rise to a rich Ethereum developer community that is both creative and tireless in addressing challenges, like the inherent price volatility of blockchains.
In an attempt to create a stable source of value for Ethereum, a group of developers wrote and uploaded code to Ethereum called Dai. It’s a digital token that is always worth about $1 USD. (The technical details to achieve this stability are fascinating but beyond the scope of this tutorial — if you’d like to read more about the mechanics you can find more here). Once we hold the Dai token, we can exchange it with other users for the same rate as US dollars. We’ll do that now!
(Note: to get Dai to an account different from the one in the tutorial, you can mint your own on the testnet using this contract address, Metamask and your own account. Follow the steps in the tutorial here)
Contract Instantiation
First, to interface with code that’s been uploaded by a developer to Ethereum, we need to know what methods the uploaded code exposes. Web3.py natively knows how to interface with the core Ethereum software, but needs guidance to interact with third-party code. We provide that guidance by providing Web3.py an Application Binary Interface (ABI). Similar to an Application Programming Interface (API), the ABI allows our machine to know what functions are available to us and what parameters those functions expect. ABIs are not available on the blockchain and are supplied by the developer on sites like Github or Etherscan.
Here’s the testnet Dai ABI we’ll be using, please click and copy the entire code snippet:
Note: this code is really long, take special care to copy it fully!
We need to parse it using json :
We also need to tell web3.py where to find this code on the Ethereum network. We do so with the following code:
We then use the ABI and the address to instantiate a smart contract object. This will give us access to the functions exposed by the code:
To test we’ve properly instantiated the contract, we’ll call a function that tells us how much Dai is held by the contract:
(The balance may be different by the time you run this)
Building the Transaction
To transfer the Dai from our Spanish Inquisition account ( my_account ), we’ll use the transfer function from the Dai smart contract, shown below:

We can see we need to pass in two parameters to the contract: to , which will be a hexadecimal Ethereum address and value , which is uint256 . Dealing with unsigned integers of 256 bits ( uint256 ) can be challenging for even seasoned developers. It’s a testament to unusual programming that has to be done at the smart contract level and frequently trips me up. Web3.py has a method we can use to cast values from integer to the format required for this smart contract, toHex . Since the amount we’re sending is below 16, we’ll just put a 0x on the front of it.
So our transaction currently looks like this:
These parameters are good for the Dai contract (we won’t get an error there), but we need more parameters for our transaction to run on the Ethereum network. Those values are chainId , gas and nonce .
ChainId helps web3.py know to which network the transaction is being sent. Different networks have different quirks (as we saw when we installed the middleware at the beginning for Rinkeby) and this helps web3.py bundle the transaction correctly. Rinkeby’s network ID is 4 , here’s a complete list of network IDs..
Gas is the small payment you make to miners on the network to run your transaction. Many people are surprised by this, but the amount is small (our transaction will cost 0.00007000 ETH, for example, but is demarcated in a particular denomination called Gwei). Gas helps run the network in a decentralized and secure way.
Nonce is a global variable particular to each Ethereum account. It serves the same purpose as the number on the bottom of the check: it allows for proper ordering of payments from different accounts. It increments up one after each transaction sent. Web3.py has a method for finding the current nonce of the address: w3.eth.getTransactionCount(ETHEREUM_ADDRESS) .
We’ll use the web3.py method .buildTransaction to incorporate these three variables into our transaction. I’m also adding in my friend’s Ethereum address and will send him 10 Dai:
Signing and Sending Transaction
Now that we have our transaction , we need to sign it with our private key. This is how the peer-to-peer protocol of Ethereum will know that it is this account that wants to send the money. To sign, we put the transaction object and our my_account._private_key into the following function:
Note: You should never post your real private key online! This is being done for educational purposes only. Double Note: Until this account is drained of test ether or test dai, the above command will be valid for the Rinkeby network
With our signed transaction, all we need to do now is send it to the network through our Infura API endpoint. We do this through our w3 object with the following command:
If that goes through, congratulations! You’ve just sent money using Python!
To find your transaction, you can print txn_hash and take the string value to Etherscan for Rinkeby. Here’s the hash I have (yours will be different!):
As you can see, using web3.py opens up all kinds of possibilities with your applications. In the next tutorial, I’m hoping to do something more built out with proper files and directories. For now, I just wanted to show you some of the incredible options blockchain can provide. I hope you found something interesting! The community is really eager to engage with new folks, be sure to reach out.
Thank you to Daniel Ellison for his feedback and comments, sometimes copied verbatim!
How to install web3 latest version manually in windows10?
. Then I added a reg key in regedit(«Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\4.0») as «VCTargetsPath» : «$(MSBuildExtensionsPath32)\Microsoft.Cpp\v4.0\V140» But it is still not working i.e., it gives the same error as mentioned.
I can install [email protected], but i want latest version as some of the functions from 0.20.7 has been removed/rearranged in v1.0.0 All I need is that nodejs should not complain when i do require(‘web3’).
I want to know that how to install web3 package with dependencies. Also how to tell E:\node_modules\scrypt\build\scrypt_wrapper.vcxproj (there is no scrypt folder inside node_modules when i checked) to use V140 or any installed platformSetTools.
I have following folders in C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0
- V120
- V140
Also is it possible to merge web3 (with dependencies) installed on someone else’s system into mine?
Update: I have following software installed in current pc:
Visual studio 2015
Microsoft .NET Framework (4.5 Multi targeting pack(MTP), 4.5 sdk, 4.5.1 MTP, 4.5.1 MTP (ENU), 4.5.1 SDK, 4.5.2 SDK, 4.5.2 MTP, 4.5.2 MTP ENU, 4.6 SDK, 4.6 Targeting Pack, 4.6 TP ENU, 4.6.1 SDK, 4.6.1 TP, 4.6.1 TP ENU, 4.7 SDK, 4.7 TP, 4.7 TP ENU)
Microsoft Visual C++ (2008,2012,2013,2017)
Also I can npm install web3 in a windows 7 (which also has visual studio 2015) and it executes/installs with no errors. This is output after attempting to install windows-build-tools and web3 packages.