Press "Enter" to skip to content

The easiest REST API with NodeJS + ExpressJS + TypeScript

I will show you in this article how to build totally the easiest REST API build with NodeJS with Express plugin with TypeScript in place. This may sound as hard task to do, but with this short tutorial you will get everything working in just a few easy steps. You will be able to proceed further on your own.

The easiest nodejs REST API

What can be the purpose of building small back-end API with NodeJS? It’s very simple, just check example below:

You are maybe 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 date from a few columns, do mapping function, agregate 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 small REST API in NodeJS + ExpressJS, do the ajax call to external API with data from data base, convert and map it there, and then return to you front-end application.

This is called a facade pattern. So you are creating an additional functionality before your main application, to handle some calculations.

OK, let’s stop talking and start doing ๐Ÿ™‚ Check code described below on our Gitlab account HERE.

  1. 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):
    The easiest nodejs REST API The easiest nodejs REST API
  2. Start typing in terminal commands:
  3. npm init – this will initialize the NodeJS.
  4. When you will be asked with question: entry point: (index.js) type: index.ts
  5. 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.
  6. 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..
  7. 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:
    The easiest nodejs REST API

  8. 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 “/”.

  9. Type now in terminal window npm run dev to run your application. You should see in the terminal window something similar to image below:
  10. Then type in your browser url: http://localhost:3010/adn you will response sent by method res.send("PUBLIC API"); from your code.
  11. Let’s make now some POST request to your 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
      }
    ]
    
  12. Let’s create a new typescript file in our root directory with name “mapper.ts”. Our root directory should look like on image below:
    The easiest nodejs REST API
  13. 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);
        });
    }
  14. 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();
    });
  15. The full code of 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}`)
  16. We must open now POSTMAN application 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:
    The easiest nodejs REST API
  17. As you can see on image above, we got the response with sum equal to 14922:
    {
        "sum": 14922
    }

 

You can find full code of this small application 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 ๐Ÿ™‚