|

|  How to Get Cryptocurrency Prices with CoinGecko API in Node.js

How to Get Cryptocurrency Prices with CoinGecko API in Node.js

October 31, 2024

Learn how to fetch real-time cryptocurrency prices using the CoinGecko API in Node.js with this step-by-step guide for developers.

How to Get Cryptocurrency Prices with CoinGecko API in Node.js

 

Install Necessary Packages

 

To interact with the CoinGecko API in Node.js, you'll need the coingecko-api package, which provides a convenient wrapper to access the API.

npm install coingecko-api

 

Initialize the CoinGecko Client

 

After installing the package, you need to initialize the CoinGecko client in your project.

const CoinGecko = require('coingecko-api');
const CoinGeckoClient = new CoinGecko();

 

Fetch Current Cryptocurrency Prices

 

Once you have initialized the client, you can fetch the current price of any cryptocurrency using the simple.price method. Here's how you can get the prices for Bitcoin and Ethereum in USD:

async function getPrices() {
    try {
        const response = await CoinGeckoClient.simple.price({
            ids: ['bitcoin', 'ethereum'],
            vs_currencies: ['usd']
        });
        console.log(response.data);
    } catch (error) {
        console.error(error);
    }
}

getPrices();

 

Work with Other Endpoints

 

CoinGecko's API offers a variety of endpoints. For instance, you can retrieve market data with coins.markets. Below is an example that fetches market data for the first 10 coins:

async function getMarketData() {
    try {
        const response = await CoinGeckoClient.coins.markets({
            vs_currency: 'usd',
            order: 'market_cap_desc',
            per_page: 10,
            page: 1
        });
        console.log(response.data);
    } catch (error) {
        console.error(error);
    }
}

getMarketData();

 

Utilize Historical Data

 

To access historical data for a coin, use the coins.fetchHistory method to get price information for a specific date:

async function getHistoricalData() {
    try {
        const response = await CoinGeckoClient.coins.fetchHistory({
            id: 'bitcoin',
            date: '30-12-2021', // Format: dd-mm-yyyy
        });
        console.log(response.data.market_data.current_price.usd);
    } catch (error) {
        console.error(error);
    }
}

getHistoricalData();

 

Error Handling and Debugging

 

When working with any API, robust error handling is crucial. Use try-catch blocks to manage errors gracefully:

async function fetchWithErrorHandling() {
    try {
        const data = await CoinGeckoClient.ping();
        console.log('Ping:', data);
    } catch (error) {
        if (error.response) {
            console.error('Response Error:', error.response.status, error.response.data);
        } else if (error.request) {
            console.error('Request Error:', error.request);
        } else {
            console.error('Error:', error.message);
        }
    }
}

fetchWithErrorHandling();

 

Implement Best Practices

 

  • **Cache Data**: Consider caching API responses to reduce the number of hits to CoinGecko’s server, which can help maintain the efficiency and speed of your application.
  •  

  • **Rate Limits**: Be aware of any rate limits specified by CoinGecko to avoid being blocked. While at the time of writing, CoinGecko offers free unlimited API calls, this is subject to change.
  •  

  • **Environment Configurations**: Keep sensitive information like API keys (if any, in other APIs) secure by using environment variables.
  •  

Limited Beta: Claim Your Dev Kit and Start Building Today

Instant transcription

Access hundreds of community apps

Sync seamlessly on iOS & Android

Order Now

Turn Ideas Into Apps & Earn Big

Build apps for the AI wearable revolution, tap into a $100K+ bounty pool, and get noticed by top companies. Whether for fun or productivity, create unique use cases, integrate with real-time transcription, and join a thriving dev community.

Get Developer Kit Now

OMI AI PLATFORM
Remember Every Moment,
Talk to AI and Get Feedback

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI DEV KIT 2

$69.99

Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

  • Real-time conversation transcription and processing;
  • Develop your own use cases for fun and productivity;
  • Hundreds of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

thought to action

team@basedhardware.com

company

careers

events

invest

privacy

products

omi

omi dev kit

personas

resources

apps

bounties

affiliate

docs

github

help