How to Get All NFTs in a Collection
Learn how to get all NFTs that belong to a particular collection using the Alchemy NFT API
If you're building an NFT marketplace such as OpenSea, an NFT analytics platform like rarity.tools, or a website for your PFP project, you will likely want to display all the NFTs in a collection you are interested in.
The Bored Ape Yacht Club collection on OpenSea
Typically, you might achieve this by calling functions on the contract directly and parsing the data that you're interested in. This approach requires an understanding of ERC-721 or ERC-1155 standards and involves making multiple individual requests for each NFT in the collection.
Using Alchemy's NFT API, however, you can retrieve all of the data for an entire NFT collection with a single call. This tutorial will guide you in creating a script that retrieves all metadata of an NFT collection.

Our Example

In our example, we will write a script in Node that retrieves all metadata for each NFT in the Bored Ape Yacht Club (BAYC) collection on the Ethereum network. We will achieve this by using Alchemy and the NFT API.

Creating the NFT Collections Script

Prerequisites

Before you begin the steps in this tutorial, ensure you complete the following steps:
  • Install both Node.js (> 14) and npm on your local machine. To check your Node version, run the following command in your terminal:
1
node -v
Copied!

Step 1: Create an Alchemy app

To create an Alchemy app:
  1. 1.
    From Alchemy's dashboard, hover over the Apps drop-down menu and choose Create App.
  2. 2.
    Provide a Name and Description for your app. For Chain, select Ethereum and for Network select Mainnet.
  3. 3.
    Click the Create App button.
Creating an app on the Alchemy Dashboard
Once you have created your app, click on your app's View Key button in the dashboard and save the API KEY. We will use this later.

Step 2: Create a Node project

Now, let's create an empty repository and install all node dependencies. To make requests to the NFT API, we recommend using the Alchemy SDK. However, you can also use axios or fetch libraries. Run the following commands in your terminal:
Alchemy SDK (Recommended)
Axios
Fetch
1
mkdir nft-collection && cd nft-collection
2
npm init -y
3
npm install --save @alch/alchemy-sdk
4
touch main.js
Copied!
1
mkdir nft-collection && cd nft-collection
2
npm init -y
3
npm install --save axios
4
touch main.js
Copied!
1
mkdir nft-collection && cd nft-collection
2
npm init -y
3
touch main.js
Copied!
This above commands create a repository named nft-collection that holds all the files and dependencies we need. Open this repository in your favorite text editor (e.g., VS Code). We will write the remainder of our code in the main.js file.

Step 3: Get all NFTs that belong to a collection

To retrieve all of the NFTs that belong to a collection, we will use the getNFTsForCollection method. This method accepts one required argument and two optional arguments.
  • contractAddress: The address of the NFT contract we're interested in. This is a required argument.
  • withMetadata: A boolean that indicates whether the method should return NFT metadata. By default, this is set to False, and we only retrieve token IDs. For our purposes, we will set this to True.
  • startToken: An offset that is used for pagination. The method only returns 100 NFTs at a time. Using this argument, we can specify which 100 we are interested in.
