Today’s blockchain API tutorial will highlight numerous API examples and demonstrate how to fetch essential blockchain data. As we move forward, we’ll dive into Moralis’ industry-leading Blockchain API – the ultimate tool for blockchain data. It features numerous endpoints, allowing you to effortlessly get blocks, transactions, logs, events, and much more. To give you a little sneak peek, here’s a blockchain API example of how you can get the contents of a block with a single call to Moralis’ Blockchain API:
const response = await Moralis.EvmApi.block.getBlock({ "chain": "0x1", "blockNumberOrHash": "15863321" });
All you have to do is configure the chain
and blockNumberOrHash
parameters to fit your query before calling the endpoint in the example above. In return, you’ll get a response containing the block’s timestamp, number, hash, log bloom, miner, and much more. This is what it can look like:
{ "timestamp": "2021-05-07T11:08:35.000Z", "number": 12386788, "hash": "0x9b559aef7ea858608c2e554246fe4a24287e7aeeb976848df2b9a2531f4b9171", "parent_hash": "0x011d1fc45839de975cc55d758943f9f1d204f80a90eb631f3bf064b80d53e045", "nonce": "0xedeb2d8fd2b2bdec", "sha3_uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "logs_bloom": "0xdde5fc46c5d8bcbd58207//...", "transactions_root": "0xe4c7bf3aff7ad07f9e80d57f7189f0252592fee6321c2a9bd9b09b6ce0690d27", "state_root": "0x49e3bfe7b618e27fde8fa08884803a8458b502c6534af69873a3cc926a7c724b", "receipts_root": "0x7cf43d7e837284f036cf92c56973f5e27bdd253ca46168fa195a6b07fa719f23", "miner": "0xea674fdde714fd979de3edf0f56aa9716b898ec8", "difficulty": "7253857437305950", "total_difficulty": "24325637817906576196890", "size": "61271", "extra_data": "0x65746865726d696e652d6575726f70652d7765737433", "gas_limit": "14977947", "gas_used": "14964688", "transaction_count": "252", "transactions": { //... } }
And that’s it; when working with Moralis, getting blockchain data doesn’t have to be more difficult. However, if you want a more detailed tutorial and explore some more endpoints, read on! Also, if you want to follow along and make similar calls yourself, don’t forget to sign up with Moralis. You can create an account for free and immediately unlock the power of blockchain data!
Overview
In today’s tutorial, we’ll kickstart things by diving straight into the Moralis Blockchain API. In doing so, we’ll briefly explore what this tool does and cover some of its key benefits. From there, we’ll explore some prominent use cases and give you a practical example of how you can leverage the Blockchain API in each case. Lastly, to top things off, we’ll jump into an in-depth tutorial showing you how to get the contents of a block by its number in three straightforward steps:
- Get a Moralis API Key
- Write a Script Calling the
getBlock()
Endpoint - Execute the Code
Also, if you’re serious about building blockchain projects, consider checking out some more Web3 data tools Moralis offers. For instance, explore the Price API to learn how to seamlessly get prices of crypto and integrate this data into your projects!
Nevertheless, without further ado, let’s explore Moralis’ industry-leading Blockchain API!
What is the Moralis Blockchain API?
The Moralis Blockchain API is an industry-leading interface that allows you to seamlessly unlock the power of raw blockchain data with speed and precision. With only single lines of code, you can effortlessly get blocks, transactions, logs, events, and much more with the Blockchain API. As such, when working with the Moralis, it has never been easier to build Web3 projects!
So, what are the features of the Blockchain API?
- Get Block Data: Get info on particular blocks – including timestamps, gas used, miners, transactions, etc. – across multiple blockchain networks.
- Fetch Transactions and Internal Transactions: Seamlessly access all historical and real-time transactions of an address.
- Query Logs and Events: Use the Blockchain API to query logs and events of any smart contract across all major EVM chains.
- Raw and Decoded Data: Get both raw and decoded data based on contract ABIs.
- Labels: Efforlessly interpret transactions with enriched data labeling, including receiver and sender address labels.
- And more!
Additionally, the Blockchain API is cross-chain compatible. This means you can query blockchain data across all major networks, including Ethereum, Polygon, BNB Smart Chain, Arbitrum, and many others!
Benefits of the Moralis Blockchain API
Along with many powerful features, the Blockchain API also provides many benefits. Here are four prominent examples:
- Scalable: Our Blockchain API is built for growth. Consequently, as your projects see increased adoption, the interface will have no trouble delivering even as your user base grows.
- Real-Time: The Blockchain API is fast, indexes real-time data, and ensures immediate access to the latest blockchain info.
- Precise: Data accuracy is essential when building Web3 projects, which is why the Blockchain API always offers precise and reliable data.
- Organized: Blockchain data can be messy, and we believe in digestible and detailed information. As such, our Blockchain API organizes blocks into transfers, transactions, and logs, giving you a structured way to navigate the crypto landscape.
Now, with an overview of our industry-leading Blockchain API, let’s explore some of its use cases!
Blockchain API Examples and Use Cases
The Moralis Blockchain API has many prominent use cases, and in this section, we’ll look at three examples:
- Block Explorers: Block explorers are online tools enabling you to search for real-time and historical data about a blockchain. This usually includes block data, addresses, transactions, and much more. Some prominent examples of already existing block explorers are Etherscan, PolygonScan, and BscScan.
Since explorers allow you to search for information about a blockchain, you need seamless access to this data (e.g., transactions, blocks, logs, etc.) when building one. And the easiest way to query this info is to use the Moralis Blockchain API.
- Web3 Wallets: Web3 wallets are software allowing you to store and manage digital assets, including fungible and non-fungible tokens. Some examples of prominent wallet providers include MetaMask and Rainbow.
A common feature of most Web3 wallets is to display each user’s wallet activity. This gives users an overview of all their trades, which can be useful in many cases. To display this information, you need access to transaction info and events, which is where our Blockchain API enters the equation.
- Decentralized Application (Dapp) Alerts: When building dapps, it can be highly beneficial to set up alert systems to notify users of important events. This can, for instance, be alerts for when crypto whales sell a large portion of their holdings.
To set up alert systems like this, you need access to smart contract events and logs, which you can effortlessly get with only single lines of code when working with our Blockchain API.
Nevertheless, that covers three prominent use cases. In the following sections, we’ll expand on this further by providing examples of how to use the Blockchain API to get the info you need with multiple programming languages!
Block Explorers: JavaScript Blockchain API Example
As mentioned above, you need access to a lot of data when building a block explorer. With the Moralis Blockchain API, you can get the info you need in a heartbeat!
All you have to do is call the getBlock()
endpoint while passing along two parameters: chain
and blockNumberOrHash
. Here’s an example of what it might look like:
const response = await Moralis.EvmApi.block.getBlock({ "chain": "0x1", "blockNumberOrHash": "15863321" });
In return for calling the endpoint above, you’ll get a comprehensive response looking something like this:
{ "timestamp": "2021-05-07T11:08:35.000Z", "number": 12386788, "hash": "0x9b559aef7ea858608c2e554246fe4a24287e7aeeb976848df2b9a2531f4b9171", "parent_hash": "0x011d1fc45839de975cc55d758943f9f1d204f80a90eb631f3bf064b80d53e045", "nonce": "0xedeb2d8fd2b2bdec", "sha3_uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "logs_bloom": "0xdde5fc46c5d8bcbd58207//...", "transactions_root": "0xe4c7bf3aff7ad07f9e80d57f7189f0252592fee6321c2a9bd9b09b6ce0690d27", "state_root": "0x49e3bfe7b618e27fde8fa08884803a8458b502c6534af69873a3cc926a7c724b", "receipts_root": "0x7cf43d7e837284f036cf92c56973f5e27bdd253ca46168fa195a6b07fa719f23", "miner": "0xea674fdde714fd979de3edf0f56aa9716b898ec8", "difficulty": "7253857437305950", "total_difficulty": "24325637817906576196890", "size": "61271", "extra_data": "0x65746865726d696e652d6575726f70652d7765737433", "gas_limit": "14977947", "gas_used": "14964688", "transaction_count": "252", "transactions": { //... } }
Note: We used JavaScript for the example above. However, you can also use multiple other programming languages, including Python, TypeScript, etc. To learn more about this, check out our official get block by block number documentation page.
Web3 Wallets: Python Blockchain API Example
When building a Web3 wallet, you need seamless access to a user’s transaction history so you can display this information. With our Blockchain API, you can seamlessly get this data with a single call to the get_wallet_transactions()
endpoint while passing along two parameters: chain
and address
. Here’s an example of what it might look like:
params = { "chain": "eth", "address": "0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326" } result = evm_api.transaction.get_wallet_transactions( api_key=api_key, params=params, )
In return for calling the get_wallet_transactions()
endpoint, you get an array of all inbound and outbound transactions of the provided address. This is what the response can look like:
{ "page_size": 100, "page": 0, "cursor": "eyJhbGciOiJIUzI1N//...", "result": [ { "hash": "0x4742fc54f2f6f1121d472ebc6cad6821f9d79407237c36782641d9873832b825", "nonce": "337201", "transaction_index": "149", "from_address": "0x1f9090aae28b8a3dceadf281b0f12828e676c326", "from_address_label": "rsync-builder", "to_address": "0xde2a1a6dd691e56fc225d13ab51d4e05ea148f2f", "to_address_label": null, "value": "38602051712948608", "gas": "21000", "gas_price": "13881451241", "input": "0x", "receipt_cumulative_gas_used": "29986680", "receipt_gas_used": "21000", "receipt_contract_address": null, "receipt_root": null, "receipt_status": "1", "block_timestamp": "2023-10-31T07:44:23.000Z", "block_number": "18468703", "block_hash": "0x2c00ee96af806132e858edc91406843258d234783c39d30313644b46c2af2315", "transfer_index": [ 18468703, 149 ] //... ]
Note: We used Python for this example. However, you can also use many other languages, including JavaScript, TypeScript, etc. Check out the official get transactions of address documentation to learn more.
Dapp Alerts: TypeScript Blockchain API Example
When building dapps, you often need an easy way to set up alerts so you can notify your end users of important events. To do so, you need access to events and logs of smart contracts.
So, to get the logs of any contract, all you need is a single API call to the getContractLogs()
endpoint while passing along three parameters: address
, chain
, and topic
. This is what a request might look like:
const response = await Moralis.EvmApi.events.getContractLogs({ "chain": "0x1", "topic0": "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "address": "0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB" });
In return for calling the endpoint above, you’ll get a response containing all logs based on your specifications. Here’s an example of what it might look like:
{ "page_size": 100, "page": 1, "cursor": "eyJhbGciO//...", "result": [ { "transaction_hash": "0x4abb0d08b5fea482ce708b880c60757635a38203b55fd064148c3f6301206efa", "address": "0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb", "block_timestamp": "2023-10-31T07:33:35.000Z", "block_number": "18468649", "block_hash": "0x7fd8e733e3a7c03624b9bdcaa058a6be60089093a1d0976db450fb60dbafc0db", "data": "0x0000000000000000000000000000000000000000000000000000000000000001", "topic0": "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "topic1": "0x000000000000000000000000ff36ff458b51dcd034598c56f65a8491427dc572", "topic2": "0x000000000000000000000000e42abe865a7f83f8662e0d602195ade90a569ff0", "topic3": null, "transaction_index": 76, "log_index": 73 }, //... ]
Note: We used TypeScript in the example above. However, you can get logs using other programming languages as well, including JavaScript, Python, and others. To learn more, check out the official get logs for contract documentation.
That’s it for our three examples. In the next section, we’ll give you a more in-depth tutorial on how you can call the various endpoints of the Blockchain API!
Step-by-Step Blockchain API Tutorial
In this section, we’ll give you an in-depth tutorial on how you can get block data by its number using the Moralis Blockchain API. Thanks to the accessibility of this industry-leading Web3 development tool, you can get the info you need in three straightforward steps:
- Get a Moralis API Key
- Write a Script Calling the
getBlock()
Endpoint - Execute the Code
However, before you can call the getBlock()
endpoint, you need to deal with a few prerequisites!
Prerequisites
In today’s blockchain API example tutorial, we’ll be using JavaScript. As such, if you want to follow along, make sure you have the following ready:
Step 1: Get a Moralis API Key
To be able to call the Blockchain API and the getBlock()
endpoint, you need a Moralis API key. To get an API key, you need a Moralis account. So, if you haven’t already, click on the ”Start for Free” button at the top right and set up your account:
With a Moralis account at hand, head on over to the ”Settings” tab, scroll down to the ”API Keys” section, and copy your key:
Keep it for now, as you need it in the next section!
Step 2: Write a Script Calling the getBlock()
Endpoint
For the second step, start by setting up a new project in your integrated development environment (IDE). From there, open a new terminal and run the command below in the project’s root folder to install the Moralis SDK:
npm install moralis @moralisweb3/common-evm-utils
Next, create a new ”index.js” file and add the following code:
const Moralis = require("moralis").default; const { EvmChain } = require("@moralisweb3/common-evm-utils"); const runApp = async () => { await Moralis.start({ apiKey: "YOUR_API_KEY", // ...and any other configuration }); const blockNumberOrHash = "15863321"; const chain = EvmChain.ETHEREUM; const response = await Moralis.EvmApi.block.getBlock({ blockNumberOrHash, chain, }); console.log(response.toJSON()); }; runApp();
You then need to change the code slightly, and you can start by replacing YOUR_API_KEY
with the key you copied in the previous step to initialize Moralis:
Next, configure the blockNumberOrHash
and chain
constants to fit your query:
We then pass blockNumberOrHash
and chain
as parameters when calling the getBlock()
endpoint:
That’s it; you’re now ready to run the code!
Step 3: Execute the Code
For the final step, open a new terminal, cd
into your project’s root folder, and run the following command:
node index.js
Executing the command above will run the code, and in return, you’ll get a bunch of information related to the block in question. Some prominent examples include a timestamp, log bloom, gas used, the miner, an array of transactions, and much more. This is what it might look like:
{ "timestamp": "2022-10-30T20:39:11.000Z", "number": "15863321", "hash": "0x4f5d3bb78f0311301ef282b281d23e178ced236a7ae465820fe6edeba609954a", "parent_hash": "0x27e61d430386d7b4a144bee6e120a57010fbdb3cf963ca37e2d20b5452203621", "nonce": "0x0000000000000000", "sha3_uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "logs_bloom": "0x11e91824051850625f13 \...", "transactions_root": "0x1e0b205c9c48af7dfa3f277c8ec2ba403dc4ab63635a18bbfe532097527fb18e", "state_root": "0xcb1df24273693eb33869961233baac112adbdf51e980e5cf8b8aa7084e8063be", "receipts_root": "0x3a3d89417ad3898d47f66155e0e5fdf3e1efde2a6f389e7b051acf729db28617", "miner": "0x388C818CA8B9251b393131C08a736A67ccB19297", "difficulty": "0", "total_difficulty": "58750003716598360000000", "size": "117595", "extra_data": "0x", "gas_limit": "30000000", "gas_used": "19044124", "transaction_count": "156", "base_fee_per_gas": "8175724594", "transactions": [ { //... ] }
Congratulations; that’s it for this blockchain API tutorial. You now know how to easily get a block’s contents using its number!
Also, this was just a simple blockchain API example, and you can follow the same steps (with minor configurations to the code in the second part) to call any other of our API endpoints.
To explore all existing endpoints, check out the official Moralis Blockchain API documentation page!
Summary: Blockchain API Example and Tutorial
In today’s tutorial, we explored the Moralis Blockchain API, which is an industry-leading tool for getting and integrating blockchain data into Web3 projects, including transactions, logs, events, etc. This tool boasts many prominent features and supports all major chains, making Moralis clearly stand out as the premier option among the best blockchain API providers in the business!
In addition to exploring the Blockchain API, we also showed you how to use this tool to get the content of a block by its number in three straightforward steps:
- Get a Moralis API Key
- Write a Script Calling the
getBlock()
Endpoint - Execute the Code
As such, if you have followed along this far, you now have the skills to fetch data, such as blocks, events, logs, and much more, with Moralis’ Blockchain API!
If you liked this Blockchain API tutorial, consider reading more guides here on the blog. For instance, explore the intricacies of meta transactions, read about EIP-4844, or learn how to set up notifications for NFT sales. Also, don’t forget to sign up with Moralis. You can create an account for free, and you’ll get immediate access to all industry-leading tools, including the Blockchain API!
Read More: moralis.io