DEV Community

Carlo Gino Catapang
Carlo Gino Catapang

Posted on • Originally published at codegino.com

How to fetch NFT collection using JavaScript and OpenSea API

TLDR

Check the code here

Check my list of NFTs here

Introduction

Non-fungible tokens (NFT)

  • A way to represent anything unique as an Ethereum-based asset.
  • NFTs are giving more power to content creators than ever before.
  • Powered by smart contracts on the Ethereum blockchain.

OpenSea is the world's first and largest NFT marketplace. It can be used to discover, collect, and sell extraordinary NFTs.

In this article, I will show how I fetch all my collections using OpenSea's API and then display them on my website.

Prerequisite

For us to be able to use OpenSea's API, we need to request an OpenSea API key here

Create a reusable options object for each API call

This will contain the API key provided by OpenSea

const options = {
  method: 'GET',
  headers: {
    Accept: 'application/json',
    // Do not expose your API key in the browser
    'X-API-KEY': process.env.OPENSEA_API,
  },
};
Enter fullscreen mode Exit fullscreen mode

To avoid exposing your API key, refer to this blog.

(OPTIONAL) Create a variable for the wallet's address

This is the address of our wallet. We can use this address to fetch our collections and assets.

const WALLET_ADDRESS = '0x704CD00cbB8BF91038dFCF8bC008D065DDF1D8F8';
Enter fullscreen mode Exit fullscreen mode

Fetch all collections owned by the specified address

const collectionResponse = await fetch(
  `https://api.opensea.io/api/v1/collections?asset_owner=${WALLET_ADDRESS}`,
  options,
).then(response => response.json());
Enter fullscreen mode Exit fullscreen mode

Map the response to the preferred structure

Here is the type definition of how my website used the response data

type NftCollection = {
  name: string;
  slug: string;
  contractAddress: string;
  details: string;
  owned: {
    id: number;
    img: string;
    name: string;
  }[];
};
Enter fullscreen mode Exit fullscreen mode

Here is how the mapping of the response to the above type definition

const collection = collectionResponse.map((item) => ({
  details: item.description,
  slug: item.slug,
  name: item.name,
  contractAddress: item.primary_asset_contracts[0].address,
  owned: [],
}));
Enter fullscreen mode Exit fullscreen mode

For each collection, fetch all assets owned by the defined address

for (const iterator of collection) {
  const assetsResponse = await fetch(
    `https://api.opensea.io/api/v1/assets?owner=${WALLET_ADDRESS}&asset_contract_address=${iterator.contractAddress}&include_orders=false`,
    options,
  ).then(response => response.json());

  iterator.owned = assetsResponse.assets
    .map((item) => ({
      name: item.name,
      img: item.image_url,
      id: item.token_id,
    }))
    .filter((item: any) => item.name && item.img);
}
Enter fullscreen mode Exit fullscreen mode

Putting it all together

const fetchOwnCollection = async () => {
  const WALLET_ADDRESS = '0x704CD00cbB8BF91038dFCF8bC008D065DDF1D8F8';

  const options = {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'X-API-KEY': process.env.OPENSEA_API as string,
    },
  };

  const collectionResponse = await fetch(
    `https://api.opensea.io/api/v1/collections?asset_owner=${WALLET_ADDRESS}`,
    options,
  ).then(response => response.json());

  const collection = collectionResponse.map(item => ({
    details: item.description,
    slug: item.slug,
    name: item.name,
    contractAddress: item.primary_asset_contracts[0].address,
    owned: [],
  }));

  for (const iterator of collection) {
    const assetsResponse = await fetch(
      `https://api.opensea.io/api/v1/assets?owner=${WALLET_ADDRESS}&asset_contract_address=${iterator.contractAddress}&include_orders=false`,
      options,
    ).then(response => response.json());

    iterator.owned = assetsResponse.assets
      .map(item => ({
        name: item.name,
        img: item.image_url,
        id: item.token_id,
      }))
      .filter(item => item.name && item.img);
  }

  return collection;
};
Enter fullscreen mode Exit fullscreen mode

Rendering the collection

It will depend on the frontend framework of choice. Here is how I did it using NextJs.

NOTE: The overall API requests might be slow when fetched from the browser, make sure to have an appropriate content loader in place. Caching the response might help as well.

Demo

What's next?

Add functionalities for visitors to make offers and buy my NFT collection.

Discussion (0)