As noted, the method does not return NFT metadata by default. In our example, however, we will override this default behavior by setting withMetadata to True. For more information about NFT metadata, check out the NFT API FAQ.
Add the following code to the main.js file, using your Alchemy API key:
Alchemy SDK (Recommended)
Axios
Fetch
1
const { initializeAlchemy, getNftsForCollection } = require('@alch/alchemy-sdk');
2
​
3
// Alchemy app API key
4
const settings = {
5
apiKey: '<-- ALCHEMY APP API KEY -->',
6
};
7
​
8
const alchemy = initializeAlchemy(settings);
9
​
10
const main = async () => {
11
​
12
// Contract address
13
const address = '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D'
14
​
15
// Metadata inclusion flag
16
const withMetadata = 'true';
17
​
18
// Get all NFTs
19
const response = await getNftsForCollection(alchemy, address, { withMetadata: withMetadata })
20
console.log(JSON.stringify(response, null, 2))
21
}
22
​
23
const runMain = async () => {
24
try {
25
await main();
26
process.exit(0);
27
}
28
catch (error) {
29
console.log(error);
30
process.exit(1);
31
}
32
};
33
​
34
runMain();
Copied!
1
const axios = require('axios')
2
​
3
// Contract address
4
const address = '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D'
5
​
6
// Metadata inclusion flag
7
const withMetadata = 'true';
8
​
9
// Alchemy API key
10
const apiKey = '<-- YOUR ALCHEMY APP API KEY -->';
11
​
12
// Alchemy URL
13
const baseURL = `https://eth-mainnet.alchemyapi.io/nft/v2/${apiKey}/getNFTsForCollection`;
14
const url = `${baseURL}?contractAddress=${address}&withMetadata=${withMetadata}`;
15
​
16
const config = {
17
method: 'get',
18
url: url,
19
};
20
​
21
// Make the request and print the formatted response:
22
axios(config)
23
.then(response => console.log(JSON.stringify(response['data'], null, 2)))
24
.catch(error => console.log(error));
Copied!
1
import fetch from 'node-fetch';
2
​
3
// Contract address
4
const address = '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D'
5
​
6
// Metadata inclusion flag
7
const withMetadata = 'true';
8
​
9
// Alchemy API key
10
const apiKey = '<-- ALCHEMY APP API KEY -->';
11
​
12
// Alchemy URL
13
const baseURL = `https://eth-mainnet.alchemyapi.io/nft/v2/${apiKey}/getNFTsForCollection`;
14
const url = `${baseURL}?contractAddress=${address}&withMetadata=${withMetadata}`;
15
​
16
var requestOptions = {
17
method: 'get',
18
redirect: 'follow'
19
};
20
​
21
fetch(url, requestOptions)
22
.then(response => response.json())
23
.then(response => JSON.stringify(response, null, 2))
24
.then(result => console.log(result))
25
.catch(error => console.log('error', error));
Copied!
Run this script by running the following command in your terminal:
1
node main.js
Copied!
If successful, you should see output that looks something like this:
1
{
2
"nfts":
3
[
4
...
5
{
6
"contract": {
7
"address": "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d"
8
},
9
"id": {
10
"tokenId": "0x00000000000000000000000000000000000000000000000000000000000000c7",
11
"tokenMetadata": {
12
"tokenType": "ERC721"
13
}
14
},
15
"title": "",
16
"description": "",
17
"tokenUri": {
18
"raw": "ipfs://QmeSjSinHpPnmXmspMjwiXyN6zS4E9zccariGR3jxcaWtq/199",
19
"gateway": "https://ipfs.io/ipfs/QmeSjSinHpPnmXmspMjwiXyN6zS4E9zccariGR3jxcaWtq/199"
20
},
21
"media": [
22
{
23
"raw": "ipfs://QmUiCqmHZd5CxeGsamizmS2Y8eSuMkNgVN44RzLcFVctyw",
24
"gateway": "https://res.cloudinary.com/alchemyapi/image/upload/mainnet/e8009d708d27f11c38fed183c70f2f48.png",
25
"thumbnail": "https://res.cloudinary.com/alchemyapi/image/upload/w_256,h_256/mainnet/e8009d708d27f11c38fed183c70f2f48.png"
26
}
27
],
28
"metadata": {
29
"image": "ipfs://QmUiCqmHZd5CxeGsamizmS2Y8eSuMkNgVN44RzLcFVctyw",
30
"attributes": [
31
{
32
"value": "Army Green",
33
"trait_type": "Background"
34
},
35
{
36
"value": "Striped Tee",
37
"trait_type": "Clothes"
38
},
39
{
40
"value": "Zombie",
41
"trait_type": "Eyes"
42
},
43
{
44
"value": "Brown",
45
"trait_type": "Fur"
46
},
47
{
48
"value": "Grin",
49
"trait_type": "Mouth"
50
},
51
{
52
"value": "Girl's Hair Short",
53
"trait_type": "Hat"
54
}
55
]
56
},
57
"timeLastUpdated": "2022-05-26T14:52:39.110Z"
58
}
59
],
60
"nextToken": "0x00000000000000000000000000000000000000000000000000000000000000c8"
61
}
Copied!
Note: The API will only return data for the first 100 NFTs. For collections that contain more than 100 NFTs, use the startToken argument for the getNFTsForCollection method and set it to NFT number you wish to retrieve.
For instance, if you want data on NFTs 101-200, set startToken to 101. For 201-300, set it to 201. Continue this process until you reach the end of the collection.
For more information, check out the NFT API docs.

Step 4: Parse the NFT API Output

