In as we speak’s tutorial, we’ll present you the best way to use the {industry}’s #1 crypto worth API – the Moralis Worth API – to fetch an asset’s real-time and historic worth. We’ll additionally briefly present you the best way to make batch requests to fetch the costs of a number of belongings concurrently. Should you’re desirous to get going, then listed below are three fast examples of the way it works:
Fetch Actual-Time PricesWith a single API name to the getTokenPrice() endpoint, you may seamlessly fetch the real-time worth of an asset: import Moralis from ‘moralis’;
strive {
await Moralis.begin({
apiKey: “YOUR_API_KEY”
});
const response = await Moralis.EvmApi.token.getTokenPrice({
“chain”: “0x1”,
“tackle”: “0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0”
});
console.log(response.uncooked);
} catch (e) {
console.error(e);
} Get Historic PricesBy specifying the toBlock parameter when calling the getTokenPrice() endpoint, you may effortlessly get the worth of an asset at a given cut-off date: import Moralis from ‘moralis’;
strive {
await Moralis.begin({
apiKey: “YOUR_API_KEY”
});
const response = await Moralis.EvmApi.token.getTokenPrice({
“chain”: “0x1”,
“toBlock”: 18085987,
“tackle”: “0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0”
});
console.log(response.uncooked);
} catch (e) {
console.error(e);
} Make Batch RequestsYou could make batch requests by passing an array of addresses to get the worth of a number of tokens in a single response:// Dependencies to put in:
// $ npm set up node-fetch –save
// add “sort”: “module” to package deal.json
import fetch from ‘node-fetch’;
const choices = {
technique: ‘POST’,
headers: {
settle for: ‘software/json’,
‘content-type’: ‘software/json’,
‘X-API-Key’: ‘YOUR_API_KEY’
},
physique: JSON.stringify({
“tokens”: [
{
“token_address”: “0xae7ab96520de3a18e5e111b5eaab095312d7fe84”,
“to_block”: 16314545
}
]
})
};
fetch(‘https://deep-index.moralis.io/api/v2.2/erc20/costs?chain=eth&embody=percent_change’, choices)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
Getting worth knowledge with the Moralis Worth API has by no means been simpler. By familiarizing your self with this API, you may spin up Web3 purposes very quickly. It’s also possible to be taught extra concerning the use instances above by testing the official Moralis Worth API documentation.
Additionally, don’t neglect to enroll with Moralis instantly so you can begin leveraging the complete energy of the blockchain {industry} as we speak!
Overview
We’ll kickstart as we speak’s article by exploring the intricacies of crypto worth APIs. From there, we’ll look nearer at why you would possibly want a worth API for cryptocurrency within the first place. Subsequent, we’re going to cowl some outstanding crypto worth API use instances. In doing so, we’ll introduce the Moralis Worth API and present you the best way to use this software to fetch worth knowledge. Extra particularly, we’ll present you the best way to:
Fetch real-time worth dataGet historic token pricesMake batch requests
So, in case you are already aware of the ins and outs of crypto worth APIs, be at liberty to skip to the ”Crypto Worth API Use Instances” part and get straight into the code!
In any other case, be part of us within the following part as we take a look at what a crypto worth API is!
What’s a Crypto Worth API?
Cross-system communication is important when constructing purposes and web sites, as they don’t work optimally in isolation in as we speak’s interconnected world. As such, builders want environment friendly methods to allow decoupled software program methods to speak with each other. Luckily, that is exactly the place APIs enter the equation.
However what precisely is an API? And the way do they work within the context of Web3 growth?
A crypto API, brief for software programming interface, is a algorithm, protocols, and strategies permitting you to seamlessly work together with blockchain networks and combine crypto-related performance into your purposes, software program, and web sites. They supply a structured option to entry knowledge and carry out actions associated to blockchain networks, cryptocurrencies, and decentralized purposes (dapps).
A crypto worth API is a selected sort of interface specializing in worth knowledge, and it permits you to seamlessly entry real-time and historic costs for varied cryptocurrencies, like ETH (Ethereum), BTC (Bitcoin), and so on.
All in all, crypto worth APIs make the method of querying blockchain networks for pricing knowledge easy. Moreover, they play an integral position within the Web3 growth area, making your job as a developer considerably extra accessible!
Why Do You Want a Reside Crypto Worth API?
It doesn’t matter for those who plan to construct a decentralized alternate (DEX) or the subsequent MetaMask; you’ll nearly all the time must combine pricing knowledge when constructing Web3 tasks. And by leveraging a crypto worth API, it can save you an abundance of time and growth sources!
Querying blockchain networks is a tedious process, and for those who’re doing it from scratch, it could actually shortly turn into a time-consuming course of. So, as an alternative of “reinventing the wheel”, you may merely use a crypto worth API to get real-time and historic worth knowledge with just a few strains of code. That approach, you may allocate your time and sources towards extra crucial duties like serving your finish customers.
![Illustrative image showing how live price data shows up when using a crypto price API](https://moralis.io/wp-content/uploads/2023/09/Illustrative-image-showing-how-live-price-data-shows-up-when-using-a-crypto-price-API-1024x509.jpeg)
By leveraging a crypto worth API, you’ll immediately achieve a aggressive benefit and may transfer to market a lot faster than your rivals!
Crypto Worth API Use Instances
With an summary of what crypto worth APIs are and why you want them, let’s now discover the {industry}’s main interface: the Moralis Worth API. The API provided by Moralis has a number of use instances, and within the following sections, we’ll cowl three outstanding examples:
Fetch real-time pricesGet historic worth dataMake batch requests
![Moralis Price API - The Ultimate Crypto Price API - Get Started for Free!](https://moralis.io/wp-content/uploads/2023/09/Moralis-Price-API-The-Ultimate-Crypto-Price-API-Get-Started-for-Free-1024x307.png)
Nevertheless, earlier than we present you the best way to use the Moralis Worth API to fetch real-time token costs, you initially must cope with a few conditions!
Conditions
Earlier than you get began with the free crypto Worth API from Moralis, you initially must have the next put in:
Node v.14+ or PythonNPM/Yarn or Pip
You additionally must register with Moralis to get your API key. As such, for those who haven’t already, hit the ”Begin for Free” button on the prime proper on Moralis‘ homepage:
![Showing the Start For Free Button on Moralis Website](https://moralis.io/wp-content/uploads/2023/09/Showing-the-Start-For-Free-Button-on-Moralis-Website-1024x339.png)
When you’ve arrange your account, go to the ”Web3 APIs” tab and hit the ”Get your API keys” button:
![Moralis UI and the Crypto Price API Key](https://moralis.io/wp-content/uploads/2023/09/Moralis-UI-and-the-Crypto-Price-API-Key-1024x392.png)
With the API key at your disposal, you additionally must run the next command within the root folder of your mission to put in the Moralis SDK:
npm set up moralis @moralisweb3/common-evm-utils
Now that’s it; you are actually prepared to begin utilizing the Moralis Worth API to fetch worth knowledge! So, with out additional ado, let’s leap straight into the primary use case and present you the best way to fetch real-time costs utilizing the {industry}’s main worth API for crypto!
Fetch Actual-Time Costs
With the Moralis Worth API, you may effortlessly question the real-time worth of any ERC-20 token. All it requires is a single API name, and right here’s an instance of what it would seem like:
import Moralis from ‘moralis’;
strive {
await Moralis.begin({
apiKey: “YOUR_API_KEY”
});
const response = await Moralis.EvmApi.token.getTokenPrice({
“chain”: “0x1”,
“tackle”: “0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0”
});
console.log(response.uncooked);
} catch (e) {
console.error(e);
}
When you run the code above, you’ll get a response trying one thing like this:
{
“tokenName”: “Matic Token”,
“tokenSymbol”: “MATIC”,
“tokenLogo”: “https://cdn.moralis.io/eth/0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0.png”,
“tokenDecimals”: “18”,
“nativePrice”: {
“worth”: “332947305392970”,
“decimals”: 18,
“identify”: “Ether”,
“image”: “ETH”,
“tackle”: “0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2”
},
“usdPrice”: 0.5423105104030737,
“usdPriceFormatted”: “0.5423105104030737”,
“exchangeAddress”: “0x1f98431c8ad98523631ae4a59f267346ea31f984”,
“exchangeName”: “Uniswap v3”,
“tokenAddress”: “0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0”
}
By merely passing the chain and contract tackle as parameters when calling the getTokenPrice() endpoint, you’ll get the token’s real-time worth denominated in each the native cryptocurrency of the chain and USD.
Word: Don’t neglect to interchange YOUR_API_KEY along with your precise Moralis API key.
Get Historic Worth Information
Along with fetching the real-time worth of a token, you may simply as simply use the Moralis Worth API to question the worth at any given cut-off date. To take action, you merely must enter a timestamp or a block quantity, and the crypto Worth API from Moralis takes care of the remaining!
So, how does it work?
To get the historic worth of a token, you may merely use the getTokenPrice() endpoint as soon as once more. Nevertheless, this time, you should specify the toBlock parameter. Right here’s an instance of what it could actually seem like:
import Moralis from ‘moralis’;
strive {
await Moralis.begin({
apiKey: “YOUR_API_KEY”
});
const response = await Moralis.EvmApi.token.getTokenPrice({
“chain”: “0x1”,
“toBlock”: 18085987,
“tackle”: “0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0”
});
console.log(response.uncooked);
} catch (e) {
console.error(e);
}
In return, you’ll get a response trying one thing like this:
{
“tokenName”: “Matic Token”,
“tokenSymbol”: “MATIC”,
“tokenLogo”: “https://cdn.moralis.io/eth/0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0.png”,
“tokenDecimals”: “18”,
“nativePrice”: {
“worth”: “338661989977717”,
“decimals”: 18,
“identify”: “Ether”,
“image”: “ETH”,
“tackle”: “0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2”
},
“usdPrice”: 0.5535986848542233,
“usdPriceFormatted”: “0.5535986848542233”,
“exchangeAddress”: “0x1f98431c8ad98523631ae4a59f267346ea31f984”,
“exchangeName”: “Uniswap v3”,
“tokenAddress”: “0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0”,
“toBlock”: “18085987”
}
As soon as once more, you get the worth denominated in each the chain’s native token in addition to USD. Nevertheless, this time, it’s the worth from the required timestamp/block quantity.
Word: Don’t neglect to interchange YOUR_API_KEY along with your precise Moralis API key.
Make Batch Requests
Lastly, with the Moralis Worth API, you can also make batch requests to fetch the worth of a number of tokens concurrently and in a single response. To take action, you merely must specify an array of token addresses, and right here’s an instance of what it would seem like:
// Dependencies to put in:
// $ npm set up node-fetch –save
// add “sort”: “module” to package deal.json
import fetch from ‘node-fetch’;
const choices = {
technique: ‘POST’,
headers: {
settle for: ‘software/json’,
‘content-type’: ‘software/json’,
‘X-API-Key’: ‘YOUR_API_KEY’
},
physique: JSON.stringify({
“tokens”: [
{
“token_address”: “0xae7ab96520de3a18e5e111b5eaab095312d7fe84”,
“to_block”: 16314545
}
]
})
};
fetch(‘https://deep-index.moralis.io/api/v2.2/erc20/costs?chain=eth&embody=percent_change’, choices)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
In return, you’ll obtain an array containing token costs denominated within the blockchain’s native foreign money and USD. Right here’s an instance 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 Worth API, it doesn’t need to be extra complicated than that to fetch present and historic token costs!
Word: Don’t neglect to interchange YOUR_API_KEY along with your precise Moralis API key.
Why Use the Moralis Crypto Worth API?
Together with the use instances above, there are a number of extra the explanation why you need to go for the Moralis Worth API for crypto. To focus on why, we’ll take a look at some advantages and benefits of Moralis’ industry-leading crypto Worth API on this part!
![Illurtation of various token prices being fed using the Moralis Crypto Price API](https://moralis.io/wp-content/uploads/2023/09/Illurtation-of-various-token-prices-being-fed-using-the-Moralis-Crypto-Price-API-1024x509.jpeg)
Costs for All Tokens: In case you have had sufficient of awful protection and lacking tokens, you then’ll wish to begin utilizing the Moralis Worth API. With this API, cash present up instantaneously as they begin buying and selling on any DEX. We monitor each new coin and liquidity pool to provide the newest worth knowledge as quickly because it turns into accessible. There aren’t any approval processes and no gatekeeping! Help for All Main EVM Chains: The Moralis Worth API helps all main EVM chains and a number of DEXs. Some outstanding examples embody QuickSwap, Camelot, Uniswap, TraderJoe, and plenty of others. Consequently, the Moralis Worth API is the one worth API you should construct your Web3 tasks!
Now, how does Moralis evaluate to different crypto worth API suppliers?
The Moralis Crypto Worth API vs. Different Alternate options
With protection starting from the smallest and latest cash to probably the most well-established cryptocurrencies, Moralis supplies probably the most complete API available on the market. Moreover, the Moralis crypto Worth API is the {industry}’s premier possibility by any metric, together with options, aggressive pricing, and velocity!
For example, right here’s a comparability with rivals like CoinMarketCap and CoinGecko:
![Moralis Crypto Price API vs CoinGecko Price API vs CoinMarketCap Crypto API - Table with Metrics](https://moralis.io/wp-content/uploads/2023/09/Moralis-Crypto-Price-API-vs-CoinGecko-Price-API-vs-CoinMarketCap-Crypto-API-Table-with-Metrics-1024x509.png)
So, for those who’re planning to construct a Web3 mission the place you want worth knowledge, create your free Moralis account as we speak and begin leveraging the true energy of blockchain expertise!
Past the Crypto Worth API
The Worth API for crypto is simply the tip of the iceberg, and there’s much more to Moralis. Moreover, the free crypto Worth API works like a appeal along with the opposite interfaces in Moralis’ Web3 API suite. As such, for those who’re severe about constructing Web3 tasks, contemplate checkout out a few of our different merchandise:
Pockets API: The proper API for constructing Web3 wallets.Token API: A robust out-of-the-box resolution for fetching ERC-20 token knowledge in actual time.Steadiness API: Get the token steadiness for any person pockets.DeFi API: Fetch pair and liquidity reserve knowledge throughout a number of blockchain networks. Transaction API: Get detailed transactions and log knowledge in a heartbeat.
Moralis’ Multi-Chain Compatibility
Do you know you don’t restrict your self to 1 blockchain community when working with Moralis? Moralis helps chain-agnostic constructing, which means you may construct Web3 tasks and dapps throughout the preferred blockchain networks. Some outstanding examples embody Ethereum, BNB Sensible Chain, Polygon, Avalanche, and plenty of others.
The Moralis staff is working onerous day by day on including new networks and integrations. As such, you may count on extra blockchain networks and much more cross-chain compatibility sooner or later!
Abstract: Free Crypto Worth API
We kickstarted as we speak’s article by exploring the ins and outs of worth APIs for crypto. In doing so, we realized {that a} crypto worth API is a algorithm, strategies, and protocols enabling you to effortlessly work together with and combine blockchain-related performance into your tasks.
From there, we launched the Moralis Worth API for crypto. Moreover, we demonstrated the best way to fetch real-time token costs, get historic token costs, and make batch requests! Consequently, if in case you have adopted alongside this far, you now know the best way to use the Moralis Worth API to fetch the information you should construct extra subtle Web3 tasks!
If that is your ambition, be at liberty to take a look at some extra content material right here on the Web3 weblog. For example, learn to create a blockchain explorer or dive into Web3 market growth.
Additionally, for those who haven’t already, ensure that to enroll with Moralis. You possibly can create your account at no cost to get fast entry to the assorted APIs. With these instruments, you can begin leveraging the complete energy of Web3 expertise immediately!