DEV Community

Cover image for How to Create an NFT Viewer with Infura's New NFT API
Alvin Lee
Alvin Lee

Posted on • Originally published at Medium

How to Create an NFT Viewer with Infura's New NFT API

Digital collectibles (or NFTs, which stands for “non-fungible tokens”) have arguably been one of the biggest breakthrough applications of web3. If you’re a creator building with digital collectibles, however, you’ve probably noticed that working with them from code can be complicated!

Creating NFTs, minting NFTs, writing smart contracts … even something as simple as building a dapp to view them all from a wallet can be difficult. This is where Infura’s new NFT API comes in.

With this API, you can replace a lot of tedious code with a single API call. Build a digital collectibles marketplace, mint digital art, do any-NFT-thing you want, and all on the chain of your choice (including the Ethereum blockchain, Polygon, zkEVM, and more).

It’s really easy to create something beautiful with just a few lines of code!

In this tutorial, we’ll walk through the process of creating a simple dapp that allows you to view digital collectibles owned by a particular wallet address (similar to OpenSea or Rarible).

In the first part, we’ll walk through a step-by-step guide to writing a simple Node script that outputs ownership information to the terminal.

In the second part, we’ll build on top of our script and launch a full-blown React app.

Part 1: The Digital Collectible Ownership Script

Step 1: Install NPM and Node

Our project will be built with Node and npm. If you don’t have these installed on your local machine, you can do so here.

To ensure everything is working correctly, run the following command:

$ node -v
Enter fullscreen mode Exit fullscreen mode

If all goes well, you should see a version number for Node.

Step 2: Sign Up for an Infura Account

Next, we need access to the Infura NFT API. This allows us to access digital collectible ownership information for a wallet address.

Sign up for a free Infura account here. Once you’ve created your account, navigate to the dashboard and Create New Key.

Image description

For the network, choose Web3 API, and name it NFT Viewer.

Once you click on Create, Infura will generate an API key for you, and give you access to its NFT API endpoints.

The NFT API is in open beta and can be accessed from https://nft.api.infura.io/. To authenticate requests to this API, we’ll need a username and a password.

The username is the API key that you see at the top of your project page. The password is the API secret which can be obtained by navigating to the Security tab of your project.

Step 3: Create a Node Project and Install Dependencies

Let’s set up an empty project repository by running the following commands:

$ mkdir nft-ownership && cd nft-ownership
$ npm init -y
Enter fullscreen mode Exit fullscreen mode

In order to make HTTP requests, we will use the Axios library. Install this by running:

$ npm install axios
Enter fullscreen mode Exit fullscreen mode

Step 4: Write the Ownership Script

To reiterate, we want to extract a list of all NFTs (and their associated metadata) for any given wallet address.

If you look at the Infura API documentation, you will see that this information is readily available to us through a single call to an endpoint listed under the Metadata section. The only thing we need to supply is the wallet address.

Create a new file called index.js, and add the following code:

const axios = require('axios')

// Wallet address
const walletAddress = "0x0a267cf51ef038fc00e71801f5a524aec06e4f07"

// Set chain ID to 1 for Ethereum
const chainId = "1"

// Infura NFT API URL
const baseUrl = "https://nft.api.infura.io"
const url = `${baseUrl}/networks/${chainId}/accounts/${walletAddress}/assets/nfts`

// Configure the request
const config = {
    method: 'get',
    url: url,
    auth: {
        username: '<-- INFURA API KEY –>',
        password: '<-- INFURA API SECRET →',
    }
};

// Make request to NFT API
axios(config)
    .then(response => {
        console.log(response['data'])
    })
    .catch(error => console.log('error', error)); 
Enter fullscreen mode Exit fullscreen mode

Run the script using the following command:

$ node index.js
Enter fullscreen mode Exit fullscreen mode

You should see an output that looks something like this:

