Checking the Balances of a BTC/bitcoin wallet address can be done in two ways: Querying a Node, or Querying a Third party API.
Querying a Node requires running your own node, or some other existing nodes. Setting up a node could be complex and there is running cost incurred. Accessing some existing node may require a more complexity coding. However, this method allows low latency – as the data from the chain is almost real-time.
On the other hand, we can query a third party API (which can be seen as a centralized service). The API node monitors and processes the data from the blockchain and store them in database(s) before the data becomes available for API calls. So there is a small delay. However, the coding skills required for this are much smaller than directly accessing the Blockchain API.
This post shows you two ways to get the balance of a BTC wallet via the third party APIs: mempool and blockcypher.
Checking Balances of BTC Wallets by Mempool API
We can check the balance of any BTC/Bitcoin Wallet Addresses via the following NodeJs function by using the API from Mempool.space (which provides free and paid version of API calls):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
const axios = require('axios'); async function getBTCAddressBalance(btcAddress) { const url = `https://mempool.space/api/address/${btcAddress}`; try { const response = await axios.get(url); const { chain_stats, mempool_stats } = response.data; const confirmedBalance = chain_stats.funded_txo_sum - chain_stats.spent_txo_sum; const unconfirmedBalance = mempool_stats.funded_txo_sum - mempool_stats.spent_txo_sum; const totalBalance = confirmedBalance + unconfirmedBalance; console.log(`Address: ${btcAddress}`); console.log(`Confirmed Balance: ${confirmedBalance} satoshis`); console.log(`Unconfirmed Balance: ${unconfirmedBalance} satoshis`); console.log(`Total Balance: ${totalBalance} satoshis`); return { "total": totalBalance, "confirmedBalance": confirmedBalance, "unconfirmedBalance": unconfirmedBalance, }; } catch (error) { console.error('Error:', error.message); return null; } } |
const axios = require('axios'); async function getBTCAddressBalance(btcAddress) { const url = `https://mempool.space/api/address/${btcAddress}`; try { const response = await axios.get(url); const { chain_stats, mempool_stats } = response.data; const confirmedBalance = chain_stats.funded_txo_sum - chain_stats.spent_txo_sum; const unconfirmedBalance = mempool_stats.funded_txo_sum - mempool_stats.spent_txo_sum; const totalBalance = confirmedBalance + unconfirmedBalance; console.log(`Address: ${btcAddress}`); console.log(`Confirmed Balance: ${confirmedBalance} satoshis`); console.log(`Unconfirmed Balance: ${unconfirmedBalance} satoshis`); console.log(`Total Balance: ${totalBalance} satoshis`); return { "total": totalBalance, "confirmedBalance": confirmedBalance, "unconfirmedBalance": unconfirmedBalance, }; } catch (error) { console.error('Error:', error.message); return null; } }
Converting the above Javascript (Node Js) function of getting a balance of a Bitcoin Wallet to Python, here’s how you can convert the JavaScript function into Python using the requests library to perform HTTP requests:
This Python function performs the same task as the original JavaScript function: it fetches the balance of a Bitcoin address using the Mempool Space API and prints out the confirmed, unconfirmed, and total balance in satoshis. It handles errors by catching exceptions that might occur during the HTTP request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import requests def get_btc_address_balance(btc_address): url = f'https://mempool.space/api/address/{btc_address}' try: response = requests.get(url) response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code data = response.json() chain_stats = data['chain_stats'] mempool_stats = data['mempool_stats'] confirmed_balance = chain_stats['funded_txo_sum'] - chain_stats['spent_txo_sum'] unconfirmed_balance = mempool_stats['funded_txo_sum'] - mempool_stats['spent_txo_sum'] total_balance = confirmed_balance + unconfirmed_balance print(f'Address: {btc_address}') print(f'Confirmed Balance: {confirmed_balance} satoshis') print(f'Unconfirmed Balance: {unconfirmed_balance} satoshis') print(f'Total Balance: {total_balance} satoshis') return { "total": total_balance, "confirmedBalance": confirmed_balance, "unconfirmedBalance": unconfirmed_balance, } except requests.RequestException as error: print('Error:', error) return None |
import requests def get_btc_address_balance(btc_address): url = f'https://mempool.space/api/address/{btc_address}' try: response = requests.get(url) response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code data = response.json() chain_stats = data['chain_stats'] mempool_stats = data['mempool_stats'] confirmed_balance = chain_stats['funded_txo_sum'] - chain_stats['spent_txo_sum'] unconfirmed_balance = mempool_stats['funded_txo_sum'] - mempool_stats['spent_txo_sum'] total_balance = confirmed_balance + unconfirmed_balance print(f'Address: {btc_address}') print(f'Confirmed Balance: {confirmed_balance} satoshis') print(f'Unconfirmed Balance: {unconfirmed_balance} satoshis') print(f'Total Balance: {total_balance} satoshis') return { "total": total_balance, "confirmedBalance": confirmed_balance, "unconfirmedBalance": unconfirmed_balance, } except requests.RequestException as error: print('Error:', error) return None
Checking Balances of BTC Wallet Addressess by BlockCypher API
We can also utilize the Blockcypher API to query the balance for a BTC bitcoin wallet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const axios = require('axios'); async function getBTCBalance(address) { const url = `https://api.blockcypher.com/v1/btc/main/addrs/${address}/balance`; try { const response = await axios.get(url); const balance = response.data.balance; console.log('Balance in Satoshis:', balance); console.log('Balance in BTC:', balance / 1e8); return { "balance": balance, "balance_in_btc": balance / 1e8 } } catch (error) { console.error('Error:', error.message); } } |
const axios = require('axios'); async function getBTCBalance(address) { const url = `https://api.blockcypher.com/v1/btc/main/addrs/${address}/balance`; try { const response = await axios.get(url); const balance = response.data.balance; console.log('Balance in Satoshis:', balance); console.log('Balance in BTC:', balance / 1e8); return { "balance": balance, "balance_in_btc": balance / 1e8 } } catch (error) { console.error('Error:', error.message); } }
The following Python function mimics the behavior of the original JavaScript version: it retrieves and prints the balance of a specified Bitcoin address from the BlockCypher API, both in satoshis and in BTC. It handles potential HTTP or other request-related errors gracefully.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import requests def get_btc_balance(address): url = f'https://api.blockcypher.com/v1/btc/main/addrs/{address}/balance' try: response = requests.get(url) response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code data = response.json() balance = data['balance'] print('Balance in Satoshis:', balance) print('Balance in BTC:', balance / 1e8) return { "balance": balance, "balance_in_btc": balance / 1e8 } except requests.RequestException as error: print('Error:', error) return None |
import requests def get_btc_balance(address): url = f'https://api.blockcypher.com/v1/btc/main/addrs/{address}/balance' try: response = requests.get(url) response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code data = response.json() balance = data['balance'] print('Balance in Satoshis:', balance) print('Balance in BTC:', balance / 1e8) return { "balance": balance, "balance_in_btc": balance / 1e8 } except requests.RequestException as error: print('Error:', error) return None
Please note that the balance for a BTC wallet is not directly stored on the chain because there is a return-changes process: Remember to Specify the Change Address Parameter when Sending Funds from One Bitcoin Wallet to Another Address
Blockchain Web3 Technology
Bitcoin/BTC Wallets
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading…
896 words
Last Post: Teaching Kids Programming – The Birthday Candles Problem (Three Algorithms)