Get Blocks and Transactions from Cosmos Blockchain API

By Adam Temple

The Cosmos-SDK based blockchains automatically create API's to consume. In this article I will walk you through pulling data from Cosmos Hub blockchain. 

First we need a server to query. I have used cosmos.network quite a bit, but you can find others here: https://chain-registry.netlify.app/

Let's say you were doing this inside of your app. The first thing you need to do is query for the latest block. 

1. Query For The Latest Block

https://rpc.cosmos.network/status

It returns JSON. The part we care about is: "latest_block_height": "10009478"

2. Get block by height

We have the block height, so let's get the actual block. I prefer the RPC endpoint when it provides the right into. The REST and RCP endpoints provide different info. RPC works great in this instance:

https://rpc.cosmos.network/block?height=10009478

Actually, we don't even need the block, but this is a life skill you will need, so I am leave'n it!

3. Get list of block transactions

Next we get all the transactions that are in the block.

https://rpc.cosmos.network/tx_search?query=%22tx.height=10009478%22

Explore JSON and you can see each transaction hash. 

"hash":"51E0B909719101CE3DCECD5B62AEB4E8F2E39E64D33F5D54BA49035C2C80AE8D"

4. Grab each transaction

You will loop through each transaction in the list and download each separately. Well, that's the way I do it, so let me know if there's a better way. The non RPC API provides the most information:

https://api.cosmos.network/cosmos/tx/v1beta1/txs/51E0B909719101CE3DCECD5B62AEB4E8F2E39E64D33F5D54BA49035C2C80AE8D

In case you want to use RPC, here it is for reference:

https://rpc.cosmos.network/tx?hash=0x51E0B909719101CE3DCECD5B62AEB4E8F2E39E64D33F5D54BA49035C2C80AE8D

Feel The Power!

With this power along you can slay the crypto world with your creative reach. The API is very useful, but when you need to go deeper and build your own blockchain specific app, the only option for cool kids is Cosmos SDK.