How to build a Dashboard to return all NFT tokens a user holds using NFTPort.
In this guide, developers will take a sequence of steps to build a dashboard that returns all the tokens owned by a user, using the NFTPort endpoint: “Retrieve NFTs owned by an account.”
What are NFTs?
I make a personal recommendation to developers to always read the ethereum improvement proposals on the website: eips.ethereum.org, there you will find that prior to settling on the name choice of “NFTs”, one of the first name choices was the word “Deeds”. In legal terms “A deed is a legal document that grants ownership to a piece of real estate or other property asset.” An understanding of NFTs as deeds opens up the developer to a plethora of use cases that can be builT using NFTs. Popular today is ownership of tokenized art. A user can own many NFTs deployed across multiple chains and deployed by various contracts. To demonstrate or check ownership of such assets by a user, one has to go to various blockchain explorers and input the user address to return all the NFTs owned by the user of that particular chain. This is a problem that NFTPort has solved using her APIs.
What is NFTPort?
NFTPort grants users ONE API Key to unlock access to NFTs across multiple chains. NFTPort prides itself on its ability to “Bring your NFT application to market in hours instead of months.” In this guide, we will rely on one of the API endpoints available in NFTPort and build a user dashboard where you can parse any ethereum address and return all the NFTs owned by that address. We will build the entire DApp using one API in the suite of APIs from NFTPort.
Sample DApp
We will build a simple app using HTML and JS. The app will call the API: Retrieve NFTs owned by an account
This endpoint Returns NFTs owned by a given account (i.e. wallet) address. It is useful for: For checking if a user owns a specific NFT and then unlocking specific activity. Adding NFT portfolio section to your apps.
The next step will walk you through building a simple dapp.
HTML
Using any code editor of your choice, kindly create a folder and create the following files index.html
and index.js
. In the index.html
file, paste the following code.
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script type="module" src="index.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1>Sample DApp</h1>
<form id="setData">
<div class="form-group">
<label for="setDataInput">Enter Address into the Input:</label>
<input id="setDataInput" type="text" class="form-control"></input>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div>Total NFTs held: <span id="totalNFTs"></span></div>
</div>
</div>
</div>
</body>
</html>
If you are using vscode as your primary editor, use the liveserver extension to launch the app, you will see the following screen:
This is a landing page where a user can input any ethereum address and return all the NFTs held by that address. The next step is to write javascript code that will return the data to the user. Follow the sequence of steps to gain a firm understanding of the process.
JavaScript
Go to the NFTPort website and sign up to get a free API Key.
Open your
index.js
file and enter the code:const options = { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: 'your-api-key' } }; fetch('https://api.nftport.xyz/v0/accounts/address?chain=ethereum', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err));
This is a GET request where a call is made to the Retrieve NFTs owned by an account endpoint. The endpoint url is
https://api.nftport.xyz/v0/accounts/address?chain=ethereum
whereaddress
can be any ethereum externally owned address, and the chain we are exploring is ethereum. The Fetch API is used to query the endpoint and the response is formatted to json before it is logged to the console in this step.Copy any ethereum address from etherscan and enter it into the address, the url will look like this
https://api.nftport.xyz/v0/accounts/0x….?chain=ethereum
Open the browser page where the index file is running, and open the console. You will see an
object
response. Click on the object to see all the data return by the endpoint.You can also click on the
nfts
dropdown where you will see all the json values returned:contract_address
,token_id
andcontract_name
To return more data, there is the
include
query where you can add the option to return nftmetadata
to the url path.https://api.nftport.xyz/v0/accounts/address?chain=ethereum&include=metadata
This returns more information about the token.
We have successfully confirmed that we can connect to the API using our API KEY, query an endpoint and return data to the app using the fetch api. The next step is to write a function that will take any address parsed as an argument and when a user clicks
submit
return the response. Add the following code toindex.js
… const $setData = document.getElementById("setData"); $setData.addEventListener("submit", (e) => { e.preventDefault(); const data = e.target.elements[0].value; console.log(data); });
The is a DOM manipulation script where the user targets the form by its id
setData
. An event listener is added with an action triggered bysubmit
, where an async function is run and whatever is parsed into the input is logged to the console. Go ahead and test it out by typing anything into the input field.The next step is to ensure that we can parse an ethereum address into the input and it will be resolved as part of the api url query. This will be done in a try catch block inside the event listener. In this step, we will refactor the code we have already written, and add the URL object query method to create a url path that can be resolved using the fetch api. Make the function inside the event listener an async function. Delete or comment out the fetch method already in the code, and add the following lines inside the event listener function.
const url = new URL( `https://api.nftport.xyz/v0/accounts/${data}?chain=ethereum&include=metadata` ); try { const response = await fetch(url, options); const results = await response.json(); console.log(results); } catch (error) { console.log(error); }
Copy any ethereum address and enter it into the input, click ‘submit’, the response will be logged to the console! From the point, you can build any UI to return the data to users via the interface.
In this sample dapp, we will return the data via a simple table that will list the following:
- Contract Address
- Token Name
- Token ID
- Image URL
- Contract Creator Address
- Total Number of NFTs held by the address
To return the total number of nfts held by the address, we will target the
<span>
tag on the frontend, this has an idtotalNFTs
, target thetotalNFTs
id from the DOM using:let $totalNFTs = document.getElementById("totalNFTs");
add the following code to the try block:
$totalNFTs.innerHTML = results.total;
You will see the total number of NFTs returned to the UI.
The final step is to return the remaining data to the UI using the table.
Add the following line into the
index.html
file under the Total NFTs div<table id="tokenTable" class="table table-striped"></table>
This is a
<table>
div from getBootstrap that creates a pleasant looking table, we have assigned it an idtokenTable
.Target the DOM using the
tokenTable
idlet tableRef = document.getElementById("tokenTable"); tableRef.innerHTML = `<thead class="thead-dark"> <tr> <th>Contract Address</th> <th>Token Name</th> <th>Token ID</th> <th>Image URL</th> <th>Creator Address</th> </tr> </thead> <tbody> </tbody>`;
Update the try block:
const nfts = results.nfts;
nfts.map((result) => {
tableRef.insertRow().innerHTML =
`<td> <a href="https://etherscan.io/address/${result.contract_address}"
target="_blank">${result.contract_address}</a></td>` +
`<td> ${result.name} </td>` +
`<td> ${result.token_id} </td>` +
`<td> <a href="${result.metadata.image}" target="_blank">image</a></td>` +
`<td> <a href="https://etherscan.io/address/${result.creator_address}"
target="_blank">${result.creator_address}</a></td>`;
});
Enter an ethereum address and click submit!
Conclusion
Here is the complete code for your reference. In this guide, we explored the “Retrieve NFTs owned by an account” API endpoint. We explored its relevance in building NFT applications. We build a simple application to establish a primary understanding of the endpoint. In conclusion, this guide represents a frame of reference that a developer can start with and build any form of use case using the single API endpoint.
View a video demo and code walkthrough of the app here