As a final step, parse the API output to show the image URL of every NFT. In the case of BAYC, this is an IPFS (InterPlanetary File System) URL.
Replace the contents of main.js with the following code:
Alchemy SDK (Recommended)
Axios
Fetch
1
const { initializeAlchemy, getNftsForCollection } = require('@alch/alchemy-sdk');
2
​
3
// Alchemy app API key
4
const settings = {
5
apiKey: '<-- ALCHEMY APP API KEY -->',
6
};
7
​
8
const alchemy = initializeAlchemy(settings);
9
​
10
const main = async () => {
11
​
12
// Contract address
13
const address = '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D'
14
​
15
// Metadata inclusion flag
16
const withMetadata = 'true';
17
​
18
// Get all NFTs
19
const response = await getNftsForCollection(alchemy, address, { withMetadata: withMetadata })
20
const nfts = response['nfts']
21
​
22
console.log("NFT Metadata")
23
​
24
let i = 1
25
​
26
for (let nft of nfts) {
27
console.log(`${i}. ${nft['rawMetadata']['image']}`)
28
i++;
29
}
30
​
31
}
32
​
33
const runMain = async () => {
34
try {
35
await main();
36
process.exit(0);
37
}
38
catch (error) {
39
console.log(error);
40
process.exit(1);
41
}
42
};
43
​
44
runMain();
Copied!
1
const axios = require('axios')
2
​
3
// Contract address
4
const address = '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D'
5
​
6
// Metadata inclusion flag
7
const withMetadata = 'true';
8
​
9
// Alchemy API key
10
const apiKey = '<-- YOUR ALCHEMY APP API KEY -->';
11
​
12
// Alchemy URL
13
const baseURL = `https://eth-mainnet.alchemyapi.io/nft/v2/${apiKey}/getNFTsForCollection`;
14
const url = `${baseURL}?contractAddress=${address}&withMetadata=${withMetadata}`;
15
​
16
const config = {
17
method: 'get',
18
url: url,
19
};
20
​
21
// Make the request and print the formatted response:
22
axios(config)
23
.then(response => {
24
const nfts = response['data']['nfts']
25
​
26
console.log("NFT Metadata")
27
let i = 1
28
for (let nft of nfts) {
29
console.log(`${i}. ${nft['metadata']['image']}`)
30
i++;
31
}
32
})
33
.catch(error => console.log('error', error));
Copied!
1
import fetch from 'node-fetch';
2
​
3
// Contract address
4
const address = '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D'
5
​
6
// Metadata inclusion flag
7
const withMetadata = 'true';
8
​
9
// Alchemy API key
10
const apiKey = '<-- ALCHEMY APP API KEY -->';
11
​
12
// Alchemy URL
13
const baseURL = `https://eth-mainnet.alchemyapi.io/nft/v2/${apiKey}/getNFTsForCollection`;
14
const url = `${baseURL}?contractAddress=${address}&withMetadata=${withMetadata}`;
15
​
16
var requestOptions = {
17
method: 'get',
18
redirect: 'follow'
19
};
20
​
21
fetch(url, requestOptions)
22
.then(response => {
23
24
const nfts = response['data']['nfts']
25
​
26
console.log("NFT Metadata")
27
let i = 1
28
for (let nft of nfts) {
29
console.log(`${i}. ${nft['metadata']['image']}`)
30
i++;
31
}
32
})
33
.catch(error => console.log('error', error))
Copied!
Run the script by calling the following command in your terminal:
1
node main.js
Copied!
You should obtain output that looks like this:
1
NFT Metadata
2
1. ipfs://QmRRPWG96cmgTn2qSzjwr2qvfNEuhunv6FNeMFGa9bx6mQ
3
2. ipfs://QmPbxeGcXhYQQNgsC6a36dDyYUcHgMLnGKnF8pVFmGsvqi
4
3. ipfs://QmcJYkCKK7QPmYWjp4FD2e3Lv5WCGFuHNUByvGKBaytif4
5
4. ipfs://QmYxT4LnK8sqLupjbS6eRvu1si7Ly2wFQAqFebxhWntcf6
6
5. ipfs://QmSg9bPzW9anFYc3wWU5KnvymwkxQTpmqcRSfYj7UmiBa7
7
6. ipfs://QmNwbd7ctEhGpVkP8nZvBBQfiNeFKRdxftJAxxEdkUKLcQ
8
7. ipfs://QmWBgfBhyVmHNhBfEQ7p1P4Mpn7pm5b8KgSab2caELnTuV
9
8. ipfs://QmRsJLrg27GQ1ZWyrXZFuJFdU5bapfzsyBfm3CAX1V1bw6
10
9. ipfs://QmXEqPbvM4aq1SQSXN8DSuEcSo5SseYW1izYQbsGB8yn9x
11
10. ipfs://QmUQgKka8EW7exiUHnMwZ4UoXA11wV7NFjHAogVAbasSYy
12
11. ipfs://QmPQdVU1riwzijhCs1Lk6CHmDo4LpmwPPLuDauY3i8gSzL
13
12. ipfs://QmVvdAbabZ2awja88uUhYHFuq67iEiroFuwLGM6HyiWcc8
14
13. ipfs://QmexFWUtmFNGQwVuRN8dLLwcucSFoLYjeHkv2uAyan5H8t
15
14. ipfs://QmaZLhanFj41yfXY3Ux1JNv6ZAnzsWXfbJmo7qbJzZjh4s
16
15. ipfs://QmbcWzteFsAvdwiaZyC1YJVNsApDaPRmqkQDyrYAvP4u48
Copied!
Congratulations! You now know how to use the Alchemy NFT API to retrieve all NFTs in a collection or at an address. You can adapt this for any network (e.g., Ethereum, Polygon, etc.).
If you enjoyed this tutorial about how to get all NFTs owned by an address, tweet us at @AlchemyPlatform and give the authors @rounak_banik and @ankg404 a shoutout!
Don't forget to join our Discord server to meet other blockchain devs, builders, and entrepreneurs!
Ready to start using the Alchemy NFT API?
​Create a free Alchemy account and do share your project with us!