Token API Quickstart

A new developer's guide to using the Token API and mastering how to get token information. Learn how to query Token data using alchemy-web3 (recommended), fetch, or axios.

With the Token API, you can easily request information on specific tokens such as metadata or balances. Alchemy currently supports the following Token API Endpoints:

  • alchemy_getTokenAllowance: Returns the amount which the sender is allowed to withdraw from the owner.
  • alchemy_getTokenBalances : Returns ERC20 token balances for all tokens the given address has ever transacted in with. Optionally accepts a list of contracts.
  • alchemy_getTokenMetadata: Returns metadata (name, symbol, decimals, logo) for a given token contract address.

📘

Decoded values

Unless otherwise specified, Alchemy methods will return decoded values in their responses (e.g., for token decimals, 18 will be returned instead of "0x12") to save you the extra step of decoding the value yourself ✅

For this JavaScript quickstart guide, we recommend using the Alchemy SDK, a library that allows you to more easily interact with Alchemy APIs. The Alchemy SDK also gives you WebSocket support and other benefits right out of the box! Fetch or Axios are two alternative modules that also allow you to make HTTP requests.


Common setup steps

If you're new to the Alchemy Quickstart series, you should start with these steps before choosing any of the modules below. If you're a returning dev, go ahead and skip.

Choose a package manager (npm or yarn)

For this guide we will be using npm or yarn as our package manager to install either alchemy-web3, fetch, or axios.

npm

To get started with npm, follow the documentation to install Node.js and npm for your operating system: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm

yarn

To get started with yarn, follow these steps: https://classic.yarnpkg.com/lang/en/docs/install

Set up your repo (npm or yarn)

npm

Open up a terminal, and from the command line, create a new repository to hold your quickstart scripts. We'll also initialize the repo as an npm project.

mkdir alchemy-token-api
cd alchemy-token-api
npm init --yes

yarn

mkdir alchemy-token-api
cd alchemy-token-api
yarn init --yes

Support import syntax

Since we'll be using import syntax to load ES6 modules, add 'type': 'module' to your package.json file:

// package.json
{
  ...
  "type": "module"
}

See this discussion for more context: https://stackoverflow.com/questions/61401475/why-is-type-module-in-package-json-file


How to Query the Token API

Alchemy SDK (Recommended)

You can install the alchemy-sdk module to easily interact with Alchemy APIs. We highly recommend using the alchemy-sdk because you also get WebSocket support, retries, and other benefits without the complexity!

For full documentation on alchemy-sdk, check the github repo: https://github.com/alchemyplatform/alchemy-sdk-js

Installation

Run the following command to install alchemy-sdk with npm or yarn

npm install alchemy-sdk
yarn add alchemy-sdk

Usage

touch alchemy-sdk-script.js

And then paste the following code snippet into the file:

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

const settings = {
  apiKey: "demo", // Replace with your Alchemy API Key.
  network: Network.ETH_MAINNET, // Replace with your network.
};
const alchemy = new Alchemy(settings);

// The wallet address / token we want to query for:
const ownerAddr = "0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be";
const balances = await alchemy.core.getTokenBalances(ownerAddr, [
  "0x607f4c5bb672230e8672085532f7e901544a7375",
]);

// The token address we want to query for metadata:
const metadata = await alchemy.core.getTokenMetadata(
  "0x607f4c5bb672230e8672085532f7e901544a7375"
);

console.log("Token Balances:");
console.log(balances);
console.log("Token Metadata: ");
console.log(metadata);

From your command line, you can execute the script with:

node alchemy-sdk-script.js

You should see output like this:

Token Balances:
{
  address: '0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be',
  tokenBalances: [
    {
      contractAddress: '0x607f4c5bb672230e8672085532f7e901544a7375',
      tokenBalance: '0x0000000000000000000000000000000000000000000000000000000000000000',
      error: null
    }
  ]
}
Token Metadata:
{
  decimals: 9,
  logo: 'https://static.alchemyapi.com/images/assets/1637.png',
  name: 'iExec RLC',
  symbol: 'RLC'
}