{
  total: 44,
  pageNumber: 1,
  pageSize: 100,
  network: 'ETHEREUM',
  account: '0x0a267cf51ef038fc00e71801f5a524aec06e4f07',
  cursor: null,
  assets: [
    {
      contract: '0xb94c3fd0016888bab09dbc229f9397294e828a54',
      tokenId: '0',
      supply: '1',
      type: 'ERC1155',
      metadata: [Object]
    },
   
    {
      contract: '0x030d5ffc1f8a64c58a040e0216b96e52c5cbe569',
      tokenId: '612',
      supply: '1',
      type: 'ERC721',
      metadata: [Object]
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

That was really simple! Now we have all the digital collectibles owned by the wallet in one single call. Infura also conveniently sends us the associated metadata information, such as title, description, image URL, and so on.

Now that we know how to use the API to get NFT ownership information, let’s build an app on top of this script.

Part 2: The Digital Collectibles Viewer App

Step 1: Download the Starter Repository

We have a React repository already made available to you which implements several styles to make our app look pretty. You can download it here.

Note that we will be writing all the logic of the app from scratch.

Step 2: Add the Infura Credentials

In the src folder, create a new folder called data, and add a file called constants.js. In this file, add the following code:

const API_KEY = "<-- INFURA API KEY –>";
const API_SECRET = "<-- INFURA API SECRET –>"

export { API_KEY, API_SECRET }
Enter fullscreen mode Exit fullscreen mode

Step 3: Write the App Logic

We are now ready to write the main app in logic in the App.js file.

This is how our app works:

  1. The user enters a wallet address in a form and clicks Submit.

  2. The app takes the wallet address and uses code from Part 1 to get all NFTs owned by the address.

  3. The API response is cleaned, and then finally displayed on the app.

Add the following code:

import { useState } from 'react';
import './App.css';
import axios from 'axios';

// Get Infura API credentials
import { API_KEY, API_SECRET } from './data/constants';

function App() {

  // Variable that stores wallet address from form
  const [walletAddress, setWalletAddress] = useState('');

  // Variable that stores response from the NFT API
  const [nfts, setNfts] = useState([]);

  // Input handler
  const walletHandler = (e) => {
    setWalletAddress(e.target.value);
  }

  // Form handler that issues requests to NFT API
  const formHandler = async (e) => {

    // Prevent page refresh on form submit
    e.preventDefault();

    if (walletAddress.length > 0) {
      // Set chain ID to 1 for Ethereum
      const chainId = "1"

      // Infura NFT API URL
      const baseUrl = "https://nft.api.infura.io"
      const url = `${baseUrl}/networks/${chainId}/accounts/${walletAddress}/assets/nfts`

      // Configure the request
      const config = {
        method: 'get',
        url: url,
        auth: {
          username: API_KEY,
          password: API_SECRET,
        }
      };

      // Issue request to API
      const response = await axios(config);

      // Filter list based on availability of metadata
      let nftList = response['data']['assets'];
      nftList = nftList.filter(x => x['metadata'] !== null)
      nftList = nftList.filter(x => x['metadata']['image'] !== null && x['metadata']['name'] !== null)

      // Set nfts variable to cleaned list
      setNfts(nftList);

    }
  }

  return (
    <div className="App">
      <h1>NFT Viewer</h1>

      {/* Wallet Address Form */}
      <form className='wallet-form' onSubmit={formHandler}>
        <input type='text' value={walletAddress} onChange={walletHandler} required></input>
        <button type='submit'>Submit</button>
      </form>

      {/* NFT Viewer Main Dashboard */}
      <div className='nft-dashboard'>
        {nfts.map(nft => {
          return <div className='nft'>
            <img src={nft['metadata']['image']}
              alt={nft['metadata']['name']}
              key={nft['metadata']['name']}></img>
            <p>{nft['metadata']['name'].slice(0, 35)}</p>
          </div>
        })}
      </div>
    </div >
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

We’re all set! Deploy the app on localhost by running:

$ npm start
Enter fullscreen mode Exit fullscreen mode

We visit http://localhost:3000 in our browser, and this is what we see:

Image description

If you input an address and click submit, you should see the page populate with NFTs. Here is a snapshot of the NFT collection owned by the address we used in Part 1:

Image description

(Note that some images may be broken because they may have been taken off their hosting service.)

Conclusion

Digital collectibles have exploded in popularity over the last several years, and have created amazing business opportunities in the form of escrows, marketplaces, and analytics.

Normally, it would be extremely difficult for NFT creators to extract useful data about digital collectibles and ownership from the blockchain. But with the advent of tools like Infura’s NFT API, working with digital collectibles has never been easier.

Combine it with other tools, such as Truffle (a suite of development tools) and MetaMask (a digital wallet), and you’re well on your way.

We’ve seen how we can build a digital collectibles platform user profile page from scratch in less than 20 lines of code. But we’ve explored only one use of Infura's new API.

There are lots of others to explore — such as creating your own digital collectibles, storing them, optimizing gas fees, and more. Have fun!

Top comments (0)