Creating a REST API Backend using Node.js, Express and Postgres
Last Updated :
16 Sep, 2024
Creating a REST API backend with Node.js, Express, and PostgreSQL offers a powerful, scalable solution for server-side development. It enables efficient data management and seamless integration with modern web applications.
This backend can do Query operations on the PostgreSQL database and provide the status or data on the REST API.
Installation Requirement:
Node.js:
PostgreSQL:
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.
Steps to Setup Database
Step 1: Open the PostgreSQL Shell
Step 2: Type the Database Credentials for local Setup or press enter in case you want to go with default values as shown below: 
Step 3: Create the database using:
create database gfgbackend;
Step 4: Switch to this database using:
\c gfgbackend;
Step 5: Create a test table using:
create table test(id int not null);
Step 6: Insert values into test table using:
insert into test values(1);
insert into test values(2);
Step 7: Now try to validate whether the data is inserted into table using:
select * from test;

Steps to Create a Backend
Step 1: Go to the Directory where you want to create project
Step 2: Initialize the Node Project using:
npm init
Step 3: Type the name of Project and Other Details or Press Enter if you want to go with Default 
Step 4: Install express using npm
npm install --save express
Step 5: Install the node-postgres Client using npm
npm install --save pg
Step 6: Install the postgres module for serializing and de-serializing JSON data in to hstore format using npm.
npm install --save pg-hstore
Step 7: Create a file index.js as entry point to the backend.
Now, Install body-parser using npm
npm install --save body-parser
Example: 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.
JavaScript
// Filename - index.js
// 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 3000
const server = app.listen(3000, function () {
let host = server.address().address
let port = server.address().port
// Starting the Server at the port 3000
})
Step to Run the Backend: Now, start the backend server using:
node index.js
Open Browser and try to router to:
http://localhost:3000/testdata
Now, you can see the data from test table as follows: 
Conclusion
Creating a REST API backend using Node.js, Express, and PostgreSQL provides a scalable and efficient solution for building modern web applications. This stack offers easy integration, robust data handling, and flexibility, making it ideal for backend development needs.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
REST API Introduction REST API stands for REpresentational State Transfer API. It is a type of API (Application Programming Interface) that allows communication between different systems over the internet. REST APIs work by sending requests and receiving responses, typically in JSON format, between the client and server.
7 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read