This simple application presents a simple demo using a simple form below to allow users to enter the NFT owner's address and select a network to fetch the NFTs owned by the address using the Alchemy API.
Owner's Address
Network
How It Works
Frontend:
- The form allows users to enter the NFT owner's 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 owner 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 handleGetNftsForOwner
Function
The handleGetNftsForOwner
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 handleGetNftsForOwner ( res: NextApiResponse, owner? : string, network? : Network, pageSize: 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}/getNFTsForOwner?owner=${ owner}&withMetadata=true&pageSize=${pageSize}${ 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 owner with JavaScript or NodeJS