DEV Community

Cover image for ๐ŸŽจ Exploring the Alchemy NFT API
Vedant Chainani
Vedant Chainani

Posted on • Edited on

๐ŸŽจ Exploring the Alchemy NFT API

NFTs have revolutionized the idea of art, its access and ownership. By dividing up ownership rights, they have not only removed art from the four walls of galleries but also reduced the price of pricey works of art. The NFT movement is quickly gaining traction among developers and business people as well as producers and collectors, which is why there are more NFT applications available now than ever before. Additionally, there is a steady rise in the number of people wanting to create NFT apps like NFT games, NFT wallets, and NFT markets.

NFTs

Although NFT applications are very popular with consumers, developers, and organisations, creating NFT applications is still challenging since NFT apps require a substantial quantity of data to function properly. To make NFT apps useful for consumers, a lot of data sourcing must be done, from gathering NFT ownership information to retrieving transaction history.

It takes a lot of time and labour to go through each NFT smart contract individually to retrieve data. Different purpose-built NFT APIs can be utilised to address this issue and make the creation of NFT apps faster and easier. These APIs assist in exploring undiscovered prospects in the NFT space by allowing developers to directly access NFT data relating to tokens, metadata, assets, ownership, etc.

This article provides information about the Alchemy NFT API and its expanding importance in the development community. Let's touch on the essentials first, though, before going any farther.

  • What are NFTs?
  • What are APIs?

What are NFTs?

Non-fungible tokens, or NFTs, are digital assets that represent ownership of a wide range of tangible and intangible assets, including videos, images, fine art, real estate, music, and so on. Because each token carries a unique identification code and metadata, and is verified and secured by a blockchain, these unique cryptographic tokens cannot be destroyed or replicated. An NFT certifies the ownership, origin, uniqueness, and permanence of a digital collectible.

NFTs

NFTs differ from traditional digital currencies such as Bitcoin, Ethereum, and Dogecoin in some ways, such as the fact that they both represent digital assets and operate on top of a blockchain network. Furthermore, non-fungible tokens, like fungible tokens, can be transferred from one wallet to another in a quick, secure, and cost-effective manner. Because NFTs are hosted on a blockchain, their ownership is transparent and verifiable.

Unquestionably, one of the most fascinating trends in the blockchain industry is NFT. Everyone is hopping on the NFT bandwagon, from major corporations to famous celebrities and influencers. Since the first NFT "Quantum" was issued in 2014, the NFT market has likewise experienced tremendous expansion. The global NFT market is anticipated to increase by USD 147.24 billion from 2021 to 2026, at a CAGR of 35.27 percent, according to a recent industry report by Technavio.


What are APIs?

Let's first define an API before we study NFT APIs. Application Programming Interface, or API, is the mechanism underlying all computer system connectivity and interactivity. Simply put, an API is the messenger that accepts your requests, instructs a system to perform them, and then provides you the result.

What is an API

You are probably accustomed to the procedure of looking for flights online. You can choose your departure and destination cities, your departure and arrival dates, your chosen cabin class, and other parameters from a menu. In essence, all you do is engage with the website of your preferred airline, access its database, check to see if tickets are available on your preferred dates, and find out what the booking fees might be based on various factors.

What happens, though, if you use an online travel agency instead of the airline's website, which compiles data from other airlines? The information you require won't reach you immediately in that situation. The travel service will initially interface with the airline's API and make a request for data from the airline's system regarding seats, meals, and baggage options. The travel service receives the request from the API, transmits it to the system, receives the airline's response, and then sends it back to you (the user).



Alchemy NFT API

Alchemy NFT API

You may rapidly obtain all the information you require about NFTs from the blockchain using Alchemy's NFT API (i.e. Ethereum, Polygon, Flow). You can now submit a single request to get specified NFT information for both ERC-721 and ERC-1155 tokens rather than manually searching, indexing, and storing data, such as Metadata and properties for each NFT token controlled by an address


Step 1: Create Alchemy Account

We must obtain an API Key from Alchemy in order to use all of the endpoints in the Alchemy NFT API. The simplest method is to register for a free Alchemy account.

It's as simple as entering your information and clicking "Sign Up" (Even Gavin can do it).

When you are signed in and in your dashboard, click the "+ CREATE APP" button to start developing an app to acquire your API Key.

Just give your app a name, then choose a network and chain. We'll be working on the Ethereum Mainnet for this session.

Click โ€œCreate appโ€ and thatโ€™s it! Your app should appear in your apps table.

By clicking on the "View Key" link to the right of the the table row for your app, you will be able to find the API_KEY which you can use to access a Ethereum Mainnet node using Alchemy.

