DEV Community

Cover image for How to make an API Query the Blockchain
Cormac
Cormac

Posted on

How to make an API Query the Blockchain

Blockchain makes data public to anyone however it can be a little tricky to access.

In this blog I’ll break down how to make API requests to blockchains, using Avalanche as an example.

Much of Avalanche’s API functionality requires you to have access to each Node’s permissions or to run your own node which currently has a startup staking fee of 2,000 AVAX or $126,000.

For developers who wish to access Avalanches on-chain data without staking their own node, the Avalanche team provides a public endpoint to make api requests.

For this demonstration we will be request the latest block from Avalanche’s C-Chain.

Because the C-Chain is an instance of the Ethereum Virtual Machine powered, you can request much of the same information you could using GETH in Ethereum:

Let’s Get Started

To make things easy, we’ll first request the latest block curl. Using the first link above, we see we can request information from the C-chain using
.

By browsing through the eth execution-apis in the second link we can use eth_getBlockByNumber to get the latest block data.

Putting it all together we get the following curl request:

curl -X POST --data '{
"jsonrpc":"2.0",
"id" :1,
"method":"eth_getBlockByNumber",
"params":["latest", false]
}' -H 'content-type:application/json;' https://api.avax.network/ext/bc/C/rpc

If you open terminal, paste and enter this command you should get a response looking similar to this:

Image description

Congratulations! You just made a request to the Avalanche blockchain.

Avalanche Request using HTTP Postman

If you prefer http requests, we can make the same request be using postman:

Image description

Paste in link and the body into Postman like in the screenshot above, then press Send.

You’ll get a response looking like this:

Image description

Just like before we can see the latest block’s gas fee, height, transaction hashes and more.

We could also use Axios

await axios.post(postUrl, {
"jsonrpc": "2.0",
"id": 1,
"method": "eth_getBlockByNumber",
"params": ["latest", false]
})
.then((res: any) => {
console.log("AVAX BLOCK DATA: ", res.data.result)
})
.catch((err: any) => {
console.log("err: ", err.response)
return err
})

Once you get the hang of it, requesting Avalanche and Ethereum chains is pretty straightforward and by using public APIs we can save a lot of resources.

Discussion (0)