REST API with Express.js
Node.js

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Before Node.js JavaScript was only used in the client-side, but now with Node.js it is possible to use JavaScript also in the server-side. You can download Node.js from the page https://nodejs.org/en/.

As an asynchronous event driven JavaScript runtime, Node is designed to build scalable network applications.

Example make a folder and add a file named server.js inside that folder. Then add below code to the server.js file

  const http = require('http');

  const hostname = '127.0.0.1';
  const port = 3000;

  const server = http.createServer(
      function (req, res) {
          res.statusCode = 200;
          res.setHeader('Content-Type', 'text/plain');
          res.end('Hello World\n');
      }
  );

  server.listen(port, hostname, 
      function() {
          console.log(`Server running at http://${hostname}:${port}/`);
      }
  );
  
Then inside the folder give a command node server.js and then with your browser navigate to url localhost:3000. So now you have a simple "web-server".

npm

npm is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. If you have installed node.js, you already have npm also.

You can manage locally installed npm packages with the package.json file.

Example
Create a folder named test and inside that folder give a command npm init and if you just press ENTER to all questions, you will have below package.json file

    {
      "name": "test",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
  
Then if you example would like to use MySQL in your application, you can add below lines to package.json
    "dependencies": {
        "mysql": "^2.16.0"
    }
  
if you then execute command npm install, you will get the packages which MySQL needs.

Instead of writing to the the package.json file, you can also execute command npm install mysql --save

You can find useful information about mysql-npm from https://www.npmjs.com/package/mysql#introduction

Volta

Volta is a tool which you can use to manage JavaScript command-line tools like node and npm. You can download it from https://volta.sh/.

You can install several versions of node.js and here are some examples about the commands

  1. volta install node@lts # install latest lts version
  2. volta install node@16.9.0 # install specific version 16.9.0
  3. volta install node@12 # install the latest v12 release
And you can check which versions you have installed with the command
volta list node

If you want to set your project to use a node version which is not your default, you can set it by executing below command inside your project folder
volta pin node@16.14.0 (version 16.14.0 is just an example)

Express.js

Express.js is a backend web application framework for Node.js. Express is designed for building web applications and APIs. Express provides various features that make web application development fast and easy which otherwise takes more time using only Node.js.

You can read the basic things about Express from this webpage https://www.freecodecamp.org/news/express-explained-with-examples-installation-routing-middleware-and-more/

And you can read about middlewares from this page https://expressjs.com/en/guide/writing-middleware.html

Routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on)

Here is an example about a route for GET method

app.get('/example',
    function(request,response){
        response.send('I am example');
        console.log('I am example');
    }
);
The first parameter (/example) is the route and the function is the callback. And the url might be something like http://localhost:3000/example. If you add parameters after the route like this
app.get('/example/:name',
    function(request,response){
        response.send('Hello '+request.params.name);
    }
);
Then you have to send the request like this http://localhost:3000/example/Jim

And if you need to use two parameters in GET-request, you can use this syntax

app.get('/example2/:firstName/:lastName',
    function(request, response){
        response.send('Hello '+request.params.firstName+" "+request.params.lastName);
    }
);
Then you can send the request like this http://localhost:3000/example2/Jim/Jones

And also you can use below syntax for two parameters GET-request
app.get('/example2/:firstName&:lastName',
    function(request, response){
       response.send('Hello '+request.params.firstName+" "+request.params.lastName);
    }
);
Then you can send the request like this http://localhost:3000/example2/Jim&Jones

Here is an example about route for POST method

app.post('/',
    function(request,response){
        response.send(request.body);
        console.log(request.body);
    }
);
Above function will response with the same data that you send inside the HTTP body.

Middleware

Middleware functions are executed after every incoming request. Below is an example about middleware function

app.use(
    function(req,res,next){
        console.log('The common middleware called');
        next();
    }
);
So, below middleware is executed after every request to every routes. You can also add a path to the middleware.
app.use('/example',
    function(req,res,next){
        console.log('The example middleware called');
        next();
    }
);
So, the above middleware is executed when request to path example comes.

The next function is a function in the Express router which is used to execute the other middleware functions succeeding the current middleware.

SQL Queries

Here is an example about SQL query which will return the name of a book based on the id given in the htpp-request.

const db = require('../database');

app.get('/name_v1/:id?',
 function(request, response) {
  var id=request.params.id;
  db.query('select name from book where id_book=?', [id], 
    function (err, dbResult){
      if (err) {
        response.json(err);
      } else {
        response.json(dbResult);
      }
    })
 }
);
And here is the same example, so that the database query is separated to it's own function named getById
const db = require('../database');

app.get('/name_v2/:id?',
 function(request, response) {
    getById(request.params.id, 
      function(err, dbResult) {
        if (err) {
          response.json(err);
        } else {
          response.json(dbResult);
        }
      })
 }
);

const getById = function(id, callback) {
  return db.query('select name from book where id_book=?', [id], callback);
}
In above examples there is a file named database.js, which includes the connection parameters for the database.

You can read more details about the node.js driver for mysql from https://www.npmjs.com/package/mysql

Response format

You can choose to send the response as a JSON array or as a JSON object or as a string.

Example you have made this kind of SQL-query select CONCAT(fname," ",lname) AS fullname from person where id_person=6. Then you can choose which kind of response to send.

response.json(dbResult);

Then the response is a JSON array like this:
[
    {
        "fullname": "Jim Smith"
    }
]
response.json(dbResult[0]);

Then the response is a JSON object like this:

{
    "fullname": "Jim Smith"
}
response.json(dbResult[0].fullname);

Then the response is a string like this:

"Jim Smith"
response.send(dbResult[0].fullname);

Then the response is a string like this:

Jim Smith



Toggle Menu