How to Query the Ethereum Blockchain with Python

You, PythonEthereumCrypto
Back

Crypto data is becoming more and more prevalent. While there are tons of tools and APIs which allow you to use their service to access this data, you may have wondered “How can I get this data myself?”.

The first thing you’ll need is a node. You could set one up yourself; however, for most people it will be more practical to use a hosted node from services such as Infura or Quicknode.

Working backwards, our full code is going to look like this:

# TITLE: Querying the Ethereum Blockchain with Python
# DESCRIPTION: 
#   Uses web3.py to query your ETH balance
# TODO:
# - 
# - 
# -

# MODULES
from web3 import Web3, HTTPProvider

# CONNECT TO NODE
w3 = Web3(HTTPProvider('[YOUR NODE]'))

# GET CURRENT ETH BALANCE
balance = w3.eth.get_balance('[YOUR ADDRESS]') / 1e18
print(balance)

This script will return the wallet balance for any given address and, the best part, it’s only three real lines of code!

The first thing you’ll need to do is import the correct dependencies. In our case, we’re using web3.py. This library allows you to do much more than just query user balances so explore the documentation further for your specific use case.

# MODULES
from web3 import Web3, HTTPProvider

The next thing you’ll need to do is connect to your node. Once you create an Infura account, you should see a screen that looks like this:

Press “CREATE NEW KEY” in the top right corner and fill out the required fields.

You will then be redirected to a page containing your credentials. Copy your desired URL from the “Network Endpoints” section. Your URL should look similar to this: https://mainnet.infura.io/v3/{YOUR_API_KEY}

Now, just paste your URL into the code like this:

# CONNECT TO NODE
w3 = Web3(HTTPProvider('https://mainnet.infura.io/v3/{YOUR_API_KEY}'))

Finally, you can call the balance function (or any other available web3.py function). The balance function will accept either a wallet address or an ENS domain name. Additionally, depending on the currency you are querying, you may need to format the resulting number. For Ethereum, you will need to divide the output by 1e18.

Feel free to try this out with my wallet:

# GET CURRENT ETH BALANCE
balance = w3.eth.get_balance('trevorfrench.eth') / 1e18
print(balance)

You’re all set! This just scrapes the surface of what is possible but hopefully it builds some confidence and excitement.

Video here: https://www.youtube.com/watch?v=Q_t9a9uiaYY

© Trevor French.RSS