Skip to content

coolhillblack/simple-crypto-api-js

Repository files navigation

simple-crypto-api-js

A lightweight, zero-dependency JavaScript wrapper for the CoinGecko cryptocurrency API.

Node.js License: MIT PRs Welcome


Features

  • Clean, Promise-based API
  • Zero runtime dependencies (uses Node.js built-in https)
  • Typed error classes for easy error handling
  • Helper utilities for formatting prices and numbers
  • Works with the free CoinGecko tier (no API key required)
  • Optional Pro API key support

Table of Contents


Installation

npm install simple-crypto-api-js

Requirements: Node.js >= 18.0.0


Quick Start

const { CryptoClient } = require('simple-crypto-api-js');

const client = new CryptoClient();

// Get Bitcoin price in USD
const prices = await client.getPrice('bitcoin');
console.log(prices.bitcoin.usd); // e.g. 65000

// Get top 10 coins by market cap
const markets = await client.getMarkets({ perPage: 10 });
markets.forEach(coin => console.log(coin.name, coin.current_price));

Configuration

Pass a config object to the constructor:

const client = new CryptoClient({
  apiKey: 'your-coingecko-pro-key', // optional
  currency: 'eur',                  // default vs_currency (default: 'usd')
  timeout: 15000,                   // request timeout in ms (default: 10000)
});
Option Type Default Description
apiKey string null CoinGecko Pro API key (optional)
currency string 'usd' Default target currency
timeout number 10000 Request timeout in milliseconds
baseUrl string api.coingecko.com Override API base URL (advanced)

API Methods

getPrice(coinIds, options?)

Get the current price for one or more coins.

// Single coin
const result = await client.getPrice('bitcoin');
// { bitcoin: { usd: 65000 } }

// Multiple coins
const result = await client.getPrice(['bitcoin', 'ethereum'], {
  currency: 'eur',
  include24hChange: true,
});

Options:

Option Type Default Description
currency string client default Target currency
includeMarketCap boolean false Include market cap data
include24hChange boolean false Include 24h price change %

getMarkets(options?)

Get paginated list of coins ranked by market cap.

const top50 = await client.getMarkets({ perPage: 50, page: 1 });

Options:

Option Type Default Description
currency string client default vs_currency
perPage number 10 Results per page (max 250)
page number 1 Page number
order string market_cap_desc Sort order

getCoinDetails(coinId, options?)

Get detailed data for a single coin.

const btc = await client.getCoinDetails('bitcoin');
console.log(btc.name);               // 'Bitcoin'
console.log(btc.market_data.ath.usd); // all-time high in USD

getTrending()

Get the top trending coins in the last 24 hours.

const trending = await client.getTrending();
trending.coins.forEach(({ item }) => {
  console.log(item.name, item.symbol);
});

getPriceHistory(coinId, fromDate, toDate, options?)

Get historical price data for a given date range.

const history = await client.getPriceHistory(
  'ethereum',
  '2024-01-01',
  '2024-06-01'
);
// { prices: [[timestamp, price], ...], market_caps: [...], total_volumes: [...] }

search(query)

Search for coins, categories, and markets.

const results = await client.search('sol');
console.log(results.coins); // array of matching coins

getSupportedCurrencies()

Returns an array of all supported vs_currency strings.

const currencies = await client.getSupportedCurrencies();
// ['btc', 'eth', 'usd', 'eur', ...]

Error Handling

All methods throw typed errors. Import them to handle specific cases:

const {
  CryptoAPIError,
  RateLimitError,
  NotFoundError,
  AuthenticationError,
  NetworkError,
} = require('simple-crypto-api-js/errors');

try {
  const price = await client.getPrice('bitcoin');
} catch (err) {
  if (err instanceof RateLimitError) {
    console.log('Too many requests — slow down!');
  } else if (err instanceof NotFoundError) {
    console.log('Coin not found.');
  } else if (err instanceof NetworkError) {
    console.log('Check your internet connection.');
  } else {
    console.log('Unexpected error:', err.message);
  }
}

Error classes

Class Status Code When thrown
CryptoAPIError varies Base class for all errors
RateLimitError 429 API rate limit exceeded
NotFoundError 404 Requested resource not found
AuthenticationError 401/403 Invalid or missing API key
NetworkError null Network failure or timeout
ServerError 5xx API server error

Running the Example

node examples/basicUsage.js

Running Tests

npm test

Tests use the Node.js built-in test runner — no extra packages needed.


Contributing

Contributions are welcome! Please read CONTRIBUTING.md before opening a PR.

See issues.md for a list of open tasks, ranging from beginner-friendly to advanced.


License

MIT

About

A lightweight, zero-dependency JavaScript wrapper for the CoinGecko cryptocurrency API.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors