@allratestoday/sdk

中文文档
1.4.15发布于 2026/11/03MITTypeScriptESM + CJS零依赖近 30 天下载 2073

Exchange Rate API — Real-time mid-market currency exchange rates for Node.js and browsers. 160+ currencies, zero dependencies, free tier.

原始使用文档
文档目录27 节
  1. 🚀 Why Choose This Client?
  2. 🔑 Get Your API Key
  3. 📦 Installation
  4. 🏁 Quick Start
  5. 📚 API Reference
  6. Latest Exchange Rates
  7. Historical Exchange Rates
  8. Currency Conversion
  9. Available Currencies
  10. Time Series Data
  11. Single Rate
  12. Official Central-Bank & Tax-Authority Rates (no key needed)
  13. Historical Rates by Period
  14. 🔧 Configuration
  15. 🔀 Per-Request API Key Override
  16. 🛡️ Error Handling
  17. 🔷 TypeScript
  18. 📦 CommonJS
  19. 💡 Examples
  20. Currency Dropdown (React)
  21. Price Display with Caching
  22. Historical Chart Data
  23. 📖 Methods Reference
  24. 🧪 Testing
  25. 🤖 Use it from an AI agent
  26. 🔗 Links
  27. 📜 License

Exchange Rate API — @allratestoday/sdk

npm version codecov license TypeScript zero dependencies Security: Snyk

Real-time mid-market currency exchange rates for Node.js and browsers. The most elegant way to access 160+ currencies.

🚀 Why Choose This Client?

  • ⚡ Lightning Fast — Zero runtime dependencies, pure TypeScript performance
  • 📡 Real-Time Data — Rates updated every 60 seconds
  • 💹 Mid-Market Rates — No retail spread or markup baked in
  • 🌍 160+ Currencies — Major, minor, and exotic currency pairs
  • 🏛️ Official Rates Too — latest tables from 122 central banks and 4 tax authorities via officialRates(), no key needed
  • 🔷 Type-Safe — Full TypeScript support with intelligent autocomplete
  • 🌐 Universal — Works seamlessly in Node.js 18+ and modern browsers
  • 🧑‍💻 Developer-Friendly — Simple API, extensive documentation, and great DX

🔑 Get Your API Key

Ready to start? Get your free API key from allratestoday.com/register.

📦 Installation

npm install @allratestoday/sdk
yarn add @allratestoday/sdk
pnpm add @allratestoday/sdk

🏁 Quick Start

Get up and running in seconds:

import AllRatesToday from '@allratestoday/sdk';

// Set your API key
const client = new AllRatesToday({ apiKey: 'YOUR_API_KEY' });

// Get latest exchange rates
const { rates } = await client.latest({ base: 'USD', symbols: ['EUR', 'GBP', 'JPY'] });
console.log(rates);

📚 API Reference


Latest Exchange Rates

Get the most current exchange rates with a single call:

// Get all rates from USD
const data = await client.latest();
console.log(data);

// Target specific currencies
const data = await client.latest({ base: 'USD', symbols: ['CHF', 'GBP', 'JPY'] });
console.log(data);

Response:

{
  base: 'USD',
  date: '2026-04-09T14:30:00Z',
  rates: {
    CHF: 0.8821,
    GBP: 0.7891,
    JPY: 151.42
  }
}

Historical Exchange Rates

Historical methods (forDate, timeSeries, getHistoricalRates and convert with a date) need a paid plan from €4.99/month. Free and trial keys get latest rates only and receive a 403 historical_requires_paid_plan for history.

Travel back in time to get rates from any date:

// Using a string date
const data = await client.forDate('2026-01-15', { base: 'USD', symbols: ['EUR'] });
console.log(data);

// Using a Date object
const data = await client.forDate(new Date('2026-01-15'), { base: 'EUR', symbols: ['USD', 'GBP'] });
console.log(data);

Response:

{
  base: 'USD',
  date: '2026-01-15',
  rates: {
    EUR: 0.9187
  }
}

Currency Conversion

Convert any amount between currencies — including historical conversions (paid plans):

