I will show you in this article how to build totally simplest REST API, build with NodeJS with Express plugin with TypeScript. This may sound as a hard task to do, but with this short tutorial you will get whole NodeJS rest API working in just a few easy steps. You will be able to proceed further on your own.
Table of Contents
NodeJS simple REST API – the purpose explanation
What can be the purpose of building simple REST API with NodeJS? It’s very simple, just check example below:
Let’s say that you are the front-end developer and you need to do some mapping functionality before displaying data received from data base. But in there response there is 100 000 rows, each with 30 columns. You need to take only a data from a few columns, do mapping function, aggregate the data and display to user the final results.
Of course, in ideal world, there would be a back-end developer who can deal with that problem. But in real world, you will need to make it working just by yourself.
There is nothing easiest than building the simple REST API in NodeJS + ExpressJS, take data from data base, convert and map it there in NodeJS API, and then return to you front-end application.
This is called a facade pattern with simple NodeJS rest API. So you are creating an additional functionality before your main application, to handle some operations based on incoming data.
How to build the simplest NodeJS API
OK, let’s stop talking and start doing ๐ Check code described below on our Gitlab account HERE.
- First create a new directory (new folder) and open there a new terminal window, this can be both a terminal window in your IDE like in VSCODE or normal windows’ CMD (start > write “CMD” > press enter > copy path to your directory > write in CMD: “cd YOUR_COPIED_PATH” > enter):
- Start typing in terminal commands:
npm init
– this will initialize the NodeJS.- When you will be asked with question:
entry point: (index.js)
type:index.ts
npm install --save ts-node @types/node typescript express body-parser @types/expressย
– this are packages need for the development. TS-NODE is a nodejs server which has type-script support embed by default.npm install --save-dev nodemon
– this will add as development dependency the nodemon package. It will restart the server automatically when some change in code of source files will be made. This is a really helpful package. Otherwise, you will have to manually restart the server after each code change..- When installation of all packages will finish, then just open a package.json file in your directory, and find “scripts” property, and add there: 2 lines of code
"start": "ts-node ./index.ts", "dev": "nodemon ./index.ts",
like on image below:
- Create in root directory the file index.ts with content as following:
import * as express from 'express'; import * as bodyParser from 'body-parser'; const app = express(); const PORT = 3010; app.use(bodyParser.json()); app.get("/", (req, res, next) => { res.send("PUBLIC API"); next(); }); app.listen(PORT); console.log(`Server listen on port: ${PORT}`)
First, you import needed packages – express and bodey-parser (which can be useful when you will send a JSON data to that API later, depending on your functionality).
Next you initialize app with body-parser (this is a kind of interpreter used later for JSON body in POST requests), and write first “GET” endpoint, with root path “/”.
- Type now in terminal window
npm run dev
to run your application. You should see in the terminal window something similar to image below:
- Then type in your browser url:
http://localhost:3010/
adn you will response sent by methodres.send("PUBLIC API");
from your code. - Let’s make now some POST request to our simple NodeJS rest API and simulate processing of data.
In our example we will create an endpoint to which we send an array with list of employees and their salaries, like in JSON object below. Then we will need to calculate sum of their net salaries. For calculating the net salaries we will use tax threshold – everyone who earns more that 2500 gross, would pay 25% tax, everyone who earns below 2500, would pay 20% tax.[{ "name": "John", "salary": 2000 }, { "name": "Ann", "salary": 2578 }, { "name": "Thomas", "salary": 2376 }, { "name": "Eric", "salary": 1986 }, { "name": "Michael", "salary": 2747 }, { "name": "Albert", "salary": 2234 }, { "name": "Jackie", "salary": 2612 }, { "name": "Elton", "salary": 2115 } ]
- Let’s create a new typescript file in our root directory with name “mapper.ts”. Our root directory should look like on image below:
- Next, rewrite or copy and paste there code for calculating the sum of employee’s net salaries:
export type Employee = { name: string, salary: number } export const calcSumOfNetSaleries = (data: Employee[]): number => { const taxLevelLower = 0.2; const taxLevelHigher = 0.25; const taxThreshold = 2500; return data.map((employee) => employee.salary) .reduce((salariesSum, currSalary) => { const salaryMultiplier = currSalary > taxThreshold ? (1 - taxLevelHigher) : (1 - taxLevelLower); const salaryAfterTax = currSalary * salaryMultiplier; return Math.round(salariesSum + salaryAfterTax); }); }
- Next, let’s extend our index.ts code with below. Remember to put new code before
app.listen(PORT);
line:import { Employee, calcSumOfNetSaleries } from './mapper'; app.post('/sum-net-salaries', (req, res, next) => { const employees: Employee[] = req.body; const result: number = calcSumOfNetSaleries(employees); res.send({ sum: result }); next(); });
- The full code of our simple NodeJS rest API in index.ts file should look like:
import * as express from 'express'; import * as bodyParser from 'body-parser'; const app = express(); const PORT = 3010; app.use(bodyParser.json()); app.get("/", (req, res, next) => { res.send("PUBLIC API"); next(); }); import { Employee, calcSumOfNetSaleries } from './mapper'; app.post('/sum-net-salaries', (req, res, next) => { const employees: Employee[] = req.body; const result: number = calcSumOfNetSaleries(employees); res.send({ sum: result }); next(); }); app.listen(PORT); console.log(`Serven listen on port: ${PORT}`)
- We must open now POSTMAN application to test our NodeJS API and choose: POST request, type url:
http://localhost:3010/sum-net-salaries
copy JSON from point 11 into body input and
choose “raw” with type “JSON”.
Then press blue “SEND” button.
Everything should look like on image below:
- As you can see on image above, we got the response from our NodeJS API example with sum equal to 14922:
{ "sum": 14922 }
You can find full code of this small NodeJS api on our GitHub – click here.
OK, that’s everything ๐ I hope that this short tutorial was easy and helpful for you. Remember that I have used everywhere here the TypeScript syntax, so it might look a little bit different from old JavaScript in ES5 syntax, but it should be still easy to understand ๐