How to Query the Ethereum Blockchain with Python

Trevor French
Trevor French
Published in
2 min readSep 8, 2022

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:

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.

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:

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:

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
Trevor French

I am an Analytics Manager in the Crypto industry with an M.S. in Data Analytics and a B.S. in Business Analytics. I talk about R, Python, and Data Science.