// Current conversion
const result = await client.convert('USD', 'EUR', 1000);
console.log(result);

Response:

{
  from: 'USD',
  to: 'EUR',
  amount: 1000,
  result: 923.4,
  rate: 0.9234
}
// Historical conversion — what was $1,000 worth on Jan 15?
const result = await client.convert('USD', 'EUR', 1000, { date: '2026-01-15' });
console.log(result);

Response:

{
  from: 'USD',
  to: 'EUR',
  amount: 1000,
  result: 918.7,
  rate: 0.9187,
  date: '2026-01-15'
}

Available Currencies

Discover all 160+ supported currency symbols and names:

const data = await client.symbols();
console.log(data);

Response:

{
  symbols: {
    AED: 'United Arab Emirates Dirham',
    AFN: 'Afghan Afghani',
    ALL: 'Albanian Lek',
    AMD: 'Armenian Dram',
    AUD: 'Australian Dollar',
    BDT: 'Bangladeshi Taka',
    BRL: 'Brazilian Real',
    CAD: 'Canadian Dollar',
    CHF: 'Swiss Franc',
    CNY: 'Chinese Yuan',
    EUR: 'Euro',
    GBP: 'British Pound Sterling',
    INR: 'Indian Rupee',
    JPY: 'Japanese Yen',
    KRW: 'South Korean Won',
    USD: 'United States Dollar',
    // ...160+ currencies
  }
}

Time Series Data

Get exchange rates over a date range for trend analysis and charting (paid plans):

const data = await client.timeSeries('2026-01-01', '2026-03-31', {
  base: 'USD',
  symbols: ['EUR', 'GBP'],
});
console.log(data);

Response:

{
  base: 'USD',
  startDate: '2026-01-01',
  endDate: '2026-03-31',
  rates: {
    '2026-01-01': {
      EUR: 0.9187,
      GBP: 0.7834
    },
    '2026-01-02': {
      EUR: 0.9195,
      GBP: 0.7841
    },
    '2026-01-03': {
      EUR: 0.9201,
      GBP: 0.7856
    },
    // ...
  }
}

Single Rate

Get a single exchange rate between two currencies:

const rate = await client.getRate('USD', 'EUR');
console.log(rate);

Response:

{
  from: { currency: 'USD', amount: 1 },
  to: { currency: 'EUR', amount: 0.9234 },
  rate: 0.9234,
  source: 'wise'
}
// With amount
const rate = await client.getRate('USD', 'EUR', 500);
console.log(`$500 = €${rate.to.amount}`);

Official Central-Bank & Tax-Authority Rates (no key needed)

The methods above return live mid-market rates. For the official rate an institution published — what invoices, VAT returns, customs declarations and audits require — use officialRates(). It covers 122 central banks plus HMRC, the US Treasury, Swiss BAZG and India's CBIC, and the latest table needs no API key:

const client = new AllRatesToday(); // no key

// Full ECB reference table
const table = await client.officialRates('ecb');
console.log(table.rate_date, table.rates); // [{ base: 'EUR', quote: 'USD', type: 'reference', value: 1.17 }, …]

// One pair (cross-computed inside the bank's own table if not published directly → `derived: true`)
const usd = await client.officialRates('ecb', { source: 'EUR', target: 'USD' });
console.log(`ECB ${usd.rate_date}: 1 EUR = ${usd.rate} USD`);

// Which sources exist, and which are behind their publication schedule
const { sources } = await client.officialSources();
console.log(sources.map((s) => `${s.code} ${s.latest}${s.stale ? ' (stale)' : ''}`));

Always cite the returned rate_date — it is the institution's publication date, not the time of your call. Dated tables and history need a paid plan and use /api/v1/central-bank/{bank}/{date}; publication calendars work on any key. See the central bank rates API.

Historical Rates by Period

Get historical rates using preset periods — no date math needed (paid plans):

const history = await client.getHistoricalRates('USD', 'EUR', '30d');
console.log(history);

Response:

{
  source: 'USD',
  target: 'EUR',
  period: '30d',
  current: { rate: 0.9234, time: '2026-04-09T14:30:00Z' },
  rates: [
    { rate: 0.9198, time: '2026-03-10T00:00:00Z' },
    { rate: 0.9210, time: '2026-03-11T00:00:00Z' },
    // ...
  ]
}

Available periods: 1d | 7d | 30d | 1y


🔧 Configuration

const client = new AllRatesToday({
  apiKey: 'YOUR_API_KEY',          // Required — get one free at allratestoday.com/register
  baseUrl: 'https://allratestoday.com', // Optional — API base URL
  timeout: 10000,                       // Optional — request timeout in ms
});
OptionTypeDefaultDescription
apiKeystring—Your API key
baseUrlstringhttps://allratestoday.comAPI base URL
timeoutnumber10000Request timeout in milliseconds

🔀 Per-Request API Key Override

Every method supports a per-request API key override — useful for multi-tenant apps:

const client = new AllRatesToday({ apiKey: 'default_key' });

// Override for a specific request
const data = await client.latest({ apiKey: 'other_users_key' });
const result = await client.convert('USD', 'EUR', 100, { apiKey: 'tenant_key' });
const { symbols } = await client.symbols({ apiKey: 'another_key' });

🛡️ Error Handling

All errors are thrown as AllRatesTodayError with an optional HTTP status code:

import AllRatesToday, { AllRatesTodayError } from '@allratestoday/sdk';

try {
  const rate = await client.getRate('USD', 'INVALID');
} catch (err) {
  if (err instanceof AllRatesTodayError) {
    console.log(err.message); // "Currency not found"
    console.log(err.status);  // 404
  }
}
StatusMeaning
—Missing API key (thrown before request)
401Invalid API key
404Currency code not found
429Rate limit exceeded
500Server error

🔷 TypeScript

The SDK is written in TypeScript and ships full type definitions. All interfaces are exported:

import AllRatesToday, {
  AllRatesTodayError,
  AllRatesTodayOptions,
  RequestOptions,
  RateResponse,
  AuthRateResponse,
  LatestOptions,
  LatestResponse,
  ForDateOptions,
  ForDateResponse,
  ConvertOptions,
  ConvertResponse,
  TimeSeriesOptions,
  TimeSeriesResponse,
  HistoricalRateResponse,
  SymbolsResponse,
} from '@allratestoday/sdk';

📦 CommonJS

const AllRatesToday = require('@allratestoday/sdk').default;

const client = new AllRatesToday({ apiKey: 'YOUR_API_KEY' });
client.latest().then(data => console.log(data.rates));

💡 Examples

Currency Dropdown (React)

import { useEffect, useState } from 'react';
import AllRatesToday from '@allratestoday/sdk';

const client = new AllRatesToday({ apiKey: 'YOUR_API_KEY' });

function CurrencySelect({ value, onChange }) {
  const [currencies, setCurrencies] = useState([]);

  useEffect(() => {
    client.symbols().then(({ symbols }) => {
      setCurrencies(
        Object.entries(symbols).map(([code, name]) => ({ code, name }))
      );
    });
  }, []);

  return (
    <select value={value} onChange={e => onChange(e.target.value)}>
      {currencies.map(c => (
        <option key={c.code} value={c.code}>{c.code} — {c.name}</option>
      ))}
    </select>
  );
}

Price Display with Caching

import AllRatesToday from '@allratestoday/sdk';

const client = new AllRatesToday({ apiKey: 'YOUR_API_KEY' });
let cache: { rates: Record<string, number>; time: number } | null = null;
const TTL = 5 * 60 * 1000; // 5 minutes

async function getPrice(amountUSD: number, currency: string): Promise<string> {
  if (!cache || Date.now() - cache.time > TTL) {
    const data = await client.latest({ base: 'USD' });
    cache = { rates: data.rates, time: Date.now() };
  }
  const converted = (amountUSD * cache.rates[currency]).toFixed(2);
  return `${converted} ${currency}`;
}

console.log(await getPrice(99.99, 'EUR')); // "92.32 EUR"
console.log(await getPrice(99.99, 'GBP')); // "78.90 GBP"

