ethereumblockchainsmartcontractsnft

HTTP API to get the image of an nft based on contract and NFT ID?


I have tried many different ideas, but am unable to find how I can get the image of an NFT with an HTTP request. I tried to find an HTTP API that returns the token URI, but was unable to find anything. Without the token URI I am unable to find the image on ipfs.


Solution

  • If you get the "tokenUri" of the NFT and paste it to the browser

          ipfs://tokenUriHERE
    

    You will see the NFT metadata in a json format like this.

    {
       "name": "name it",
       "image": "ipfs://QmR36VFfo1hH2RAwVs4zVJ5btkopGip5cW7ydY4jUQBrKW",
       "description": "description",
       "attributes": [
            {
              "trait_type": "Artist",
              "value": "value"
            },
    ] }
    

    If you get the image URL and paste it to the browser you will see the image.

    If you want to write a code to fetch data, just send get request to ipfs://tokenUriHERE get the JSON, retrieve the image and then get the image.

    Or you can use libraries. In javascript, web3.storage

    import { Web3Storage } from 'web3.storage'
    
    const token = process.env.API_TOKEN
    const client = new Web3Storage({ token })
    
    async function retrieveFiles () {
      const cid =
        'bafybeidd2gyhagleh47qeg77xqndy2qy3yzn4vkxmk775bg2t5lpuy7pcu'
      // You can fetch data using any CID, even from IPFS Nodes or Gateway URLs!
      const res = await client.get(cid)
      const files = await res.files()
    
      for (const file of files) {
        console.log(`${file.cid}: ${file.name} (${file.size} bytes)`)
      }
    }
    
    retrieveFiles()