Post

How to Use the Moralis API to Fetch Blockchain Data: An Example with NFT Tokens on the EVM Chain

How to Use the Moralis API to Fetch Blockchain Data: An Example with NFT Tokens on the EVM Chain

The blockchain ecosystem continues to grow at an accelerated pace, with various platforms and APIs designed to simplify the development process. One such API is Moralis, which provides a robust set of tools for building decentralized applications (dApps). In this blog post, we’ll focus on how to use the Moralis API to fetch blockchain data for NFTs on the Ethereum Virtual Machine (EVM) chain.

🚀 What is Moralis?

Moralis is a backend-as-a-service (BaaS) platform that offers an easy-to-use API for developers working with blockchain data. It provides a range of services, including real-time data synchronization, user authentication, and access to on-chain data for multiple blockchains. Moralis allows you to quickly integrate blockchain functionality into your applications without worrying about managing infrastructure or dealing with complex smart contracts directly.

Moralis supports various blockchains, including Ethereum, Binance Smart Chain (BSC), Polygon, and more. Its powerful tools and services make it an ideal choice for building dApps, especially for fetching and displaying data from smart contracts, such as NFTs.


🖼️ How Moralis Works with NFTs

NFTs (Non-Fungible Tokens) are a type of digital asset that represents ownership of unique items, such as art, music, or collectibles. NFTs are typically deployed on blockchains like Ethereum, and they follow specific standards like ERC-721 and ERC-1155.

The Moralis API allows developers to interact with blockchain data easily and retrieve information about NFTs such as:

  • Ownership of an NFT
  • Metadata associated with an NFT
  • Transaction history
  • Token transfers

In the following sections, we’ll demonstrate how to use Moralis to fetch data for an NFT token located on an EVM-compatible blockchain (like Ethereum or Polygon).


🛠️ Prerequisites

Before you begin, you’ll need:

  1. A Moralis account – You can sign up for free on the Moralis website.
  2. A Moralis app – Create an app from the Moralis dashboard to obtain your API keys.
  3. A JavaScript environment – This example will use JavaScript with Node.js.

Additionally, you should be familiar with basic JavaScript, blockchain concepts, and NFTs.


⚙️ Step 1: Set Up Moralis

First, you’ll need to install the Moralis SDK and set up your project. In this example, we’ll use Node.js.

  1. Install the required packages:
    1
    2
    
     npm init -y
     npm install moralis axios
    
  2. Create an index.js file in your project folder.

  3. Import the Moralis SDK and initialize it with your application’s API credentials:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
     const Moralis = require('moralis/node');
     const axios = require('axios');
    
     const MORALIS_APP_ID = 'your-moralis-app-id';
     const MORALIS_SERVER_URL = 'your-moralis-server-url';
    
     Moralis.start({ 
       appId: MORALIS_APP_ID, 
       serverUrl: MORALIS_SERVER_URL 
     });
    

You can obtain your App ID and Server URL by creating a new Moralis app in the Moralis dashboard.


🔍 Step 2: Fetching NFT Data

Now that your project is set up, let’s write a function to fetch the metadata for a specific NFT token. We will use an example NFT located on an EVM-compatible chain (e.g., Ethereum).

  1. Define the contract address and token ID of the NFT you want to fetch. For example, let’s consider the contract address for CryptoKitties on Ethereum:
    1
    2
    
     const contractAddress = '0x06012c8cf97BEaD5deAe237070F9587f8E7A266d'; // CryptoKitties contract address
     const tokenId = 1; // Token ID of a specific CryptoKitty
    
  2. Use Moralis to fetch the NFT metadata:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
     async function getNFTMetadata(contractAddress, tokenId) {
         try {
             // Fetch the NFT metadata
             const options = {
                 chain: 'eth', // Ethereum blockchain
                 address: contractAddress,
                 token_id: tokenId.toString()
             };
    
             const nft = await Moralis.Web3API.token.getTokenIdMetadata(options);
             console.log('NFT Metadata:', nft);
         } catch (error) {
             console.error('Error fetching NFT data:', error);
         }
     }
    
     // Call the function
     getNFTMetadata(contractAddress, tokenId);
    

The getTokenIdMetadata function fetches the metadata of the NFT specified by its contract address and token ID. This metadata includes details like the NFT’s name, image, description, and other relevant attributes.


🧩 Step 3: Parsing the Metadata

When you fetch the NFT data, it’s typically returned in a JSON format that contains various details about the token. Below is an example of the data structure:

1
2
3
4
5
6
7
8
9
{
  "name": "CryptoKitty #1",
  "image": "https://ipfs.io/ipfs/Qm...imageurl",
  "description": "A cute CryptoKitty!",
  "attributes": [
    { "trait_type": "Fur", "value": "Spotted" },
    { "trait_type": "Eyes", "value": "Big" }
  ]
}

You can extract relevant information like this:

1
2
3
4
5
6
7
8
9
10
11
async function displayNFTDetails(nft) {
    const { name, image, description, attributes } = nft;

    console.log('NFT Name:', name);
    console.log('Description:', description);
    console.log('Image URL:', image);
    console.log('Attributes:');
    attributes.forEach(attr => {
        console.log(`${attr.trait_type}: ${attr.value}`);
    });
}

🏃 Step 4: Testing and Running the Code

Once your code is ready, you can run your script using Node.js:

1
node index.js

If everything is set up correctly, the metadata of the specified NFT will be printed to the console.


🧠 Final Thoughts

In this blog post, we covered how to use the Moralis API to fetch data from blockchain networks, specifically for NFTs located on EVM-compatible chains like Ethereum. Moralis offers an incredibly simple way to access blockchain data, without the need for managing complex infrastructure or querying raw blockchain data.

Whether you’re building an NFT marketplace, a dApp, or just exploring blockchain data, Moralis is an invaluable tool to streamline your development process. By utilizing its APIs, you can quickly access metadata, user data, and transaction history.

I hope this article has helped you understand how to integrate Moralis into your projects. Happy coding, and don’t hesitate to explore more about the powerful features that Moralis offers for decentralized applications!

This post is licensed under CC BY 4.0 by the author.