Historical Chart Data

Needs a paid plan (history is not included in free or trial keys).

import AllRatesToday from '@allratestoday/sdk';

const client = new AllRatesToday({ apiKey: 'YOUR_API_KEY' });

const data = await client.timeSeries('2026-01-01', '2026-04-01', {
  base: 'USD',
  symbols: ['EUR'],
});

// Format for charting libraries (Chart.js, Recharts, etc.)
const labels = Object.keys(data.rates).sort();
const values = labels.map(date => data.rates[date].EUR);

console.log({ labels, values });
// { labels: ['2026-01-01', '2026-01-02', ...], values: [0.92, 0.921, ...] }

📖 Methods Reference

MethodDescription
latest(options?)Get latest rates for one or more currencies
forDate(date, options?)Get rates for a specific historical date (paid plan)
convert(from, to, amount, options?)Convert amount between currencies (historical date needs a paid plan)
timeSeries(start, end, options?)Get rates across a custom date range (paid plan)
symbols(options?)List all 160+ supported currency codes and names
getRate(from, to, amount?, options?)Get a single exchange rate
getRates(source, target, options?)Get rates with full metadata
getHistoricalRates(source, target, period?, options?)Historical rates by preset period (1d/7d/30d/1y; paid plan)
officialRates(bank, options?)Latest official table (or one pair) published by a central bank / tax authority — keyless
officialSources(options?)Every covered official source with latest publication date and freshness — keyless

🧪 Testing

Run isolated unit tests (no API calls needed):

npm test

Run tests with coverage report:

npm run test:coverage

Watch mode for development:

npm run test:watch

🤖 Use it from an AI agent

The same rates are available to coding agents and LLM tools without a second integration:

  • Claude Code plugin (no key): /plugin marketplace add AllRates-Today/claude-code-plugin then /plugin install allratestoday@allratestoday
  • Hosted MCP endpoint: https://allratestoday.com/api/mcp — Streamable HTTP, keyless, nothing to install
  • Local MCP servers: npx -y @allratestoday/mcp-server (live mid-market rates) · npx -y @allratestoday/central-bank-mcp (official central-bank rates)
  • Trial key for agents, no signup: POST https://allratestoday.com/api/agent/keys (send Content-Type: application/json) returns a 100-call key valid 7 days for latest rates and latest central-bank tables (history and dated tables are paid-plan only); both MCP servers expose it as request_trial_key
  • Daily Reference Rate (first published 2026-10-12): one fixed USD table per business day, the 16:00 London median of minute samples, never revised — keyless at https://allratestoday.com/api/open/reference-rate, get_reference_rate in the MCP server
  • Machine-readable site guide: llms.txt

📜 License

MIT

版本与发布记录

@allratestoday/sdk 共发布 32 个版本,首次发布于 2026/04/06;过去 12 个月发布了 32 个版本。

版本发布日期距今
1.4.15latest2026/11/035 天前
1.4.142026/11/016 天前
1.4.132026/10/317 天前
1.4.122026/10/2711 天前
1.4.112026/10/2711 天前
1.4.102026/10/2217 天前

关于 @allratestoday/sdk 的常见问题

@allratestoday/sdk 是什么?

Exchange Rate API — Real-time mid-market currency exchange rates for Node.js and browsers. 160+ currencies, zero dependencies, free tier.

如何安装 @allratestoday/sdk?

在项目目录运行 npm install @allratestoday/sdk,或使用 pnpm add / yarn add / bun add。

@allratestoday/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@allratestoday/sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@allratestoday/sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@allratestoday/sdk 可以商用吗?

@allratestoday/sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@allratestoday/sdk 的下载量有多少?

根据 npm 官方下载统计,@allratestoday/sdk 在 2026/10/06 – 2026/11/04 这 30 天内被下载 2,073 次,日均约 69 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@allratestoday/sdk 还在维护吗?

最新版本 1.4.15 发布于 2026/11/03(5 天前);至今共发布 32 个版本,其中过去 12 个月发布了 32 个;首次发布于 2026/04/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。