This simple application presents a simple demo using a simple form below to allow users to enter the NFT contract address and select a network to fetch the NFTs using the Alchemy API.
Contract Address
Network
How It Works
Frontend:
- The form allows users to enter the NFT contract address and select a network.
- When the "Fetch NFTs" button is clicked, it triggers the
fetchNfts
function. - This function sends a request to the backend API to fetch the NFTs.
Backend:
- The backend API handles the request to fetch the NFTs belonging to the specified contract using the Alchemy SDK.
- It processes the request, retrieves the NFTs, and sends the response back to the frontend.
The Code at the Backend
The handleGetNftsForContract
Function
The handleGetNftsForContract
function is an asynchronous function used in the backend to fetch the NFTs of a specified owner's wallet address using the Alchemy API.
async function handleGetNftsForContract ( res: NextApiResponse, contractAddress? : string, network? : Network, withMetaData : boolean = true, limit: number = 3, pageKey? : string ){ try { const net = network ?? Network.ETH_MAINNET; const options = {method: 'GET', headers: {accept: 'application/json'}}; const url =`https://${net}.g.alchemy.com/nft/v3/${process.env.ALCHEMY_API_KEY}/getNFTsForContract?contractAddress=${ contractAddress}&withMetadata=${withMetaData ? 'true' : 'false'}&limit=${limit}${ pageKey ? `&pageKey=${pageKey}` : ""}`; let result = await fetch(url, options); res.status(200).json({data: await result.json()}); } catch(e: any){ res.status(500).send({error: e.message, status: -1}); } }
Refer here for how to use the Alchemy NFT API to fetch NFTs for a given contract with JavaScript or NodeJS