September 7, 2023

Free Crypto Price API – How to Get Live Cryptocurrency Prices

Table of Contents

In today’s tutorial, we’ll show you how to use the industry’s #1 crypto price API – the Moralis Price API – to fetch an asset’s real-time and historical price. We’ll also briefly show you how to make batch requests to fetch the prices of multiple assets simultaneously. If you’re eager to get going, then here are three quick examples of how it works: 

  • Fetch Real-Time Prices
    With a single API call to the getTokenPrice() endpoint, you can seamlessly fetch the real-time price of an asset: 
import Moralis from 'moralis';

try {
  await Moralis.start({
    apiKey: "YOUR_API_KEY"
  });

  const response = await Moralis.EvmApi.token.getTokenPrice({
    "chain": "0x1",
    "address": "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0"
  });

  console.log(response.raw);
} catch (e) {
  console.error(e);
}
  • Get Historical Prices
    By specifying the toBlock parameter when calling the getTokenPrice() endpoint, you can effortlessly get the price of an asset at a given point in time: 
import Moralis from 'moralis';

try {
  await Moralis.start({
    apiKey: "YOUR_API_KEY"
  });

  const response = await Moralis.EvmApi.token.getTokenPrice({
    "chain": "0x1",
    "toBlock": 18085987,
    "address": "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0"
  });

  console.log(response.raw);
} catch (e) {
  console.error(e);
}
  • Make Batch Requests
    You can make batch requests by passing an array of addresses to get the price of multiple tokens in a single response:
// Dependencies to install:
// $ npm install node-fetch --save
// add "type": "module" to package.json

import fetch from 'node-fetch';

const options = {
  method: 'POST',
  headers: {
    accept: 'application/json',
    'content-type': 'application/json',
    'X-API-Key': 'YOUR_API_KEY'
  },
  body: JSON.stringify({
    "tokens": [
      {
        "token_address": "0xae7ab96520de3a18e5e111b5eaab095312d7fe84",
        "to_block": 16314545
      }
    ]
  })
};