Node Fetch

node-fetch is a lightweight, common module that brings the Fetch API to Node.js and allows us to make our HTTP requests.
See the documentation for more info: https://www.npmjs.com/package/node-fetch

Installation

Run the following command to install node-fetch with npm or yarn

npm install node-fetch
yarn add node-fetch

Usage

touch fetch-script.js

and then paste the following code snippet into the file to explore the getNFTs method:=

// alchemy-token-api/fetch-script.js
import fetch from 'node-fetch';

// Replace with your Alchemy API key:
const apiKey = "demo";
const fetchURL = `https://eth-mainnet.g.alchemy.com/v2/${apiKey}`;

// Replace with the wallet address you want to query:
const ownerAddr = "0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be";
// Replace with the token contract address you want to query:
const tokenAddr = "0x607f4c5bb672230e8672085532f7e901544a7375";

var raw = JSON.stringify({
  "jsonrpc": "2.0",
  "method": "alchemy_getTokenBalances",
  "headers": {
    "Content-Type": "application/json"
  },
  "params": [
    `${ownerAddr}`,
    [
      `${tokenAddr}`,
    ]
  ],
  "id": 42
});

var requestOptions = {
  method: 'POST',
  body: raw,
  redirect: 'follow'
};

// Make the request and print the formatted response:
fetch(fetchURL, requestOptions)
  .then(response => response.json())
  .then(response => JSON.stringify(response, null, 2))
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

From your command line, you can execute the script with:

node fetch-script.js

Your output should look like the following:

{
  "jsonrpc": "2.0",
  "id": 42,
  "result": {
    "address": "0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be",
    "tokenBalances": [
      {
        "contractAddress": "0x607f4c5bb672230e8672085532f7e901544a7375",
        "tokenBalance": "0x00000000000000000000000000000000000000000000000000003c005f81ab00",
        "error": null
      }
    ]
  }
}

For full documentation on the NFT API getNFTs method, check out the docs:

Axios

axios is a promise-based HTTP client for the browser and Node.js, which allows us to make a raw request to the Alchemy API.

See the documentation for more info: https://www.npmjs.com/package/axios

Installation

Run the following command to install axios with npm and yarn

npm install axios
yarn add axios

Usage

touch axios-script.js

and then paste the following code snippet in to explore the getNFTs method

// alchemy-token-api/axios-script.js
import axios from 'axios';

// Replace with your Alchemy API key:
const apiKey = "demo";
const baseURL = `https://eth-mainnet.g.alchemy.com/v2/${apiKey}`;
// Replace with the wallet address you want to query:
const ownerAddr = "0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be";
// Replace with the token contract address you want to query:
const tokenAddr = "0x607f4c5bb672230e8672085532f7e901544a7375";

var data = JSON.stringify({
  "jsonrpc": "2.0",
  "method": "alchemy_getTokenBalances",
  "params": [
    `${ownerAddr}`,
    [
      `${tokenAddr}`
    ]
  ],
  "id": 42
});

var config = {
  method: 'post',
  url: baseURL,
  headers: {
    'Content-Type': 'application/json'
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data, null, 2))
})
.catch(function (error) {
  console.log(error);
});

From your command line, you can execute the script with:

node axios-script.js

Your output should look like the following:

alchemy-token-api % node axios-script.js

{
  "jsonrpc": "2.0",
  "id": 42,
  "result": {
    "address": "0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be",
    "tokenBalances": [
      {
        "contractAddress": "0x607f4c5bb672230e8672085532f7e901544a7375",
        "tokenBalance": "0x00000000000000000000000000000000000000000000000000003c005f81ab00",
        "error": null
      }
    ]
  }
}

For full documentation on the available Token API methods, check out the docs:

ReadMe