Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Build a RESTful API Using Node, Express, and MongoDB ?
Next article icon

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

Last Updated : 16 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

  • Install the Node.js on Windows
  • Install the Node.js on Linux

PostgreSQL: 

  • 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.

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.



Next Article
How to Build a RESTful API Using Node, Express, and MongoDB ?

S

shantanujoshi
Improve
Article Tags :
  • JavaScript
  • Node.js
  • PostgreSQL
  • Web Technologies
  • JavaScript-Misc
  • Node.js-Misc

Similar Reads

  • 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 intak
    4 min read
  • Real-Time Auction Platform using Node and Express.js
    The project is a Real-Time Auction Platform developed using Node.js Express.js and MongoDB database for storing details where users can browse different categories of products, view ongoing auctions, bid on items, and manage their accounts. The platform also allows sellers to list their products for
    12 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
    6 min read
  • How to create routes using Express and Postman?
    In this article we are going to implement different HTTP routes using Express JS and Postman. Server side routes are different endpoints of a application that are used to exchange data from client side to server side. Express.js is a framework that works on top of Node.js server to simplify its APIs
    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
    6 min read
  • REST API CRUD Operations Using ExpressJS
    In modern web development, REST APIs enable seamless communication between different applications. Whether it’s a web app fetching user data or a mobile app updating profile information, REST APIs provide these interactions using standard HTTP methods. What is a REST API?A REST API (Representational
    7 min read
  • Steps to Create an Express.js Application
    Creating an Express.js application involves several steps that guide you through setting up a basic server to handle complex routes and middleware. Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Here’s a
    10 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, sha
    10 min read
  • Using Restify to Create a Simple API in Node.js
    Restify is an npm package that is used to create efficient and scalable RESTful APIs in Nodejs. The process of creating APIs using Restify is super simple. Building a RESTful API is a common requirement for many web applications. Restify is a popular Node.js framework that makes it easy to create RE
    6 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 Docume
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences