### Install Specific Version Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md Examples of installing specific versions or distribution tags of the npm package. ```bash npm install @fawazahmed0/currency-api@2024.3.6 npm install @fawazahmed0/currency-api@latest npm install @fawazahmed0/currency-api@2024-03-06 # dist tag ``` -------------------------------- ### Fetch from npm (Node.js) Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md Node.js example showing how to read currency exchange rates from the locally installed npm package using the 'fs' module. ```javascript // Install: npm install @fawazahmed0/currency-api const fs = require('fs'); const path = require('path'); // Read from installed package const usdRates = JSON.parse( fs.readFileSync( require.resolve('@fawazahmed0/currency-api/v1/currencies/usd.json'), 'utf-8' ) ); console.log('1 USD = ? EUR:', usdRates.usd.eur); ``` -------------------------------- ### Install via npm Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md Command to install the currency API npm package using npm. ```bash npm install @fawazahmed0/currency-api ``` -------------------------------- ### Install via yarn Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md Command to install the currency API npm package using yarn. ```bash yarn add @fawazahmed0/currency-api ``` -------------------------------- ### Base URL Examples Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/endpoints.md Examples of the primary and fallback base URLs for the API, demonstrating how to construct URLs for different dates and endpoints. ```url https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{date}/v1/{endpoint} ``` ```url https://{date}.currency-api.pages.dev/v1/{endpoint} ``` -------------------------------- ### v1 API Request Example Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md This is an example of a request made to the v1 API to get all exchange rates for EUR against other currencies. ```http GET /currencies/eur.json ``` -------------------------------- ### v0 API Request Example Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md This is an example of a request made to the v0 API to get the exchange rate between EUR and USD. ```http GET /currencies/eur/usd.json ``` -------------------------------- ### Cryptocurrency Prices Inversion Calculation Example Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/data-sources.md Example calculation demonstrating the inversion of cryptocurrency prices from USD base to a crypto base. ```javascript const inverted = 1 / 47500.25 // = 0.000021063... ``` -------------------------------- ### Install Dependencies and Playwright Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/configuration.md Installs system packages, swap space, npm dependencies, and Playwright browsers. Swap space is recommended for memory-intensive operations. ```bash sudo apt-get update -y sudo apt-get install swapspace -y npm i npx playwright install --with-deps ``` -------------------------------- ### v0 URL Example (404) Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md Demonstrates a v0 URL that will no longer work with the v1 API and will result in a 404 Not Found error. ```http https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/eur/usd.json # Returns: 404 Not Found ``` -------------------------------- ### Direct Download Tarball URL Example Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md Example URL for directly downloading a specific version of the npm package tarball from the npm registry. ```bash https://registry.npmjs.org/@fawazahmed0/currency-api/-/@fawazahmed0-currency-api-2024.3.6.tgz ``` -------------------------------- ### Country-to-Currency Mapping Example Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/types.md An example of the country-to-currency mapping object, showing data for the US, UK, and Japan. ```javascript { "us": { "country_name": "united states", "country_iso3": "usa", "country_iso_numeric": "840", "currency_name": "us dollar", "currency_code": "usd", "currency_number": "840" }, "gb": { "country_name": "united kingdom", "country_iso3": "gbr", "country_iso_numeric": "826", "currency_name": "pound sterling", "currency_code": "gbp", "currency_number": "826" }, "jp": { "country_name": "japan", "country_iso3": "jpn", "country_iso_numeric": "392", "currency_name": "japanese yen", "currency_code": "jpy", "currency_number": "392" } } ``` -------------------------------- ### Example Input/Output for Lowercase Currency Conversion Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/utility-scripts.md Illustrates the transformation of currency code mappings from uppercase to lowercase to enable case-insensitive lookups. ```javascript { "USD": "US Dollar", "EUR": "Euro" } Into: { "usd": "us dollar", "eur": "euro" } ``` -------------------------------- ### Example URL Comparison: v0 vs v1 Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md Illustrates the difference in URL structure for fetching currency data between v0 and v1, showing both 'latest' and specific date formats. ```text https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/eur.json https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/2024-03-06/currencies/eur.json ``` ```text https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/eur.json https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@2024-03-06/v1/currencies/eur.json ``` -------------------------------- ### Exchange Rate Object Example Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/types.md An example of an exchange rate object, showing the date and rates for USD against several other currencies. ```javascript { "date": "2024-03-06", "usd": { "eur": 0.92104, "gbp": 0.79533, "jpy": 145.23, "inr": 83.12, "btc": 0.000021, "eth": 0.0000653 } } ``` -------------------------------- ### Complete Migration Example: v0 Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md A complete v0 function to fetch an exchange rate between two currencies for a specific date, returning the direct rate. ```javascript async function getExchangeRate(from, to, date = 'latest') { const url = `https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/${date}/currencies/${from}/${to}.json`; const data = await fetch(url).then(r => r.json()); return data.rate; } // Usage const usdToEur = await getExchangeRate('usd', 'eur', 'latest'); console.log(usdToEur); // e.g., 0.92104 ``` -------------------------------- ### Usage Example for Date Filtering Arguments Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/utility-scripts.md Demonstrates how to use the generated date-based filtering arguments with Cloudflare Wrangler for managing file retention. ```bash wrangler pages deployment delete $(node getdate-args.js) ``` -------------------------------- ### Install Playwright Dependencies Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/DOCUMENTATION_INDEX.md Installs Playwright browser binaries and dependencies. This is often required for end-to-end testing or browser automation tasks within the project. ```bash npm install npx playwright install --with-deps ``` -------------------------------- ### Complete Migration Example: v1 Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md The equivalent v1 function to fetch an exchange rate. It uses the new URL structure and accesses the rate via nested properties. ```javascript async function getExchangeRate(from, to, date = 'latest') { const url = `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@${date}/v1/currencies/${from}.json`; const data = await fetch(url).then(r => r.json()); return data[from][to]; } // Usage const usdToEur = await getExchangeRate('usd', 'eur', 'latest'); console.log(usdToEur); // e.g., 0.92104 ``` -------------------------------- ### Currency Codes Object Example Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/types.md An example of the Currency Codes object, illustrating the mapping of currency codes (fiat, crypto, precious metals) to their respective names. ```javascript { "usd": "US Dollar", "eur": "Euro", "gbp": "British Pound", "jpy": "Japanese Yen", "inr": "Indian Rupee", "btc": "Bitcoin", "eth": "Ethereum", "ada": "Cardano", "bnb": "Binance Coin", "usdt": "Tether", "xau": "Gold", "xag": "Silver", "42": "42 Coin", "300": "300 token" } ``` -------------------------------- ### Example Output JSON for ISO Currency Codes Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/utility-scripts.md Shows the expected JSON output format for the 'isocodes.json' file, containing an array of unique ISO 4217 currency codes. ```json ["AFN", "EUR", "ALL", "DZD", "USD", ...] ``` -------------------------------- ### Example Output JSON for Country/Currency Data Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/utility-scripts.md Illustrates the structure of the generated 'bigJSON.json' file, where each key is a country's ISO 3166-1 alpha-2 code. ```json { "us": { "country_name": "united states", "country_iso3": "usa", "country_iso_numeric": "840", "currency_name": "us dollar", "currency_code": "usd", "currency_number": "840" }, "gb": { "country_name": "united kingdom", "country_iso3": "gbr", "country_iso_numeric": "826", "currency_name": "pound sterling", "currency_code": "gbp", "currency_number": "826" }, ... } ``` -------------------------------- ### v0 API Response Example Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md This is the JSON response format for a v0 API request, showing a single exchange rate. ```json { "rate": 1.17 } ``` -------------------------------- ### v1 API Response Example Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md This is the JSON response format for a v1 API request, showing the date and multiple exchange rates for a base currency. ```json { "date": "2024-03-06", "eur": { "usd": 1.17, "gbp": 0.87, "jpy": 125.34, "btc": 0.0000215, ... } } ``` -------------------------------- ### Fetch Current USD to EUR Rate using cURL Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/endpoints.md Example using cURL to fetch the latest exchange rates where USD is the base currency. ```bash curl https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/usd.json ``` -------------------------------- ### GET /currencies/{code} Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/INDEX.txt Retrieves exchange rates for a specified base currency against all other currencies. ```APIDOC ## GET /currencies/{code} ### Description Gets exchange rates for a specified base currency. ### Method GET ### Endpoint /currencies/{code} ### Parameters #### Path Parameters - **code** (string) - Required - The base currency code (e.g., EUR, USD). #### Query Parameters None ### Response #### Success Response (200) - **date** (string) - The date for which the rates are provided. - **base** (string) - The base currency code. - **rates** (object) - An object containing exchange rates for other currencies relative to the base currency. ### Response Example { "example": { "date": "2024-01-01", "base": "EUR", "rates": { "USD": 1.10, "GBP": 0.85 } } } ``` -------------------------------- ### Fetch Historical Rates using cURL Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/endpoints.md Example using cURL to fetch historical exchange rates for a specific date (March 6, 2024) with EUR as the base currency. ```bash curl https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@2024-03-06/v1/currencies/eur.json ``` -------------------------------- ### Initiate Data Pipeline Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/currscript.md The `begin()` function orchestrates the entire data pipeline. It is automatically called on module load to fetch currencies, generate API files, manage package versions, and copy supporting data. ```javascript begin() ``` -------------------------------- ### GET /currencies Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/endpoints.md Lists all available currency codes and their full names. This is useful for discovering which currencies the API supports. ```APIDOC ## GET /currencies ### Description Lists all available currency codes and their full names. ### Method GET ### Endpoint /currencies ### Parameters #### Query Parameters - **date** (string) - Optional - Specifies the date for the exchange rates. Accepts 'latest' or a date in 'YYYY-MM-DD' format. - **format** (string) - Optional - Specifies the output format. Accepts '.json' (prettified) or '.min.json' (minified). ### Response #### Success Response (200) - **{currencyCode}** (string) - The three-letter ISO 4217 currency code (uppercase) or crypto ticker symbol (uppercase) and its full name. ### Response Example ```json { "usd": "US Dollar", "eur": "Euro", "gbp": "British Pound", "jpy": "Japanese Yen", "btc": "Bitcoin", "eth": "Ethereum" } ``` ``` -------------------------------- ### Fetch All Sources Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/data-sources.md Fetches initial data from three different sources. Source 1 uses a provided link, while Sources 2 and 3 are fetched directly. ```javascript let currDataObj = await getCurrData(currLink) // Source 1: EUR base let currDataObj3 = await getCurrData3() // Source 2: USD base let cryptoDataObj = await getCryptoData() // Source 3: USD base ``` -------------------------------- ### Update Package Version and Write Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md JavaScript code snippet demonstrating how to read a skeleton package.json, update its version field, and write it to the output directory. ```javascript let barePackage = fs.readJsonSync(pathToSkeletonPackage) barePackage['version'] = dateTodaySemVer fs.writeJSONSync(path.join(rootDir, '..' ,"package.json"), barePackage) ``` -------------------------------- ### GET /currencies/{currencyCode} Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/endpoints.md Retrieves exchange rates for a specific currency against all other supported currencies. This endpoint is essential for performing currency conversions. ```APIDOC ## GET /currencies/{currencyCode} ### Description Get exchange rates for a specific currency as the base currency, with conversion rates to all other supported currencies. ### Method GET ### Endpoint /currencies/{currencyCode} ### Parameters #### Path Parameters - **currencyCode** (string) - Required - Three-letter ISO 4217 code (lowercase) or crypto ticker (lowercase). Example: `usd`, `eur`, `btc`, `eth` #### Query Parameters - **date** (string) - Optional - Specifies the date for the exchange rates. Accepts 'latest' or a date in 'YYYY-MM-DD' format. - **format** (string) - Optional - Specifies the output format. Accepts '.json' (prettified) or '.min.json' (minified). ### Response #### Success Response (200) - **date** (string) - ISO 8601 date (YYYY-MM-DD) when rates were captured. - **{currencyCode}** (object) - Nested object with target currency code as key. - **{currencyCode}.{targetCode}** (number) - Exchange rate: how much 1 unit of base currency equals in target currency. Up to 20 decimal places for small values. ### Response Example (USD as base) ```json { "date": "2024-03-06", "usd": { "eur": 0.92104, "gbp": 0.79533, "jpy": 145.23, "inr": 83.12, "btc": 0.000021 } } ``` ### Response Example (BTC as base) ```json { "date": "2024-03-06", "btc": { "usd": 47500.25, "eur": 43712.48, "eth": 16.35 } } ``` ``` -------------------------------- ### Fetch from CDN Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md JavaScript code snippet demonstrating how to fetch currency data directly from a CDN. ```javascript const url = 'https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/usd.json'; const response = await fetch(url); const data = await response.json(); ``` -------------------------------- ### Manual Execution of Currscript.js Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/currscript.md Set environment variables required by the script and then execute it using Node.js. Ensure all necessary links and keys are defined. ```bash # Set environment variables (or create links.ini file) export currlink="https://..." \ currlink2="https://..." \ currlink3="https://..." \ currlink3key="regex-pattern" \ cryptolink="https://..." # Run the script node currscript.js ``` -------------------------------- ### Deploy to Cloudflare Pages Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md Commands to deploy the package to Cloudflare Pages. Includes deploying the latest version and a specific dated version. ```bash wrangler pages deploy --project-name=currency-api package wrangler pages deploy --project-name=currency-api --branch=latest package wrangler pages deploy --project-name=currency-api --branch=2024-03-06 package ``` -------------------------------- ### Get Specific Currency Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/INDEX.txt Retrieves detailed information for a specific currency code. This endpoint is useful for validating a currency code or obtaining its full name. ```APIDOC ## GET /currencies/{code} ### Description Retrieves detailed information for a specific currency code. ### Method GET ### Endpoint /currencies/{code} ### Parameters #### Path Parameters - **code** (string) - Required - The currency code to retrieve information for (e.g., 'usd', 'eur', 'btc'). ### Request Example None ### Response #### Success Response (200) - **currency** (string) - The full name of the currency. #### Response Example ```json { "currency": "United States Dollar" } ``` ``` -------------------------------- ### Create Tar Archive Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/configuration.md Creates a tar archive of the package directory. ```bash 7z a package.tar package -ttar ``` -------------------------------- ### Get exchange rates for a base currency Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/DOCUMENTATION_INDEX.md This endpoint retrieves exchange rates for a specified base currency. It supports filtering by date and output format. ```APIDOC ## GET /currencies/{code} ### Description Get exchange rates for a base currency. ### Method GET ### Endpoint /currencies/{code} ### Parameters #### Path Parameters - **code** (string) - Required - The currency code (e.g., USD, EUR). #### Query Parameters - **date** (string) - Optional - Date parameter: `latest` or `YYYY-MM-DD`. - **format** (string) - Optional - Format options: `.json` (prettified) or `.min.json` (minified). ### Response #### Success Response (200) - **data** (object) - Contains exchange rates for the base currency. ### Response Example { "example": "{\"eur\": 0.92, \"gbp\": 0.79}" } ``` -------------------------------- ### Get Current Date in ISO Format Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/currscript.md Generates the current date in ISO 8601 format (YYYY-MM-DD). This is used as the 'date' field in generated JSON files. ```javascript const dateToday = new Date().toISOString().substring(0, 10) ``` -------------------------------- ### Generate Version with Date Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/DOCUMENTATION_INDEX.md Format the version number using a date-based approach with Node.js. ```bash node semver-date.js ``` -------------------------------- ### Get Currency List with Specific Base Currency Source: https://github.com/fawazahmed0/exchange-api/blob/main/README.md Retrieve currency exchange rates with a specified base currency, optionally on a specific date and in a minified format. ```APIDOC ## GET /currencies/{currencyCode} ### Description Get the currency list with a specified base currency. ### Method GET ### Endpoint `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{date}/v1/currencies/{currencyCode}.json` ### Path Parameters - **currencyCode** (string) - Required - The base currency code (e.g., EUR, BTC). ### Query Parameters - **date** (string) - Optional - The date should either be `latest` or in `YYYY-MM-DD` format. ### Response #### Success Response (200) - **date** (string) - The date for which the exchange rates are provided. - **base_currency** (string) - The base currency code. - **target_currency_code** (number) - The exchange rate for the target currency. ### Response Example ```json { "date": "2024-03-06", "eur": { "usd": 1.085, "jpy": 162.73 }, "btc": { "usd": 67000, "eur": 61750 } } ``` ## GET /currencies/{currencyCode}.min.json ### Description Get a minified version of the currency list with a specified base currency. ### Method GET ### Endpoint `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{date}/v1/currencies/{currencyCode}.min.json` ### Path Parameters - **currencyCode** (string) - Required - The base currency code (e.g., EUR, BTC). ### Query Parameters - **date** (string) - Optional - The date should either be `latest` or in `YYYY-MM-DD` format. ### Response #### Success Response (200) - **date** (string) - The date for which the exchange rates are provided. - **base_currency** (string) - The base currency code. - **target_currency_code** (number) - The exchange rate for the target currency. ### Response Example ```json { "date": "2024-03-06", "eur": { "usd": 1.085, "jpy": 162.73 }, "btc": { "usd": 67000, "eur": 61750 } } ``` ``` -------------------------------- ### Checkout Repository Action Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/configuration.md Uses the actions/checkout@v6 action to checkout the repository. ```yaml - uses: actions/checkout@v6 ``` -------------------------------- ### Get Available Currency Names Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/currscript.md Maps currency codes to their full names using reference data. Logs a warning if a currency code is not found in the reference data. ```javascript async function getAvailCurrencyJSON(CurrObj) ``` ```json { "usd": "US Dollar", "eur": "Euro", "gbp": "British Pound", "btc": "Bitcoin", ... } ``` -------------------------------- ### Environment Variables from File Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/configuration.md When not in a CI environment, environment variables are read from the 'links.ini' file. Each URL or value should be on a new line. ```ini {currlink_url} {currlink2_url} {currlink3_url} {currlink3_key_regex} {cryptolink_url} ``` -------------------------------- ### Deploy to Cloudflare Pages Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/DOCUMENTATION_INDEX.md Deploy the project to Cloudflare Pages using the Wrangler CLI. ```bash wrangler pages deploy --project-name=currency-api --branch={date} package ``` -------------------------------- ### Get Exchange Rates for a Specific Currency Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/endpoints.md Retrieves exchange rates for a specified base currency against all other supported currencies. The currency code should be in lowercase. Supports specifying a date and output format. ```http https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/eur.json ``` ```http https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/btc.min.json ``` ```http https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@2024-03-06/v1/currencies/eur.json ``` -------------------------------- ### List All Available Currencies Source: https://github.com/fawazahmed0/exchange-api/blob/main/README.md Retrieve a list of all supported currencies in a prettified JSON format or a minified version. ```APIDOC ## GET /currencies ### Description Lists all the available currencies in prettified JSON format. ### Method GET ### Endpoint `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{date}/v1/currencies.json` ### Query Parameters - **date** (string) - Optional - The date should either be `latest` or in `YYYY-MM-DD` format. ### Response #### Success Response (200) - **currency_code** (object) - An object where keys are currency codes and values are currency names. ### Response Example ```json { "eur": "Euro", "usd": "United States Dollar", "btc": "Bitcoin" } ``` ## GET /currencies.min.json ### Description Get a minified version of the available currencies list. ### Method GET ### Endpoint `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{date}/v1/currencies.min.json` ### Query Parameters - **date** (string) - Optional - The date should either be `latest` or in `YYYY-MM-DD` format. ### Response #### Success Response (200) - **currency_code** (object) - An object where keys are currency codes and values are currency names. ### Response Example ```json { "eur": "Euro", "usd": "United States Dollar", "btc": "Bitcoin" } ``` ``` -------------------------------- ### Get Significant Number for Exchange Rates Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/configuration.md This JavaScript function calculates the appropriate number of decimal places for an exchange rate. It uses 8 decimal places for rates greater than or equal to 0.1 and preserves significant digits for smaller rates. ```javascript function getSignificantNum(num){ let minSignificantDigits = 8 if(num >= 0.1) return parseFloat(num.toFixed(minSignificantDigits)) // ... for smaller numbers, preserve leading zeros + 8 significant } ``` -------------------------------- ### List All Currencies Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/endpoints.md Fetches a list of all supported currency codes and their full names. Use the .json extension for prettified output or .min.json for minified output. Supports specifying a date for historical data. ```http https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies.json ``` ```http https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies.min.json ``` ```http https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@2024-03-06/v1/currencies.json ``` -------------------------------- ### Deploy to Cloudflare Pages (Production) Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/configuration.md Deploys the package to the production branch of the Cloudflare Pages project. ```bash wrangler pages deploy --project-name=currency-api package ``` -------------------------------- ### Generate Currency Exchange Rate JSON Files Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/currscript.md Asynchronously generates a JSON file for each supported currency, containing current exchange rates against all other currencies. It creates both prettified and minified versions of each file in the 'package/v1/currencies/' directory. ```javascript async function generateFiles(googBingCurrJSON) { // Implementation details omitted for brevity } ``` ```json { "date": "2024-03-06", "usd": { "eur": 0.92104, "gbp": 0.79533, "jpy": 145.23, ... } } ``` -------------------------------- ### Extract Exchange Rate using JavaScript Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/endpoints.md Demonstrates how to use the Fetch API in JavaScript to retrieve exchange rates and extract a specific rate (USD to EUR) from the JSON response. ```javascript const response = await fetch('https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/usd.json'); const data = await response.json(); const usdToEur = data.usd.eur; // e.g., 0.92104 ``` -------------------------------- ### Tarball Creation and Publishing Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md Bash commands for creating a gzipped tar archive of the package and publishing it to npm. ```bash 7z a package.tar package -ttar # Create tar archive 7z a package.tar.gz package.tar -tgzip -mx=9 # Gzip with max compression npm publish --access public package.tar.gz # Publish to npm ``` -------------------------------- ### Deploy to Cloudflare Pages (Date-Specific Branch) Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/configuration.md Deploys the package to a date-specific branch on Cloudflare Pages, using an environment variable for the branch name. ```bash wrangler pages deploy --project-name=currency-api --branch=${{ env.date_today }} package ``` -------------------------------- ### Execute Node.js Script in CI/CD Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/utility-scripts.md Runs a Node.js script to set environment variables for date and semver date in GitHub Actions. ```yaml - name: Set date today run: | echo "date_today=`date -uI`" >> "$GITHUB_ENV" echo "date_today_semver=`node semver-date.js`" >> "$GITHUB_ENV" ``` -------------------------------- ### Publish to npm Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/DOCUMENTATION_INDEX.md Publish the package to the npm registry with public access. ```bash npm publish --access public package.tar.gz ``` -------------------------------- ### Run Data Generation Script Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/DOCUMENTATION_INDEX.md Execute the main data generation script using Node.js. ```bash node currscript.js ``` -------------------------------- ### Update Base URL: v0 vs v1 Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md Compare the old v0 base URL with the new v1 base URL. The v1 URL uses npm and includes a '/v1/' path segment. ```text https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/{date}/{endpoint} ``` ```text https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{date}/v1/{endpoint} ``` -------------------------------- ### Date-Based Versioning Logic Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md JavaScript code demonstrating the conversion of the current date into a date-based semantic version format. ```javascript const dateToday = new Date().toISOString().substring(0, 10) // "2024-03-06" const dateTodaySemVer = semver.clean( dateToday.replaceAll('-', '.'), // "2024.03.06" true ) // "2024.3.6" (leading zeros removed) ``` -------------------------------- ### Deploy to Cloudflare Pages (Latest Branch) Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/configuration.md Deploys the package to the 'latest' branch of the Cloudflare Pages project. ```bash wrangler pages deploy --project-name=currency-api --branch=latest package ``` -------------------------------- ### Root Output Directory Path Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/currscript.md Constructs the root directory path where generated API files will be saved. The path includes the API version number, e.g., 'package/v1/'. ```javascript const rootDir = path.join(__dirname, 'package', `v${apiVersion}`) ``` -------------------------------- ### Response Navigation: v0 Direct Access Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md Illustrates how to access the exchange rate in v0 responses using direct property access. ```javascript const exchangeRate = await fetch('https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/eur/usd.json') .then(r => r.json()) const rate = exchangeRate.rate // Direct access // rate = 1.17 ``` -------------------------------- ### generateFiles Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/currscript.md Generates JSON files for each supported currency code, containing the current date and exchange rates to all other currencies. It creates both prettified and minified versions of each file. ```APIDOC ## generateFiles(googBingCurrJSON) ### Description Generates a JSON file for every supported currency code. Each file contains the current date and exchange rates from that currency to all others. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **googBingCurrJSON** (Object) - Required - Object with currency codes as keys and rates as values (all against a common base like EUR) ### Side Effects - Creates directory: `package/v1/currencies/` - Generates two files per currency: - `{currencyCode}.json` (prettified) - `{currencyCode}.min.json` (minified) ### Request Example ```javascript // Assuming googBingCurrJSON contains rates against EUR generateFiles(googBingCurrJSON); ``` ### Response #### Success Response (200) * **void** - This function does not return a value but has side effects of creating files. #### Response Example *No direct response body, file generation is the output.* **File Output Format:** ```json { "date": "2024-03-06", "{baseCurrency}": { "{targetCurrency}": 0.92104, ... } } ``` **Example Generated File:** `usd.json` ```json { "date": "2024-03-06", "usd": { "eur": 0.92104, "gbp": 0.79533, "jpy": 145.23, ... } } ``` ``` -------------------------------- ### Secondary Fiat Rates Environment Variables Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/data-sources.md Environment variables for the URL and regex pattern to scrape secondary fiat rates. ```bash currlink3 = {URL} # Website URL to scrape currlink3key = {REGEX} # Regex pattern to match API responses ``` -------------------------------- ### Fetch Current Exchange Rate Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/START_HERE.md Demonstrates how to fetch the latest exchange rate for USD to EUR using the public CDN. Ensure you have a fetch implementation available. ```javascript const url = 'https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/usd.json'; const response = await fetch(url); const data = await response.json(); const usdToEur = data.usd.eur; // e.g., 0.92104 console.log(`1 USD = ${usdToEur} EUR`); ``` -------------------------------- ### Implementation with Fallback Mechanism Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/migration.md A robust function that attempts to fetch exchange rates from jsDelivr first and falls back to a Cloudflare Pages URL if the primary provider fails. ```javascript async function getExchangeRate(from, to, date = 'latest') { const providers = [ `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@${date}/v1/currencies/${from}.json`, `https://${date}.currency-api.pages.dev/v1/currencies/${from}.json` ]; for (const url of providers) { try { const response = await fetch(url); if (response.ok) { const data = await response.json(); return data[from]?.[to]; } } catch (err) { console.warn(`Failed to fetch from ${url}:`, err); continue; } } throw new Error('Failed to fetch exchange rate from all providers'); } // Usage const usdToEur = await getExchangeRate('usd', 'eur', 'latest'); console.log(usdToEur); ``` -------------------------------- ### Exchange API File Organization Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/PROJECT_OVERVIEW.md Illustrates the directory structure and key files within the exchange-api project, including data collection scripts, generated output, and utility scripts. ```tree exchange-api/ ├── currscript.js # Main data collection and generation script ├── semver-date.js # Date to semantic versioning converter ├── allcurrencies.min.json # Reference: 7000+ currency code → name mappings ├── country.json # Country code to currency mappings ├── package/ # Generated output directory │ └── v1/ │ ├── currencies.json # All currency codes and names │ ├── currencies.min.json │ └── currencies/ # Per-currency rate files │ ├── usd.json # All rates with USD as base │ ├── eur.json # All rates with EUR as base │ └── ... └── other/ # Utility scripts ├── cache-jsdelivr-api.js ├── currencycountry.js ├── getdate-args.js ├── isocodes.js └── makemergecurr.js ``` -------------------------------- ### Package Contents Structure Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md Illustrates the directory structure and key JSON files included in the npm package tarball. ```text /v1/ ├── currencies.json # All currency codes and names ├── currencies.min.json # Minified version ├── country.json # Country-to-currency mappings ├── package.json # npm metadata (updated with version) ├── index.js # Empty file (required for npm) └── currencies/ ├── usd.json # USD as base, all rates ├── usd.min.json ├── eur.json # EUR as base, all rates ├── eur.min.json ├── btc.json # BTC as base, all rates ├── btc.min.json └── {code}.json # One per supported currency (100+ codes) ``` -------------------------------- ### List all supported currency codes and names Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/DOCUMENTATION_INDEX.md This endpoint retrieves a list of all supported currency codes and their corresponding names. It supports filtering by date and output format. ```APIDOC ## GET /currencies ### Description List all supported currency codes and names. ### Method GET ### Endpoint /currencies ### Parameters #### Query Parameters - **date** (string) - Optional - Date parameter: `latest` or `YYYY-MM-DD`. - **format** (string) - Optional - Format options: `.json` (prettified) or `.min.json` (minified). ### Response #### Success Response (200) - **data** (object) - Contains currency codes and names. ### Response Example { "example": "{\"usd\": \"United States Dollar\", \"eur\": \"Euro\"}" } ``` -------------------------------- ### Error Handling for Data Sources Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/data-sources.md Illustrates different error handling strategies for data fetching. Source 1 halts the pipeline on error, while Sources 2 and 3 return empty objects. ```javascript // Source 1: Throws on error (fatal) let currDataObj = await getCurrData(currLink) // Source 2: Returns {} on error (non-fatal) let currDataObj3 = (...) ? toLowerCaseKeysBaseCurr(...) : {} // Source 3: Returns {} on error (non-fatal) let cryptoDataObj = (...) ``` -------------------------------- ### Document Map Overview Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/README.md This diagram illustrates the organizational structure of the exchange-api documentation, showing the relationships between different markdown files and their primary topics. ```markdown DOCUMENTATION_INDEX.md ← Navigation & quick reference ↓ PROJECT_OVERVIEW.md ← What is exchange-api? ├─ endpoints.md ← How to use the API ├─ types.md ← Data structures ├─ configuration.md ← Setup & CI/CD ├─ data-sources.md ← Where data comes from ├─ migration.md ← Upgrading from v0 └─ api-reference/ ├─ currscript.md ← Implementation details ├─ npm-package.md ← Publishing & versioning └─ utility-scripts.md ← Helper tools ``` -------------------------------- ### Cryptocurrency Prices Environment Variable Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/data-sources.md Environment variable for the URL of the cryptocurrency price API. ```bash cryptolink = {URL} ``` -------------------------------- ### Package Name Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md The full name of the npm package, including the scope. ```text @fawazahmed0/currency-api ``` -------------------------------- ### Create Gzip Compressed Archive Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/configuration.md Compresses the tar archive using gzip with maximum compression settings. ```bash 7z a package.tar.gz package.tar -tgzip -mx=9 -aoa -mfb=258 -mmt=on ``` -------------------------------- ### Fetch from CDN (Browser/Node.js) Source: https://github.com/fawazahmed0/exchange-api/blob/main/_autodocs/api-reference/npm-package.md A reusable JavaScript function to fetch exchange rates between two currencies from the CDN. Works in both browser and Node.js environments. ```javascript // No installation needed async function getExchangeRate(from, to) { const url = `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/${from}.json`; const response = await fetch(url); const data = await response.json(); return data[from][to]; } const rate = await getExchangeRate('usd', 'eur'); console.log('1 USD = ? EUR:', rate); ```