fetch('https://deep-index.moralis.io/api/v2.2/erc20/prices?chain=eth&include=percent_change', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

Getting price data with the Moralis Price API has never been easier. By familiarizing yourself with this API, you can spin up Web3 applications in no time. You can also learn more about the use cases above by checking out the official Moralis Price API documentation

Also, don’t forget to sign up with Moralis immediately so you can start leveraging the full power of the blockchain industry today! 

Overview

We’ll kickstart today’s article by exploring the intricacies of crypto price APIs. From there, we’ll look closer at why you might need a price API for cryptocurrency in the first place. Next, we’re going to cover some prominent crypto price API use cases. In doing so, we’ll introduce the Moralis Price API and show you how to use this tool to fetch price data. More specifically, we’ll show you how to: 

  1. Fetch real-time price data
  2. Get historical token prices
  3. Make batch requests

So, if you are already familiar with the ins and outs of crypto price APIs, feel free to skip to the ”Crypto Price API Use Cases” section and get straight into the code! 

Otherwise, join us in the following section as we look at what a crypto price API is!

What is a Crypto Price API?

Cross-system communication is essential when building applications and websites, as they don’t work optimally in isolation in today’s interconnected world. As such, developers need efficient ways to enable decoupled software systems to communicate with one another. Fortunately, this is precisely where APIs enter the equation. 

But what exactly is an API? And how do they work in the context of Web3 development?

A crypto API, short for application programming interface, is a set of rules, protocols, and methods allowing you to seamlessly interact with blockchain networks and integrate crypto-related functionality into your applications, software, and websites. They provide a structured way to access data and perform actions related to blockchain networks, cryptocurrencies, and decentralized applications (dapps). 

Crypto Price API Code Blocks

A crypto price API is a specific type of interface specializing in price data, and it allows you to seamlessly access real-time and historical prices for various cryptocurrencies, like ETH (Ethereum), BTC (Bitcoin), etc.

All in all, crypto price APIs make the process of querying blockchain networks for pricing data straightforward. Furthermore, they play an integral role in the Web3 development space, making your job as a developer significantly more accessible! 

Why Do You Need a Live Crypto Price API? 

It doesn’t matter if you plan to build a decentralized exchange (DEX) or the next MetaMask; you’ll almost always need to integrate pricing data when building Web3 projects. And by leveraging a crypto price API, you can save an abundance of time and development resources! 

Querying blockchain networks is a tedious task, and if you’re doing it from scratch, it can quickly become a time-consuming process. So, instead of “reinventing the wheel”, you can simply use a crypto price API to get real-time and historical price data with a few lines of code. That way, you can allocate your time and resources toward more critical tasks like serving your end users. 

Illustrative image showing how live price data shows up when using a crypto price API

By leveraging a crypto price API, you’ll instantly gain a competitive advantage and can move to market much quicker than your competitors! 

Crypto Price API Use Cases

With an overview of what crypto price APIs are and why you need them, let’s now explore the industry’s leading interface: the Moralis Price API. The API offered by Moralis has multiple use cases, and in the following sections, we’ll cover three prominent examples: 

  • Fetch real-time prices
  • Get historical price data
  • Make batch requests
Moralis Price API - The Ultimate Crypto Price API - Get Started for Free!

However, before we show you how to use the Moralis Price API to fetch real-time token prices, you initially need to deal with a couple of prerequisites! 

Prerequisites 

Before you get started with the free crypto Price API from Moralis, you initially need to have the following installed: 

  • Node v.14+ or Python
  • NPM/Yarn or Pip

You also need to register with Moralis to get your API key. As such, if you haven’t already, hit the ”Start for Free” button at the top right on Moralis‘ homepage: 

Showing the Start For Free Button on Moralis Website

Once you’ve set up your account, go to the ”Web3 APIs” tab and hit the ”Get your API keys” button: 

Moralis UI and the Crypto Price API Key

With the API key at your disposal, you also need to run the following command in the root folder of your project to install the Moralis SDK: 

npm install moralis @moralisweb3/common-evm-utils

Now that’s it; you are now ready to start using the Moralis Price API to fetch price data! So, without further ado, let’s jump straight into the first use case and show you how to fetch real-time prices using the industry’s leading price API for crypto! 

Fetch Real-Time Prices 

With the Moralis Price API, you can effortlessly query the real-time price of any ERC-20 token. All it requires is a single API call, and here’s an example of what it might look like: 

import Moralis from 'moralis';

try {
  await Moralis.start({
    apiKey: "YOUR_API_KEY"
  });

  const response = await Moralis.EvmApi.token.getTokenPrice({
    "chain": "0x1",
    "address": "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0"
  });

  console.log(response.raw);
} catch (e) {
  console.error(e);
}

Once you run the code above, you’ll get a response looking something like this: 

{
  "tokenName": "Matic Token",
  "tokenSymbol": "MATIC",
  "tokenLogo": "https://cdn.moralis.io/eth/0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0.png",
  "tokenDecimals": "18",
  "nativePrice": {
    "value": "332947305392970",
    "decimals": 18,
    "name": "Ether",
    "symbol": "ETH",
    "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
  },
  "usdPrice": 0.5423105104030737,
  "usdPriceFormatted": "0.5423105104030737",
  "exchangeAddress": "0x1f98431c8ad98523631ae4a59f267346ea31f984",
  "exchangeName": "Uniswap v3",
  "tokenAddress": "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0"
}

By simply passing the chain and contract address as parameters when calling the getTokenPrice() endpoint, you’ll get the token’s real-time price denominated in both the native cryptocurrency of the chain and USD. 

Note: Don’t forget to replace YOUR_API_KEY with your actual Moralis API key.  

Get Historical Price Data 

In addition to fetching the real-time price of a token, you can just as easily use the Moralis Price API to query the price at any given point in time. To do so, you simply need to input a timestamp or a block number, and the crypto Price API from Moralis takes care of the rest! 

So, how does it work? 

To get the historical price of a token, you can simply use the getTokenPrice() endpoint once again. However, this time, you need to specify the toBlock parameter. Here’s an example of what it can look like:

import Moralis from 'moralis';

try {
  await Moralis.start({
    apiKey: "YOUR_API_KEY"
  });

  const response = await Moralis.EvmApi.token.getTokenPrice({
    "chain": "0x1",
    "toBlock": 18085987,
    "address": "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0"
  });

  console.log(response.raw);
} catch (e) {
  console.error(e);
}

In return, you’ll get a response looking something like this: 

{
  "tokenName": "Matic Token",
  "tokenSymbol": "MATIC",
  "tokenLogo": "https://cdn.moralis.io/eth/0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0.png",
  "tokenDecimals": "18",
  "nativePrice": {
    "value": "338661989977717",
    "decimals": 18,
    "name": "Ether",
    "symbol": "ETH",
    "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
  },
  "usdPrice": 0.5535986848542233,
  "usdPriceFormatted": "0.5535986848542233",
  "exchangeAddress": "0x1f98431c8ad98523631ae4a59f267346ea31f984",
  "exchangeName": "Uniswap v3",
  "tokenAddress": "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0",
  "toBlock": "18085987"
}

Once again, you get the price denominated in both the chain’s native token as well as USD. However, this time, it is the price from the specified timestamp/block number.

Note: Don’t forget to replace YOUR_API_KEY with your actual Moralis API key.  

Make Batch Requests 

Lastly, with the Moralis Price API, you can make batch requests to fetch the price of multiple tokens simultaneously and in a single response. To do so, you simply need to specify an array of token addresses, and here’s an example of what it might look like: 

// Dependencies to install:
// $ npm install node-fetch --save
// add "type": "module" to package.json

import fetch from 'node-fetch';

const options = {
  method: 'POST',
  headers: {
    accept: 'application/json',
    'content-type': 'application/json',
    'X-API-Key': 'YOUR_API_KEY'
  },
  body: JSON.stringify({
    "tokens": [
      {
        "token_address": "0xae7ab96520de3a18e5e111b5eaab095312d7fe84",
        "to_block": 16314545
      }
    ]
  })
};

fetch('https://deep-index.moralis.io/api/v2.2/erc20/prices?chain=eth&include=percent_change', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

In return, you’ll receive an array containing token prices denominated in the blockchain’s native currency and USD. Here’s an example response:

[
  {
    "tokenName": "stETH",
    "tokenSymbol": "stETH",
    "tokenLogo": "https://cdn.moralis.io/eth/0xae7ab96520de3a18e5e111b5eaab095312d7fe84.png",
    "tokenDecimals": "18",
    "nativePrice": {
      "value": "985900938416575600",
      "decimals": 18,
      "name": "Ether",
      "symbol": "ETH",
      "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
    },
    "usdPrice": 1183.2332106724853,
    "usdPriceFormatted": "1183.2332106724853",
    "24hrPercentChange": "-27.08746487985908",
    "exchangeAddress": "0x1f98431c8ad98523631ae4a59f267346ea31f984",
    "exchangeName": "Uniswap v3",
    "tokenAddress": "0xae7ab96520de3a18e5e111b5eaab095312d7fe84",
    "toBlock": "16314545"
  }
]

That’s it; when working with the Moralis Price API, it doesn’t have to be more complex than that to fetch current and historical token prices! 

Note: Don’t forget to replace YOUR_API_KEY with your actual Moralis API key.  

Why Use the Moralis Crypto Price API? 

In combination with the use cases above, there are multiple additional reasons why you should opt for the Moralis Price API for crypto. To highlight why, we’ll look at some benefits and advantages of Moralis’ industry-leading crypto Price API in this section! 

Illurtation of various token prices being fed using the Moralis Crypto Price API
  • Prices for All Tokens: If you have had enough of lousy coverage and missing tokens, then you’ll want to start using the Moralis Price API. With this API, coins show up instantaneously as they start trading on any DEX. We monitor every new coin and liquidity pool to give you the latest price data as soon as it becomes available. There are no approval processes and no gatekeeping!
  • Instant Updates: The Moralis Price API updates with every new block, ensuring you get the most recent crypto price data. What’s more, with Moralis, you can seamlessly add instant webhook alerts using the Streams API to get notified as soon as the price of a token changes. 

    If you want to learn more about this, please check out the Moralis Streams API product page!
  • Support for All Major EVM Chains: The Moralis Price API supports all major EVM chains and multiple DEXs. Some prominent examples include QuickSwap, Camelot, Uniswap, TraderJoe, and many others. Consequently, the Moralis Price API is the only price API you need to build your Web3 projects!

Now, how does Moralis compare to other crypto price API providers? 

The Moralis Crypto Price API vs. Other Alternatives 

With coverage ranging from the smallest and newest coins to the most well-established cryptocurrencies, Moralis provides the most comprehensive API on the market. Furthermore, the Moralis crypto Price API is the industry’s premier option by any metric, including features, competitive pricing, and speed! 

For instance, here’s a comparison with competitors like CoinMarketCap and CoinGecko:

Moralis Crypto Price API vs CoinGecko Price API vs CoinMarketCap Crypto API - Table with Metrics

So, if you’re planning to build a Web3 project where you need price data, create your free Moralis account today and start leveraging the true power of blockchain technology!

Beyond the Crypto Price API 

The Price API for crypto is just the tip of the iceberg, and there’s a lot more to Moralis. Furthermore, the free crypto Price API works like a charm together with the other interfaces in Moralis’ Web3 API suite. As such, if you’re serious about building Web3 projects, consider checkout out some of our other products: 

  • Wallet API: The perfect API for building Web3 wallets.
  • Token API: A powerful out-of-the-box solution for fetching ERC-20 token data in real time.
  • Balance API: Get the token balance for any user wallet.
  • DeFi API: Fetch pair and liquidity reserve data across multiple blockchain networks. 
  • Transaction API: Get detailed transactions and log data in a heartbeat. 

Moralis’ Multi-Chain Compatibility 

Did you know you don’t limit yourself to one blockchain network when working with Moralis? Moralis supports chain-agnostic building, meaning you can build Web3 projects and dapps across the most popular blockchain networks. Some prominent examples include Ethereum, BNB Smart Chain, Polygon, Avalanche, and many others.

The Moralis team is working hard daily on adding new networks and integrations. As such, you can expect additional blockchain networks and even more cross-chain compatibility in the future!

Summary: Free Crypto Price API 

We kickstarted today’s article by exploring the ins and outs of price APIs for crypto. In doing so, we learned that a crypto price API is a set of rules, methods, and protocols enabling you to effortlessly interact with and integrate blockchain-related functionality into your projects. 

From there, we introduced the Moralis Price API for crypto. Furthermore, we demonstrated how to fetch real-time token prices, get historical token prices, and make batch requests! Consequently, if you have followed along this far, you now know how to use the Moralis Price API to fetch the data you need to build more sophisticated Web3 projects! 

If this is your ambition, feel free to check out some additional content here at the Web3 blog. For instance, learn how to create a blockchain explorer or dive into Web3 marketplace development

Also, if you haven’t already, make sure to sign up with Moralis. You can create your account for free to get immediate access to the various APIs. With these tools, you can start leveraging the full power of Web3 technology straight away!

Join the Moralis Community
Get the latest Moralis Web3 news and updates via email.
Related Articles
September 29, 2022

How to Connect PlayFab with Web3 Using Azure Functions

January 2, 2023

Get Contract Logs – Exploring Web3 Get Event Logs for Ethereum

January 16, 2023

The Best Ethereum Faucet in 2023

September 25, 2022

Full Guide: How to Build an Ethereum Dapp in 5 Steps

March 10, 2023

How to Get Real-Time Crypto Wallet Balance Updates

December 13, 2022

Tutorial for Blockchain Developers on How to Get All Transfers of an NFT

November 1, 2022

Cross-Chain Bridging Deep-Dive

November 9, 2022

Solana Smart Contract Examples for Developers

October 18, 2022

Add Dynamic Web3 Authentication to a Website