You can see in our example that our API_KEY is:

mlkvPMmH_o7K-dkLNTE4viDwuCyc3B3V
Enter fullscreen mode Exit fullscreen mode

DO NOT SHARE THIS WITH ANYONE! This is how you go to your node. If you distribute it, others will be free to consume the resources of your application, which will make you feel as sad as Gavin.

Copy this down for later, we will use this in our code.


Step 2: Set up your Environment

Coding Environment

Open a terminal and create a new repository for your scripts using the command line. Additionally, we'll set up the repository as a npm project.

mkdir alchemy-nft-api
cd alchemy-nft-api
npm init --yes
Enter fullscreen mode Exit fullscreen mode

To quickly interact with Alchemy APIs, install the alchemy-sdk module. Because you also receive WebSocket support, retries, and other advantages without the complexity, we strongly advise utilizing the Alchemy SDK.

Run the following command to install alchemy-sdk.

npm install alchemy-sdk
Enter fullscreen mode Exit fullscreen mode

Step 3: Initialize SDK instance

SDK

In your alchemy-nft-api directory, you can create a new file called script.js using your favorite file browser, code editor and then paste the following code snippet into the file:

import { Network, Alchemy } from "alchemy-sdk";

const settings = {
  apiKey: "mlkvPMmH_o7K-dkLNTE4viDwuCyc3B3V",
  network: Network.ETH_MAINNET,
};

const alchemy = new Alchemy(settings);
Enter fullscreen mode Exit fullscreen mode

Importing the necessary dependencies for using the Alchemy SDK Library is done in the first line of the code above. next we build a settings object, which has our apikey and the network we want to use to fetch resultsโ€”in this example, Ethereum Mainnetโ€”and finally we create a new instance of Alchemy SDK with settings as the parameters.

In this tutorial we will look at three endpoints namely getNFTs, getNFTMetadata and getNFTsForCollection.


getNFTs

The getNFTs method returns all NFTs currently owned by a given address. It takes one parameter which is the address of the NFT owner, the address can be also in ENS Format (e.g. vitalik.eth)

import { Network, Alchemy } from "alchemy-sdk";

const settings = {
  apiKey: "mlkvPMmH_o7K-dkLNTE4viDwuCyc3B3V",
  network: Network.ETH_MAINNET,
};

const alchemy = new Alchemy(settings);

const owner = "vitalik.eth";

const fetchedNFTs = await alchemy.nft.getNftsForOwner(owner);
console.log(fetchedNFTs.totalCount); // 25219
Enter fullscreen mode Exit fullscreen mode

The fetchedNFTs line returns an object that includes all of the NFTs along with their contact information, tokensId, token type, title, description, balance, and a number of other details. The totalCount key, which we logged in the next line, is located at the end of the object and contains the total number of NFTs possessed by the owner.


getNFTMetadata

The getNFTMetadata line returns the metadata associated with a given NFT. The Contract Address and the Token ID are the two mandatory arguments. We can also provide the token type, such as ERC-20 or ERC-1155.

import { Network, Alchemy } from "alchemy-sdk";

const settings = {
  apiKey: "mlkvPMmH_o7K-dkLNTE4viDwuCyc3B3V",
  network: Network.ETH_MAINNET,
};

const alchemy = new Alchemy(settings);

const metadata = await alchemy.nft
  .getNftMetadata("0x60E4d786628Fea6478F785A6d7e704777c86a7c6", 14810)
  .then(console.log);
Enter fullscreen mode Exit fullscreen mode

This returns an Object containing metadata for the given NFT.

{
  contract: {
    address: '0x60E4d786628Fea6478F785A6d7e704777c86a7c6',
    name: 'MutantApeYachtClub',
    symbol: 'MAYC',
    totalSupply: '19426',
    tokenType: 'ERC721'
  },
  tokenId: '14810',
  tokenType: 'ERC721',
  title: '',
  description: '',
  timeLastUpdated: '2022-10-09T20:30:13.968Z',
  metadataError: undefined,
  rawMetadata: {
    image: 'ipfs://QmfNzqEHVFvMv551ThzEQ26Qurzx4L812LDJnJtmUVgqeK',
    attributes: [ [Object], [Object], [Object], [Object], [Object], [Object] ]
  },
  tokenUri: {
    raw: 'https://boredapeyachtclub.com/api/mutants/14810',
    gateway: 'https://boredapeyachtclub.com/api/mutants/14810'
  },
  media: [
    {
      raw: 'ipfs://QmfNzqEHVFvMv551ThzEQ26Qurzx4L812LDJnJtmUVgqeK',
      gateway: 'https://ipfs.io/ipfs/QmfNzqEHVFvMv551ThzEQ26Qurzx4L812LDJnJtmUVgqeK'
    }
  ],
  spamInfo: undefined
}
Enter fullscreen mode Exit fullscreen mode

