Using Infura’s NFT API With Lootbox
Tags: web3, blockchain, nft, ethereum
Published: 2022-07-07 20:59:10

## Introduction

I’ve only been in Web3 for about a year now, but I can honestly say that NFTs are the most exciting aspect about it for me. I’m not talking about Apes or Punks, however. PFP (profile picture) projects and art, although cool and a simple proof of concept for the technology, won’t create a better world. 

Instead, I’m excited about the actual utility of NFTs. Allowing gamers to own their assets, delivering fair royalty commissions to musicians and artists, and making concert tickets impossible to scalp while providing a sweet digital memento are some of the use cases I find interesting.

However, building and interacting with NFTs aren’t always the easiest thing to do. As developers, we need clear resources to build projects effectively in order to give our users a better experience. 

I recently heard about [Infura’s private beta for their NFT API](https://infura.io/resources/apis/nft-api-beta-signup), so I thought I would check it out and see how it could improve my development workflow. In this article, I will explore the capabilities of Infura’s NFT API and test it out using a Lootbox NFT sample project from Infura’s Github.


## What is the Infura NFT API?

According to [this blog post](https://blog.infura.io/post/introducing-the-infura-nft-api-beta-release) on Infura’s website, the NFT API will help me “accelerate my time to value” and allow me to interact with anything related to NFTs through a convenient SDK. In addition, I can build and verify my NFTs, create metadata templates and easily mint NFTs. So my first impression is that I can start creating and interacting with NFTs using API endpoints rather than building smart contracts and deploying them.

Sounds pretty useful! And I’m all for testing any tool that will help improve my development processes. Infura’s NFT API suite seems helpful for any dev transitioning from Web2, since you can run API endpoints without Solidity.  

Now let’s dive deeper and see what this NFT API is capable of.


## Infura NFT API Capabilities

A quick glance through the [NFT API documentation](https://docs.infura.io/infura/features/nft-sdk) on Infura’s website proves my first impression correct. I will be able to deploy and call methods on my NFT contracts using Infura’s API endpoints, without having to actually write the smart contract code. This is a huge time saver! 

[Deploying a contract](https://docs.infura.io/infura/features/nft-sdk/how-to/deploy-a-contract) is straightforward. I create the NFT metadata in JSON format, [upload the metadata to IPFS](https://docs.infura.io/infura/networks/ipfs/how-to/make-requests) in another Infura project, then create a simple deployment script and run it with node. I also have to make a `.env` file to hold some environment variables. My deployment script ends up looking something like this:

```JavaScript
import { config as loadEnv } from 'dotenv';
import { SDK, Auth, TEMPLATES } from '@infura/sdk';

loadEnv();

const auth = new Auth({
      projectId: process.env.INFURA_PROJECT_ID,
      secretId: process.env.INFURA_PROJECT_SECRET,
      privateKey: process.env.WALLET_PRIVATE_KEY,
      chainId: 4,
    });

const sdk = new SDK(auth);

const myNFTContract = await sdk.deploy({
   template: TEMPLATES.ERC721Mintable,
   params: {
     name: 'My NFT Contract',
     symbol: 'MYNFT',
     contractURI: 'https://MY_NFT_METADATA_URL',
   },
 });
console.log(`Contract address is: ${myNFTContract.contractAddress}`);
```

Then, I run it with Node. Infura creates a smart contract for me and uploads it to Ethereum behind the scenes. After that, I just need to make sure I have some tokens for whichever `chainId` I have specified in my code. In this case, the Rinkeby testnet (chainId: 4). From here, I could [mint NFTs](https://docs.infura.io/infura/features/nft-sdk/how-to/mint-an-nft) from this contract or gather the contract metadata. 

This is a much easier method to create an NFT contract than writing Solidity code and deploying it myself!

The NFT API also provides methods for [gathering NFT info](https://docs.infura.io/infura/features/nft-sdk/how-to/get-nft-information) from wallets, [transferring NFTs](https://docs.infura.io/infura/features/nft-sdk/how-to/transfer-an-nft) from one wallet to another, and a host of other [NFT methods](https://docs.infura.io/infura/features/nft-sdk/apis/javascript-api/templates/erc721mintable-methods). These include [adding an address to the minter list](https://docs.infura.io/infura/features/nft-sdk/apis/javascript-api/templates/erc721mintable-methods/addminter), [setting royalty info](https://docs.infura.io/infura/features/nft-sdk/apis/javascript-api/templates/erc721mintable-methods/setroyalties), and [changing the contract URI](https://docs.infura.io/infura/features/nft-sdk/apis/javascript-api/templates/erc721mintable-methods/setcontracturi). 

Overall, it seems that Infura’s NFT API indeed helps improve my development workflow. Having all the necessary functionality for building and interacting with NFTs packaged together in an easy-to-use SDK is quite convenient!

But enough about what it can do, let’s see how this API works!


## The Lootbox Project

Along with the NFT API, Infura released an [NFT Gallery Project on their Github](https://github.com/INFURA/nft-api-lootbox-gallery-app) to demo its capabilities. All I will have to do is input an Infura project ID and secret, then connect my MetaMask wallet to the dapp frontend. Then the dapp uses the API to fetch all my NFTs to display nicely in the frontend. So to break that down, I will need the following things for this project:


* An [Infura account](https://infura.io/)
* Infura Project ID and Secret
* A [MetaMask wallet extension](https://metamask.io/) with NFTs in it 

Let’s get started!


### Step 1 - The Infura Project ID and Secret

Before starting the Lootbox project, I want to gather the necessary items. So first, I’ll head to [infura.io](https://infura.io/), log in, and create a new project. Then, I can grab the **Project ID** and **Project Secret** for use later.


![A new project dialogue box on Infura](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpitdczalk2hzfo9g4qa.png)

![The project ID and project secrets, highlighted in red, showing the reader where to copy from](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cnjbs888t2jyc2oni5ak.png)

### Step 2 - MetaMask

This step will be quick because I already have the extension installed in my browser. If someone following along with this article doesn’t, however, head to [metamask.io](https://metamask.io/) and [download](https://metamask.io/download/) the extension for your specific browser. Then follow the steps to create a new account.

Next, I’ll sign in and switch accounts to the wallet address that holds my NFTs. If you need to acquire an NFT, you can head to [your favorite marketplace](https://looksrare.org/) and buy one or try to create one yourself using the Infura NFT API 😉. Either way, you will need some ETH in your wallet.


### Step 3 - Setting Up The Project

With all the prep work out of the way, I can start building the project. So next, I’ll clone the project repo onto my local machine. I’ll first navigate to the folder I want to work out of and then type the following command:


```Bash
git clone https://github.com/INFURA/nft-api-lootbox-gallery-app.git
```


Next, I will change directories into the project folder and install dependencies using [yarn](https://classic.yarnpkg.com/lang/en/docs/install/#windows-stable):


```Bash
cd nft-api-lootbox-gallery-app
yarn
```


After everything is installed, the last thing I need to do is create a `.env` file to store my environment variables and secrets. I’ll just copy the file that’s already there and add my variables to it.


```Bash
cp .env .env.local 
```


Now I’ll open up the project and add my **Project ID** and **Project Secret** from my recently created Infura project. There’s also an option to input the Account Address of any wallet to view their NFTs, but I’ve got my own I want to see in the Lootbox NFT Gallery.

With all the setup out of the way, I can finally run the Lootbox project. But first, I want to browse through the code to see what’s happening under the hood.


### Step 4 - The Lootbox Code

Based on the [README file](https://github.com/INFURA/nft-api-lootbox-gallery-app#readme) of the Lootbox project, the most important components are in the `pages/index.tsx`, `hooks/useWallet.ts`, and `pages/api/assets.ts` files. So I’m going to browse those and see if I can figure out how this project uses the Infura NFT API.

After looking through these files, I can see the `pages/index.tsx` file contains the code which displays the frontend for the project. If the `showGallery` state variable is true, then it should display my NFTs. If it’s false, then it should display the welcome text with the **Connect Wallet** button. This Connect Wallet button connects to some functions in the `hooks/useWallet.ts` file, so I’ll check there next.

In the `hooks/useWallet.ts` file, I can see the function which is supposed to grab my NFTs. Specifically, the `getTokens` function.


```JavaScript
 const getTokens = async (accountAddress: string) => {
    try {
      const { data } = await axios.post('/api/assets', { accountAddress });
      return data.assets;
    } catch (error) {
      setTimeout(() => {
        setErrorMessage('Error getting tokens');
      }, 2000);
      return;
    }
  };
```


This function seems to make a POST request using a parameter from the `/api/assets` file and return the results with my assets. So looking into the `pages/api/assets.ts` file, I can see where the NFT API is being used. 


```JavaScript
  try {
    const { data } = await axios.get(  `https://nft.api.infura.io/networks/1/accounts/${accountAddress}/assets/nfts`,
      {
        headers: {},
        auth: {
          username: `${process.env.INFURA_PROJECT_ID}`,
          password: `${process.env.INFURA_PROJECT_SECRET}`
        }
      }
    );

    return res.status(200).json({
      assets: data.assets,
    });
```


This code calls the [get function of the NFT API](https://docs.infura.io/infura/features/nft-sdk/apis/javascript-api/sdk/getnfts), using my `Infura Project ID` and `Project Secret` to access my account, and returns my NFTs in a JSON object. Following the path back to the `pages/index.tsx` file, if the `getTokens` function from `hooks/useWallet.ts` doesn’t timeout, it will return my NFTs, switch the `setGallery` state variable to `true`, and display my NFTs on the page.

Cool! So I’ve got an idea of how it works, let’s see it in action!


### Step 5 - Running The Lootbox Project

To run the project locally, I just need to type:


```Bash
yarn dev
```


After navigating to [http://localhost:3000/](http://localhost:3000/), I can see a nice-looking frontend for the Lootbox Project.


![The Lootbox project main page displays the title "Creat an NFT Gallery" and there is a button to connect your web3 wallet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7b1nh8cfbhesd72t1ork.png)

Clicking on **Connect Wallet** prompts my MetaMask wallet to pop up to approve the connection request.


![MetaMask pops up, prompting me to connect my wallet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/em3or1gk7s7ggkdphhfy.png)

After connecting, it immediately starts fetching my tokens. This is the point where I now know the dapp is using the NFT API.


![It says: "Fetching Tokens" and has a loading symbol next to it](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rt5bkflmjdnvq4nr3dlc.png)

Once the fetch is successful, it displays my NFTs in a fancy gallery, allowing me to browse and choose each one to get a better look at them. Neat!


![My NFTs displayed successfully](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ayvwgl5rnn34zb9zykba.png)

## Conclusion

My verdict on the Infura NFT API is that it's a tool that cuts down my development time, and there’s quite a bit I can do with it. It’s handy to build, mint, and interact with NFTs from an easy-to-use API. Although I am more familiar with building NFT contracts with Solidity and deploying them with Truffle, I can easily see how this would help smooth the transition of a Web2 dev into Web3. Using JavaScript rather than writing a smart contract will be a huge time saver for many Web2 developers.

I would suggest trying the NFT API out for yourself. It’s still in private beta, but anyone can [register](https://infura.io/resources/apis/nft-api-beta-signup). For more information on its capabilities, you can check out [this YouTube demo](https://www.youtube.com/watch?v=ERV_FbCDBIQ) or [Infura’s documentation](https://docs.infura.io/infura/features/nft-sdk).