Open In App

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

Last Updated : 16 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: Postgresql Database shell

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;

Insert and Select Statement

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 npm init details

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: REST API DATA

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

How to Implement Search and Filtering in a REST API with Node.js and Express.js ?
Search and filtering are very basic features that an API must possess to serve data to the client application efficiently. By handling these operations on the server-side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance. In this article, we'll see how we can build a Node.js RE
5 min read
Node.js Building simple REST API in express
Let's have a brief introduction about the Express framework before starting the code section:Express: It is an open-source NodeJs web application framework designed to develop websites, web applications, and APIs in a pretty easier way. Express helps us to handle different HTTP requests at specific routes.As it is NodeJs web framework so make sure
2 min read
How to generate document with Node.js or Express.js REST API?
Generating documents with Node and Express REST API is an important feature in the application development which is helpful in many use cases. In this article, we will discuss two approaches to generating documents with Node.js or Express.js REST API. Table of Content Document Generation using PdfKit libraryDocument Generation using Puppeteer libra
3 min read
Build a document generator with Express using REST API
In the digital age, the need for dynamic and automated document generation has become increasingly prevalent. Whether you're creating reports, invoices, or any other type of document, having a reliable system in place can streamline your workflow. In this article, we'll explore how to build a Document Generator using Node and Express, two powerful
2 min read
REST API using the Express to perform CRUD (Create, Read, Update, Delete)
In this article, we are going to learn how can we build an API and how can we perform crud operations on that. This will be only backend code and you must know JavaScript, NodeJs, Express.js, and JSON before starting out this. This Node.js server code sets up a RESTful API for managing student data. It provides endpoints for performing CRUD (Create
9 min read
Health Tracker App Backend Using Node and Express.js
A Health Tracker App is a platform that allows users to log and monitor various data of their health and fitness. In this article, we are going to develop a Health Tracker App with Node.js and Express.js. that allows users to track their health-related activities such as exercise, meals, water intake, and sleep. Prerequisites:Node.jsExpress.jsMongo
4 min read
Difference Between REST API and RPC API
REST and RPC are design architectures widely used in web development to build APIs (Application Programming Interface). It is a set of instructions that permits two systems to share resources and services. The client creates a request to the server that responds to it with data in JSON or XML format. REST APIs It stands for Representational State T
3 min read
Know the Difference Between REST API and RESTful API
APIs (Application Programming Interface) act as an interface between two applications to interact and provide the relevant data. It uses a set of protocols using which the operation is done. Salesforce was the first organization to officially launch API, followed by eBay and Amazon. Also, 60% of transactions made on eBay use their APIs. If we talk
5 min read
Difference between REST API and SOAP API
REST (Representational State Transfer) and SOAP (Simple Object Access Protocol) are the most common methods for communications These services enable web to communicate with the servers with HTTP protocol. REST is architectural style that works over HTTP for communication while SOAP is a protocol with strict standards and is helpful for complex syst
2 min read
Build a Social Media REST API Using Node.js: A Complete Guide
Developers build an API(Application Programming Interface) that allows other systems to interact with their Application’s functionalities and data. In simple words, API is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data and interact with each other.API is a service created
15+ min read
What is REST API in Node.js ?
REST (Representational State Transfer) is an architectural style for designing networked applications. A RESTful API is an API that adheres to the principles of REST, making it easy to interact with and understand. In this article, we'll explore what REST API is in the context of Node.js, its principles, and how to create one. Table of Content Unde
11 min read
PostgreSQL - Reset Password For Postgres
In this article, we will look into the step-by-step process of resetting the Postgres user password in case the user forgets it. PostgreSQL uses the pg_hba.conf configuration file stored in the database data directory (e.g., C:\Program Files\PostgreSQL\12\data on Windows) and is used to handle user authentication. The hba in pg_hba.conf means host-
2 min read
How to Manage Postgres Failover with ZooKeeper
PostgreSQL is one of the most popular open-source relational database management systems known for its reliability. In highly available systems, ensuring that databases remain operational during hardware failures, network issues or other critical disruptions is essential. In this article, we will explore how ZooKeeper helps manage PostgreSQL failov
5 min read
How To Enable CDC With Postgres On Amazon RDS
Change Data Capture (CDC) allows organizations to track real-time changes in their databases by enabling timely data integration and analytics. In this article will explain the steps to enable CDC in your Amazon RDS PostgreSQL instance, covering configuration, replication slot creation, and setting up publications and subscriptions. How To Enable C
4 min read
What is a Postgres Hosting?
Postgres hosting gives businesses and developers a PostgreSQL database to host the issues of configuration, maintenance, and scaling that are supposed to be handled by the hosting provider. Options such as auto backups, Database performance tuning and the high availability of Postgres hosting make database manageability easy. What is a Postgres Hos
6 min read
How to Build a RESTful API Using Node, Express, and MongoDB ?
This article guides developers through the process of creating a RESTful API using Node.js, Express.js, and MongoDB. It covers setting up the environment, defining routes, implementing CRUD operations, and integrating with MongoDB for data storage, providing a comprehensive introduction to building scalable and efficient APIs. Prerequisites:NodeJS
6 min read
Creating a simple JSON based API using Node.js
API (Application Programming Interface) results are commonly used by applications, sometimes to withdraw information from their huge databases, check the status of a particular data, or sometimes they depend on third-party APIs to display additional information related to users. Here we will make a simple public JSON based Chemistry API, which can
3 min read
Travel Planning App API using Node & Express.js
In this article, we’ll walk through the step-by-step process of creating a Travel Planning App With Node and ExpressJS. This application will provide users with the ability to plan their trips by searching for destinations, booking flights and hotels, submitting reviews, receiving notifications, sharing their trips on social media, and processing p
10 min read
How to create a REST API using Java Spring Boot
Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems
6 min read
How to create Covid19 Country wise status project using REST API ?
Today, All Countries in the world fighting with Coronavirus. Every day, Coronavirus cases rising rapidly. It is important for all to keep track of COVID Cases daily and should try to keep himself/herself safe. We have made small web apps that will tell you the total no of cases, new cases, new death, recovery, etc. to the user. You have to just ent
7 min read
Consuming a REST API ( Github Users ) using Fetch - React Client
In this article, you will learn to develop a React application, which will fetch the data from a REST API using Fetch. We will use GitHub Users API to fetch the user's public information with their username. You can find the API reference and source code links at the end of this article. Prerequisites:NodeJS or NPMReactJSSteps to Create the React A
3 min read
How to create a REST API using json-server npm package ?
This article describes how to use the json-server package as a fully working REST API. What is json-server? json-server is an npm(Node Package Manager) module/package, used for creating a REST API effortlessly. Data is communicated in JSON(JavaScript Object Notation) format between client and server. Installation: Execute the below command in your
4 min read
CRUD Operation in REST API using PHP
A REST (Representational State Transfer) API allows communication between a client and a server through HTTP requests. PHP, a widely used server-side scripting language, is well-suited for creating REST APIs due to its simplicity and rich ecosystem. This article provides a step-by-step guide on building a REST API in PHP, covering various approache
5 min read
Creating a PDF Merger using Javascript and Express Js
Certain forms require us to upload multiple documents as a single PDF file. We merge those files using any online PDF merger in such cases. This article focuses on creating our own PDF merger using Javascript and Express JS. Prerequisites:NPM and Node JsExpress JsSyntax: import PDFMerger from 'pdf-merger-js'; const merger = new PDFMerger();Steps to
3 min read
RESTful Blogging API with Node and Express.js
Blogs Websites have become very popular nowadays for sharing your thoughts among the users over internet. In this article, you will be guided through creating a Restful API for the Blogging website with the help of Node, Express, and MongoDB. Prerequisites:Node JS & NPMExpress JSMongoDBApproach to Creating Restful Blogging App:To create a Restf
6 min read
Building a REST API with PHP and MySQL
This brief tutorial is a step-by-step guide on how to develop a REST API using PHP and MySQL. REST API will implement HTTP commands (Get, Post, Put, DELETE) and response will be in form of JSON. For development setup, we will be using the XAMPP while for testing of the API, we will use the Postman app. Steps to Build REST API with PHP and MySQLStep
4 min read
Creating Socket.IO Server using Express Generator
Socket.IO is a library for real-time communication between the server and the client. In Socket.IO, the headers are shared only once and it also works on the top of the TCP layer. Web Sockets are the base of the Socket.IO library. It is easier to implement the Socket.IO in express applications that are not formed with the express-generator. Socket.
3 min read
How to Resolve form-data is getting undefined in Node/Express API ?
Working with forms and handling data submissions is a basic requirement in web development. When using Node and Express for building APIs, you might get an error that the FormData object is undefined. In this article, we'll explore how to resolve form data getting undefined in a Node/Express API. The FormData object is a part of the Web API and is
3 min read
How to Call an API Continuously from Server Side Itself in Node.js/Express.js ?
To call an API continuously from the server side in a Node.js/Express.js environment, you can implement a periodic task that executes at regular intervals. This is typically done using functions such as setInterval, which is built into Node.js for scheduling repeated operations. There are multiple ways to make API calls from a Node.js server, depen
3 min read
How to use TypeScript to build Node.js API with Express ?
TypeScript is a powerful version of JavaScript that incorporates static typing and other features, making it easy to build and maintain large applications. Combined with Node.js and Express, TypeScript can enhance your development experience by providing better type safety and tools. This guide will walk you through the Node.js API using Express an
4 min read
three90RightbarBannerImg