getNFTsForCollection

The getNFTsForCollection method returns all NFTs for a given NFT contract. It takes one argument, the address of the NFT contract. For Example:

import { Network, Alchemy } from "alchemy-sdk";

const settings = {
  apiKey: "mlkvPMmH_o7K-dkLNTE4viDwuCyc3B3V",
  network: Network.ETH_MAINNET,
};

const alchemy = new Alchemy(settings);

const opts = {
  pageKey: "4756",
  omitMetadata: true,
  pageSize: 3,
  tokenUriTimeoutInMs: 0,
};
const address = "0x60E4d786628Fea6478F785A6d7e704777c86a7c6";

const nfts = await alchemy.nft.getNftsForContract(address).then(console.log);
Enter fullscreen mode Exit fullscreen mode

Output -

...
{
    contract: [Object],
    tokenId: '22',
    tokenType: 'ERC721',
    title: '',
    description: '',
    timeLastUpdated: '2022-10-10T20:15:40.835Z',
    metadataError: undefined,
    rawMetadata: [Object],
    tokenUri: [Object],
    media: [Array],
    spamInfo: undefined
},
{
    contract: [Object],
    tokenId: '23',
    tokenType: 'ERC721',
    title: '',
    description: '',
    timeLastUpdated: '2022-10-10T20:15:41.206Z',
    metadataError: undefined,
    rawMetadata: [Object],
    tokenUri: [Object],
    media: [Array],
    spamInfo: undefined
},
...
Enter fullscreen mode Exit fullscreen mode

By default it returns an object maximum of 100 NFTs for a given NFT contract, but we can set by using the getNftsForContractIterator method to iterate over NFTs

import { Network, Alchemy } from "alchemy-sdk";

const settings = {
  apiKey: "mlkvPMmH_o7K-dkLNTE4viDwuCyc3B3V",
  network: Network.ETH_MAINNET,
};

const alchemy = new Alchemy(settings);

const opts = {
  pageKey: "4756",
  omitMetadata: true,
  pageSize: 3,
  tokenUriTimeoutInMs: 0,
};
const address = "0x60E4d786628Fea6478F785A6d7e704777c86a7c6";

for await (const nft of alchemy.nft.getNftsForContractIterator(address, opts)) {
  console.log(nft);
}
Enter fullscreen mode Exit fullscreen mode

Output -

...
{
  contract: { address: '0x60E4d786628Fea6478F785A6d7e704777c86a7c6' },
  tokenId: '5553',
  tokenType: 'UNKNOWN'
}
{
  contract: { address: '0x60E4d786628Fea6478F785A6d7e704777c86a7c6' },
  tokenId: '5554',
  tokenType: 'UNKNOWN'
}
{
  contract: { address: '0x60E4d786628Fea6478F785A6d7e704777c86a7c6' },
  tokenId: '5555',
  tokenType: 'UNKNOWN'
}
...
``
Enter fullscreen mode Exit fullscreen mode

Here is a list of all the endpoints for Alchemy NFT API

Endpoint What it is used for
getNfts Retrieve the NFTs owned by a wallet address
getContractsForOwner Retrieve the list of NFT contracts from which a wallet address owns one or more tokens.
getOwnersForToken Retrieve the owners of a given token
getOwnersForCollection Retrieve all the owners for a given NFT contract or collection, including snapshotting owners at any block numb
isHolderOfCollection Check whether a given wallet owns any NFT in a given token
getNFTMetadata Retrieve the metadata associated with a given contract or collection
getContractMetadata Retrieve the metadata associated with a given contract or colleciion
searchContractMetadata Search the metadata across contracts for specific keywords
reingestContract Triggers metadata refresh for a NFT collection/refreshes stale metadata after a reveal
getNFTsForCollection Retrieve all the NFTs for a given contract or collection
getSpamContracts Retrieve a list of contracts marked as spam
isSpamContract Returns whether a specific contract is marked as spam or not
getFloorPrice Retrieve the floor price of a NFT collection by marketplace
getNFTSales Retrieve NFT sales data across marketplaces
computeRarity Compute the rarity of each attribute of an NFT.
summarizeNFTAttributes Generate a summary of attribute prevalence for an NFT collection.


Top comments (1)

Collapse
 
johner97 profile image
Johner97

NFT is a very interesting technology. You can earn very well. However, it is worth knowing how to store cryptocurrencies. If you are new to nft, I highly recommend this post: nftmonk.com/discover-how-to-create...