Creating a REST API Backend using Node.js, Express and Postgres

09 May, 2022
JavaScript Backend can be developed using Node.js, Express, and Postgres. This backend can do Query operations on the PostgreSQL database and provide the status or data on the REST API.
Installation Requirement:
Node.js:Install the Node.js on WindowsInstall the Node.js on LinuxPostgreSQL:Install Postgres on WindowsInstall Postgres on LinuxInstall Postgres on Mac
Node.js:Install the Node.js on WindowsInstall the Node.js on Linux
Install the Node.js on Windows
Install the Node.js on Linux
PostgreSQL:Install Postgres on WindowsInstall Postgres on LinuxInstall Postgres on Mac
Install Postgres on Windows
Install Postgres on Linux
Install Postgres on Mac
Testing for Successful Installation:
Node.js:Open Command Prompt or Terminal and type:node -v The output must show some version number example:v12.14.0 Note: If it shows command not found then node.js is not installed successfully.Postgres:Windows : Search for SQL Shell, if found the Installation is successful.Linux or Mac: Type the command below: which psql Note: If output present then it is installed successfully.
Node.js:Open Command Prompt or Terminal and type:node -v The output must show some version number example:v12.14.0 Note: If it shows command not found then node.js is not installed successfully.
Open Command Prompt or Terminal and type:node -v The output must show some version number example:v12.14.0 Note: If it shows command not found then node.js is not installed successfully.
node -v 
The output must show some version number example:
v12.14.0 
Note: If it shows command not found then node.js is not installed successfully.
Postgres:Windows : Search for SQL Shell, if found the Installation is successful.Linux or Mac: Type the command below: which psql Note: If output present then it is installed successfully.
Windows : Search for SQL Shell, if found the Installation is successful.
Linux or Mac: Type the command below: which psql Note: If output present then it is installed successfully.
 which psql 
Note: If output present then it is installed successfully.
Steps to Setup Database:
Open the PostgresSQL Shell
Type the Database Credentials for local Setup or press enter in case you want to go with default values as shown below:
Create the database using:create database gfgbackend;     
create database gfgbackend;     
Switch to this database using:\c gfgbackend;
\c gfgbackend;
Create a test table using:create table test(id int not null); 
create table test(id int not null); 
Insert values into test table using:insert into test values(1);  
insert into test values(2);
insert into test values(1);  
insert into test values(2);
Now try to validate whether the data is inserted into table using:select * from test;
select * from test;
Steps to Create a Backend:
Go to the Directory where you want to create project
Initialize the Node Project using:npm init
npm init
Type the name of Project and Other Details or Press Enter if you want to go with Default
Install express using npmnpm install --save express
npm install --save express
Install the node-postgres Client using npmnpm install --save pg
npm install --save pg
Install the postgres module for serializing and de-serializing JSON data in to hstore format using npm. npm install --save pg-hstore    
 npm install --save pg-hstore    
Create a file index.js as entry point to the backend.
Now Install body-parser using npmnpm install --save body-parser
npm install --save body-parser
Now add the below code to index.js file which initiates the express server, creates a pool connection and also creates a REST API ‘/testdata’. Don’t forget to add your Password while pool creation in the below code.// Entry Point of the API Server   const express = require('express');  /* Creates an Express application.    The express() function is a top-level    function exported by the express module.*/const app = express();const Pool = require('pg').Pool;  const pool = new Pool({    user: 'postgres',    host: 'localhost',    database: 'gfgbackend',    password: 'postgres',    dialect: 'postgres',    port: 5432});    /* To handle the HTTP Methods Body Parser    is used, Generally used to extract the    entire body portion of an incoming    request stream and exposes it on req.body */const bodyParser = require('body-parser');app.use(bodyParser.json())app.use(bodyParser.urlencoded({ extended: false }));    pool.connect((err, client, release) => {    if (err) {        return console.error(            'Error acquiring client', err.stack)    }    client.query('SELECT NOW()', (err, result) => {        release()        if (err) {            return console.error(                'Error executing query', err.stack)        }        console.log("Connected to Database !")    })})  app.get('/testdata', (req, res, next) => {    console.log("TEST DATA :");    pool.query('Select * from test')        .then(testData => {            console.log(testData);            res.send(testData.rows);        })})  // Require the Routes API  // Create a Server and run it on the port 3000const server = app.listen(3000, function () {    let host = server.address().address    let port = server.address().port    // Starting the Server at the port 3000})
// Entry Point of the API Server   const express = require('express');  /* Creates an Express application.    The express() function is a top-level    function exported by the express module.*/const app = express();const Pool = require('pg').Pool;  const pool = new Pool({    user: 'postgres',    host: 'localhost',    database: 'gfgbackend',    password: 'postgres',    dialect: 'postgres',    port: 5432});    /* To handle the HTTP Methods Body Parser    is used, Generally used to extract the    entire body portion of an incoming    request stream and exposes it on req.body */const bodyParser = require('body-parser');app.use(bodyParser.json())app.use(bodyParser.urlencoded({ extended: false }));    pool.connect((err, client, release) => {    if (err) {        return console.error(            'Error acquiring client', err.stack)    }    client.query('SELECT NOW()', (err, result) => {        release()        if (err) {            return console.error(                'Error executing query', err.stack)        }        console.log("Connected to Database !")    })})  app.get('/testdata', (req, res, next) => {    console.log("TEST DATA :");    pool.query('Select * from test')        .then(testData => {            console.log(testData);            res.send(testData.rows);        })})  // Require the Routes API  // Create a Server and run it on the port 3000const server = app.listen(3000, function () {    let host = server.address().address    let port = server.address().port    // Starting the Server at the port 3000})
Now, start the backend server using:node index.js
node index.js
Open Browser and try to router to:http://localhost:3000/testdataNow, you can see the data from test table as follows:
http://localhost:3000/testdata
Now, you can see the data from test table as follows:
kimoji
JavaScript-Misc
Node.js-Misc
JavaScript
Node.js
PostgreSQL
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.