In this post, you will see code samples of how to build a currency converter API with nodejs & typescript. This post contains code samples and a link to the Github repo where you can find all the code with setup instructions.
Currency converter API with nodejs & Typescript
The goal of this post is to show how you can setup and run a simple currency conversion API using NodeJS, express and Typescript. To achieve that, you will be building a simple nodejs REST API that exposes 3 endpoints, in addition the ping and healthcheck endpoints. The code presented here uses the free exchange rate API found here: ExchangeRate-API – Free & Pro Currency Converter API
Healthcheck endpoints
app.get('/', (req: Request, res: Response) => {
res.status(200).send({"message": "Hello Currency API with exchangeRate-API"});
});
app.get("/healthCheck", (req: Request, res: Response) => {
res.status(200).send("OK");
});
Default endpoint based on .env variable
app.get("/exchangeRates/default", (req: Request, res: Response) => {
const url = `${BASE_URL}/${API_KEY}/latest/${COUNTRY_CODE_DEFAULT}`;
fetch(url)
.then(resp => resp.json())
.then(data => {
res.status(200).send(data);
});
});
Currency code based endpoint
app.get("/exchangeRates/:country_code", (req: Request, res: Response) => {
const cCode = (req.params && req.params.country_code) ?? COUNTRY_CODE_DEFAULT;
const url = `${BASE_URL}/${API_KEY}/latest/${cCode}`;
fetch(url)
.then(resp => resp.json())
.then(data => {
res.status(200).send(data);
});
});
Convert from currency, amount to currency endpoint
app.get("/convert/:from_code/:amount/to/:to_code", async (req: Request, res: Response) => {
const fromCode = req.params && req.params.from_code;
let toCode = req.params && req.params.to_code;
let amount = req.params && req.params.amount;
if(!fromCode || !toCode || !amount) {
res.status(400).send("Insufficient params supplied");
}
//const amount
const url = `${BASE_URL}/${API_KEY}/latest/${fromCode}`;
const resp1 = await fetch(url);
const data = await resp1.json();
fetch(url)
.then(resp => resp.json())
.then(data => {
const conversionRate = data.conversion_rates[toCode.toUpperCase()];
const convertedVal = Number(amount) * Number(conversionRate);
res.status(200).send({"conversion": convertedVal});
});
});
Code for your entire .ts file
import express, { Express, Request, Response } from 'express';
import fetch from 'node-fetch';
import "dotenv/config";
import { configDotenv } from 'dotenv';
const app: Express = express();
const port = 3000;
configDotenv();
app.use(express.json());
app.get('/', (req: Request, res: Response) => {
res.status(200).send({"message": "Hello Currency API with exchangeRate-API"});
});
app.get("/healthCheck", (req: Request, res: Response) => {
res.status(200).send("OK");
});
// your API key
const API_KEY = process.env.EXCHANGERATES_API_KEY;
const COUNTRY_CODE_DEFAULT = process.env.COUNTRY_CODE_DEFAULT ?? "aud";
const BASE_URL = "https://v6.exchangerate-api.com/v6/";
app.get("/exchangeRates/default", (req: Request, res: Response) => {
const url = `${BASE_URL}/${API_KEY}/latest/${COUNTRY_CODE_DEFAULT}`;
fetch(url)
.then(resp => resp.json())
.then(data => {
res.status(200).send(data);
});
});
app.get("/exchangeRates/:country_code", (req: Request, res: Response) => {
const cCode = (req.params && req.params.country_code) ?? COUNTRY_CODE_DEFAULT;
const url = `${BASE_URL}/${API_KEY}/latest/${cCode}`;
fetch(url)
.then(resp => resp.json())
.then(data => {
res.status(200).send(data);
});
});
app.get("/convert/:from_code/:amount/to/:to_code", async (req: Request, res: Response) => {
const fromCode = req.params && req.params.from_code;
let toCode = req.params && req.params.to_code;
let amount = req.params && req.params.amount;
if(!fromCode || !toCode || !amount) {
res.status(400).send("Insufficient params supplied");
}
//const amount
const url = `${BASE_URL}/${API_KEY}/latest/${fromCode}`;
const resp1 = await fetch(url);
const data = await resp1.json();
fetch(url)
.then(resp => resp.json())
.then(data => {
const conversionRate = data.conversion_rates[toCode.toUpperCase()];
const convertedVal = Number(amount) * Number(conversionRate);
res.status(200).send({"conversion": convertedVal});
});
});
app.listen(port, () => {
console.log(`Listening on port ${port}`)
})
package.json and tsconfig.json file
{
"name": "currency_conv_api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"temp": "echo temp",
"devRun": "nodemon ./src/index.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/dotenv": "^8.2.0",
"typescript": "^5.1.3"
},
"dependencies": {
"@types/express": "^4.17.17",
"@types/node": "^20.2.5",
"@types/node-fetch": "^2.6.4",
"@types/nodemon": "^1.19.2",
"express": "^4.18.2",
"node-fetch": "^2.6.11",
"nodemon": "^2.0.22",
"ts-node": "^10.9.1",
"dotenv": "^16.1.4"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "CommonJS",
"outDir": "./dist",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
"resolveJsonModule": true,
}
}
That’s all you need to get a working currency converter REST API.
Conclusion
Hope you found this blogpost useful and you can find the full source code for this repo here on Github which also has instructions to setup and run this repo. You can obtain a newscatcher API key from here.
If you find any of my posts useful and want to support me, you can buy me a coffee 🙂
https://www.buymeacoffee.com/bhumansoni
While you are here, maybe try one of my apps for the iPhone.
Products – My Day To-Do (mydaytodo.com)
Have a read of some of my other posts on AWS
Deploy NodeJS, Typescript app on AWS Elastic beanstalk – (mydaytodo.com)
How to deploy spring boot app to AWS & serve via https – My Day To-Do (mydaytodo.com)
Some of my other posts on Javascript …
What is Javascript event loop? – My Day To-Do (mydaytodo.com)
How to build a game using Vanilla Javascript – My Day To-Do (mydaytodo.com)
Vanilla Javascript: Create Radio Buttons (How-To) – Bhuman Soni (mydaytodo.com)
Java Spring Boot & Vanilla Javascript solution – My Day To-Do (mydaytodo.com)
Vanilla Javascript: Create Radio Buttons (How-To) – Bhuman Soni (mydaytodo.com)
0 Comments